babylon.max.js 2.7 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565
  1. var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
  2. var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
  3. if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
  4. 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;
  5. return c > 3 && r && Object.defineProperty(target, key, r), r;
  6. };
  7. var __extends = (this && this.__extends) || function (d, b) {
  8. for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
  9. function __() { this.constructor = d; }
  10. __.prototype = b.prototype;
  11. d.prototype = new __();
  12. };
  13. var BABYLON;
  14. (function (BABYLON) {
  15. BABYLON.ToGammaSpace = 1 / 2.2;
  16. BABYLON.ToLinearSpace = 2.2;
  17. BABYLON.Epsilon = 0.001;
  18. var MathTools = (function () {
  19. function MathTools() {
  20. }
  21. MathTools.WithinEpsilon = function (a, b, epsilon) {
  22. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  23. var num = a - b;
  24. return -epsilon <= num && num <= epsilon;
  25. };
  26. MathTools.ToHex = function (i) {
  27. var str = i.toString(16);
  28. if (i <= 15) {
  29. return ("0" + str).toUpperCase();
  30. }
  31. return str.toUpperCase();
  32. };
  33. // Returns -1 when value is a negative number and
  34. // +1 when value is a positive number.
  35. MathTools.Sign = function (value) {
  36. value = +value; // convert to a number
  37. if (value === 0 || isNaN(value))
  38. return value;
  39. return value > 0 ? 1 : -1;
  40. };
  41. MathTools.Clamp = function (value, min, max) {
  42. if (min === void 0) { min = 0; }
  43. if (max === void 0) { max = 1; }
  44. return Math.min(max, Math.max(min, value));
  45. };
  46. return MathTools;
  47. }());
  48. BABYLON.MathTools = MathTools;
  49. var Color3 = (function () {
  50. function Color3(r, g, b) {
  51. if (r === void 0) { r = 0; }
  52. if (g === void 0) { g = 0; }
  53. if (b === void 0) { b = 0; }
  54. this.r = r;
  55. this.g = g;
  56. this.b = b;
  57. }
  58. Color3.prototype.toString = function () {
  59. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  60. };
  61. Color3.prototype.getClassName = function () {
  62. return "Color3";
  63. };
  64. Color3.prototype.getHashCode = function () {
  65. var hash = this.r || 0;
  66. hash = (hash * 397) ^ (this.g || 0);
  67. hash = (hash * 397) ^ (this.b || 0);
  68. return hash;
  69. };
  70. // Operators
  71. Color3.prototype.toArray = function (array, index) {
  72. if (index === undefined) {
  73. index = 0;
  74. }
  75. array[index] = this.r;
  76. array[index + 1] = this.g;
  77. array[index + 2] = this.b;
  78. return this;
  79. };
  80. Color3.prototype.toColor4 = function (alpha) {
  81. if (alpha === void 0) { alpha = 1; }
  82. return new Color4(this.r, this.g, this.b, alpha);
  83. };
  84. Color3.prototype.asArray = function () {
  85. var result = [];
  86. this.toArray(result, 0);
  87. return result;
  88. };
  89. Color3.prototype.toLuminance = function () {
  90. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  91. };
  92. Color3.prototype.multiply = function (otherColor) {
  93. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  94. };
  95. Color3.prototype.multiplyToRef = function (otherColor, result) {
  96. result.r = this.r * otherColor.r;
  97. result.g = this.g * otherColor.g;
  98. result.b = this.b * otherColor.b;
  99. return this;
  100. };
  101. Color3.prototype.equals = function (otherColor) {
  102. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  103. };
  104. Color3.prototype.equalsFloats = function (r, g, b) {
  105. return this.r === r && this.g === g && this.b === b;
  106. };
  107. Color3.prototype.scale = function (scale) {
  108. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  109. };
  110. Color3.prototype.scaleToRef = function (scale, result) {
  111. result.r = this.r * scale;
  112. result.g = this.g * scale;
  113. result.b = this.b * scale;
  114. return this;
  115. };
  116. Color3.prototype.add = function (otherColor) {
  117. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  118. };
  119. Color3.prototype.addToRef = function (otherColor, result) {
  120. result.r = this.r + otherColor.r;
  121. result.g = this.g + otherColor.g;
  122. result.b = this.b + otherColor.b;
  123. return this;
  124. };
  125. Color3.prototype.subtract = function (otherColor) {
  126. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  127. };
  128. Color3.prototype.subtractToRef = function (otherColor, result) {
  129. result.r = this.r - otherColor.r;
  130. result.g = this.g - otherColor.g;
  131. result.b = this.b - otherColor.b;
  132. return this;
  133. };
  134. Color3.prototype.clone = function () {
  135. return new Color3(this.r, this.g, this.b);
  136. };
  137. Color3.prototype.copyFrom = function (source) {
  138. this.r = source.r;
  139. this.g = source.g;
  140. this.b = source.b;
  141. return this;
  142. };
  143. Color3.prototype.copyFromFloats = function (r, g, b) {
  144. this.r = r;
  145. this.g = g;
  146. this.b = b;
  147. return this;
  148. };
  149. Color3.prototype.toHexString = function () {
  150. var intR = (this.r * 255) | 0;
  151. var intG = (this.g * 255) | 0;
  152. var intB = (this.b * 255) | 0;
  153. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB);
  154. };
  155. Color3.prototype.toLinearSpace = function () {
  156. var convertedColor = new Color3();
  157. this.toLinearSpaceToRef(convertedColor);
  158. return convertedColor;
  159. };
  160. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  161. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  162. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  163. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  164. return this;
  165. };
  166. Color3.prototype.toGammaSpace = function () {
  167. var convertedColor = new Color3();
  168. this.toGammaSpaceToRef(convertedColor);
  169. return convertedColor;
  170. };
  171. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  172. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  173. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  174. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  175. return this;
  176. };
  177. // Statics
  178. Color3.FromHexString = function (hex) {
  179. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  180. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  181. return new Color3(0, 0, 0);
  182. }
  183. var r = parseInt(hex.substring(1, 3), 16);
  184. var g = parseInt(hex.substring(3, 5), 16);
  185. var b = parseInt(hex.substring(5, 7), 16);
  186. return Color3.FromInts(r, g, b);
  187. };
  188. Color3.FromArray = function (array, offset) {
  189. if (offset === void 0) { offset = 0; }
  190. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  191. };
  192. Color3.FromInts = function (r, g, b) {
  193. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  194. };
  195. Color3.Lerp = function (start, end, amount) {
  196. var r = start.r + ((end.r - start.r) * amount);
  197. var g = start.g + ((end.g - start.g) * amount);
  198. var b = start.b + ((end.b - start.b) * amount);
  199. return new Color3(r, g, b);
  200. };
  201. Color3.Red = function () { return new Color3(1, 0, 0); };
  202. Color3.Green = function () { return new Color3(0, 1, 0); };
  203. Color3.Blue = function () { return new Color3(0, 0, 1); };
  204. Color3.Black = function () { return new Color3(0, 0, 0); };
  205. Color3.White = function () { return new Color3(1, 1, 1); };
  206. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  207. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  208. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  209. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  210. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  211. return Color3;
  212. }());
  213. BABYLON.Color3 = Color3;
  214. var Color4 = (function () {
  215. function Color4(r, g, b, a) {
  216. this.r = r;
  217. this.g = g;
  218. this.b = b;
  219. this.a = a;
  220. }
  221. // Operators
  222. Color4.prototype.addInPlace = function (right) {
  223. this.r += right.r;
  224. this.g += right.g;
  225. this.b += right.b;
  226. this.a += right.a;
  227. return this;
  228. };
  229. Color4.prototype.asArray = function () {
  230. var result = [];
  231. this.toArray(result, 0);
  232. return result;
  233. };
  234. Color4.prototype.toArray = function (array, index) {
  235. if (index === undefined) {
  236. index = 0;
  237. }
  238. array[index] = this.r;
  239. array[index + 1] = this.g;
  240. array[index + 2] = this.b;
  241. array[index + 3] = this.a;
  242. return this;
  243. };
  244. Color4.prototype.add = function (right) {
  245. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  246. };
  247. Color4.prototype.subtract = function (right) {
  248. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  249. };
  250. Color4.prototype.subtractToRef = function (right, result) {
  251. result.r = this.r - right.r;
  252. result.g = this.g - right.g;
  253. result.b = this.b - right.b;
  254. result.a = this.a - right.a;
  255. return this;
  256. };
  257. Color4.prototype.scale = function (scale) {
  258. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  259. };
  260. Color4.prototype.scaleToRef = function (scale, result) {
  261. result.r = this.r * scale;
  262. result.g = this.g * scale;
  263. result.b = this.b * scale;
  264. result.a = this.a * scale;
  265. return this;
  266. };
  267. /**
  268. * Multipy an RGBA Color4 value by another and return a new Color4 object
  269. * @param color The Color4 (RGBA) value to multiply by
  270. * @returns A new Color4.
  271. */
  272. Color4.prototype.multiply = function (color) {
  273. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  274. };
  275. /**
  276. * Multipy an RGBA Color4 value by another and push the result in a reference value
  277. * @param color The Color4 (RGBA) value to multiply by
  278. * @param result The Color4 (RGBA) to fill the result in
  279. * @returns the result Color4.
  280. */
  281. Color4.prototype.multiplyToRef = function (color, result) {
  282. result.r = this.r * color.r;
  283. result.g = this.g * color.g;
  284. result.b = this.b * color.b;
  285. result.a = this.a * color.a;
  286. return result;
  287. };
  288. Color4.prototype.toString = function () {
  289. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  290. };
  291. Color4.prototype.getClassName = function () {
  292. return "Color4";
  293. };
  294. Color4.prototype.getHashCode = function () {
  295. var hash = this.r || 0;
  296. hash = (hash * 397) ^ (this.g || 0);
  297. hash = (hash * 397) ^ (this.b || 0);
  298. hash = (hash * 397) ^ (this.a || 0);
  299. return hash;
  300. };
  301. Color4.prototype.clone = function () {
  302. return new Color4(this.r, this.g, this.b, this.a);
  303. };
  304. Color4.prototype.copyFrom = function (source) {
  305. this.r = source.r;
  306. this.g = source.g;
  307. this.b = source.b;
  308. this.a = source.a;
  309. return this;
  310. };
  311. Color4.prototype.toHexString = function () {
  312. var intR = (this.r * 255) | 0;
  313. var intG = (this.g * 255) | 0;
  314. var intB = (this.b * 255) | 0;
  315. var intA = (this.a * 255) | 0;
  316. return "#" + MathTools.ToHex(intR) + MathTools.ToHex(intG) + MathTools.ToHex(intB) + MathTools.ToHex(intA);
  317. };
  318. // Statics
  319. Color4.FromHexString = function (hex) {
  320. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  321. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  322. return new Color4(0, 0, 0, 0);
  323. }
  324. var r = parseInt(hex.substring(1, 3), 16);
  325. var g = parseInt(hex.substring(3, 5), 16);
  326. var b = parseInt(hex.substring(5, 7), 16);
  327. var a = parseInt(hex.substring(7, 9), 16);
  328. return Color4.FromInts(r, g, b, a);
  329. };
  330. Color4.Lerp = function (left, right, amount) {
  331. var result = new Color4(0, 0, 0, 0);
  332. Color4.LerpToRef(left, right, amount, result);
  333. return result;
  334. };
  335. Color4.LerpToRef = function (left, right, amount, result) {
  336. result.r = left.r + (right.r - left.r) * amount;
  337. result.g = left.g + (right.g - left.g) * amount;
  338. result.b = left.b + (right.b - left.b) * amount;
  339. result.a = left.a + (right.a - left.a) * amount;
  340. };
  341. Color4.FromArray = function (array, offset) {
  342. if (offset === void 0) { offset = 0; }
  343. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  344. };
  345. Color4.FromInts = function (r, g, b, a) {
  346. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  347. };
  348. Color4.CheckColors4 = function (colors, count) {
  349. // Check if color3 was used
  350. if (colors.length === count * 3) {
  351. var colors4 = [];
  352. for (var index = 0; index < colors.length; index += 3) {
  353. var newIndex = (index / 3) * 4;
  354. colors4[newIndex] = colors[index];
  355. colors4[newIndex + 1] = colors[index + 1];
  356. colors4[newIndex + 2] = colors[index + 2];
  357. colors4[newIndex + 3] = 1.0;
  358. }
  359. return colors4;
  360. }
  361. return colors;
  362. };
  363. return Color4;
  364. }());
  365. BABYLON.Color4 = Color4;
  366. var Vector2 = (function () {
  367. function Vector2(x, y) {
  368. this.x = x;
  369. this.y = y;
  370. }
  371. Vector2.prototype.toString = function () {
  372. return "{X: " + this.x + " Y:" + this.y + "}";
  373. };
  374. Vector2.prototype.getClassName = function () {
  375. return "Vector2";
  376. };
  377. Vector2.prototype.getHashCode = function () {
  378. var hash = this.x || 0;
  379. hash = (hash * 397) ^ (this.y || 0);
  380. return hash;
  381. };
  382. // Operators
  383. Vector2.prototype.toArray = function (array, index) {
  384. if (index === void 0) { index = 0; }
  385. array[index] = this.x;
  386. array[index + 1] = this.y;
  387. return this;
  388. };
  389. Vector2.prototype.asArray = function () {
  390. var result = [];
  391. this.toArray(result, 0);
  392. return result;
  393. };
  394. Vector2.prototype.copyFrom = function (source) {
  395. this.x = source.x;
  396. this.y = source.y;
  397. return this;
  398. };
  399. Vector2.prototype.copyFromFloats = function (x, y) {
  400. this.x = x;
  401. this.y = y;
  402. return this;
  403. };
  404. Vector2.prototype.add = function (otherVector) {
  405. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  406. };
  407. Vector2.prototype.addToRef = function (otherVector, result) {
  408. result.x = this.x + otherVector.x;
  409. result.y = this.y + otherVector.y;
  410. return this;
  411. };
  412. Vector2.prototype.addInPlace = function (otherVector) {
  413. this.x += otherVector.x;
  414. this.y += otherVector.y;
  415. return this;
  416. };
  417. Vector2.prototype.addVector3 = function (otherVector) {
  418. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  419. };
  420. Vector2.prototype.subtract = function (otherVector) {
  421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  422. };
  423. Vector2.prototype.subtractToRef = function (otherVector, result) {
  424. result.x = this.x - otherVector.x;
  425. result.y = this.y - otherVector.y;
  426. return this;
  427. };
  428. Vector2.prototype.subtractInPlace = function (otherVector) {
  429. this.x -= otherVector.x;
  430. this.y -= otherVector.y;
  431. return this;
  432. };
  433. Vector2.prototype.multiplyInPlace = function (otherVector) {
  434. this.x *= otherVector.x;
  435. this.y *= otherVector.y;
  436. return this;
  437. };
  438. Vector2.prototype.multiply = function (otherVector) {
  439. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  440. };
  441. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  442. result.x = this.x * otherVector.x;
  443. result.y = this.y * otherVector.y;
  444. return this;
  445. };
  446. Vector2.prototype.multiplyByFloats = function (x, y) {
  447. return new Vector2(this.x * x, this.y * y);
  448. };
  449. Vector2.prototype.divide = function (otherVector) {
  450. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  451. };
  452. Vector2.prototype.divideToRef = function (otherVector, result) {
  453. result.x = this.x / otherVector.x;
  454. result.y = this.y / otherVector.y;
  455. return this;
  456. };
  457. Vector2.prototype.negate = function () {
  458. return new Vector2(-this.x, -this.y);
  459. };
  460. Vector2.prototype.scaleInPlace = function (scale) {
  461. this.x *= scale;
  462. this.y *= scale;
  463. return this;
  464. };
  465. Vector2.prototype.scale = function (scale) {
  466. return new Vector2(this.x * scale, this.y * scale);
  467. };
  468. Vector2.prototype.equals = function (otherVector) {
  469. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  470. };
  471. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  472. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  473. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon);
  474. };
  475. // Properties
  476. Vector2.prototype.length = function () {
  477. return Math.sqrt(this.x * this.x + this.y * this.y);
  478. };
  479. Vector2.prototype.lengthSquared = function () {
  480. return (this.x * this.x + this.y * this.y);
  481. };
  482. // Methods
  483. Vector2.prototype.normalize = function () {
  484. var len = this.length();
  485. if (len === 0)
  486. return this;
  487. var num = 1.0 / len;
  488. this.x *= num;
  489. this.y *= num;
  490. return this;
  491. };
  492. Vector2.prototype.clone = function () {
  493. return new Vector2(this.x, this.y);
  494. };
  495. // Statics
  496. Vector2.Zero = function () {
  497. return new Vector2(0, 0);
  498. };
  499. Vector2.FromArray = function (array, offset) {
  500. if (offset === void 0) { offset = 0; }
  501. return new Vector2(array[offset], array[offset + 1]);
  502. };
  503. Vector2.FromArrayToRef = function (array, offset, result) {
  504. result.x = array[offset];
  505. result.y = array[offset + 1];
  506. };
  507. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  508. var squared = amount * amount;
  509. var cubed = amount * squared;
  510. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  511. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  512. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  513. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  514. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  515. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  516. return new Vector2(x, y);
  517. };
  518. Vector2.Clamp = function (value, min, max) {
  519. var x = value.x;
  520. x = (x > max.x) ? max.x : x;
  521. x = (x < min.x) ? min.x : x;
  522. var y = value.y;
  523. y = (y > max.y) ? max.y : y;
  524. y = (y < min.y) ? min.y : y;
  525. return new Vector2(x, y);
  526. };
  527. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  528. var squared = amount * amount;
  529. var cubed = amount * squared;
  530. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  531. var part2 = (-2.0 * cubed) + (3.0 * squared);
  532. var part3 = (cubed - (2.0 * squared)) + amount;
  533. var part4 = cubed - squared;
  534. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  535. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  536. return new Vector2(x, y);
  537. };
  538. Vector2.Lerp = function (start, end, amount) {
  539. var x = start.x + ((end.x - start.x) * amount);
  540. var y = start.y + ((end.y - start.y) * amount);
  541. return new Vector2(x, y);
  542. };
  543. Vector2.Dot = function (left, right) {
  544. return left.x * right.x + left.y * right.y;
  545. };
  546. Vector2.Normalize = function (vector) {
  547. var newVector = vector.clone();
  548. newVector.normalize();
  549. return newVector;
  550. };
  551. Vector2.Minimize = function (left, right) {
  552. var x = (left.x < right.x) ? left.x : right.x;
  553. var y = (left.y < right.y) ? left.y : right.y;
  554. return new Vector2(x, y);
  555. };
  556. Vector2.Maximize = function (left, right) {
  557. var x = (left.x > right.x) ? left.x : right.x;
  558. var y = (left.y > right.y) ? left.y : right.y;
  559. return new Vector2(x, y);
  560. };
  561. Vector2.Transform = function (vector, transformation) {
  562. var r = Vector2.Zero();
  563. Vector2.TransformToRef(vector, transformation, r);
  564. return r;
  565. };
  566. Vector2.TransformToRef = function (vector, transformation, result) {
  567. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  568. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  569. result.x = x;
  570. result.y = y;
  571. };
  572. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  573. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  574. var sign = a < 0 ? -1 : 1;
  575. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  576. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  577. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  578. };
  579. Vector2.Distance = function (value1, value2) {
  580. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  581. };
  582. Vector2.DistanceSquared = function (value1, value2) {
  583. var x = value1.x - value2.x;
  584. var y = value1.y - value2.y;
  585. return (x * x) + (y * y);
  586. };
  587. Vector2.Center = function (value1, value2) {
  588. var center = value1.add(value2);
  589. center.scaleInPlace(0.5);
  590. return center;
  591. };
  592. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  593. var l2 = Vector2.DistanceSquared(segA, segB);
  594. if (l2 === 0.0) {
  595. return Vector2.Distance(p, segA);
  596. }
  597. var v = segB.subtract(segA);
  598. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  599. var proj = segA.add(v.multiplyByFloats(t, t));
  600. return Vector2.Distance(p, proj);
  601. };
  602. return Vector2;
  603. }());
  604. BABYLON.Vector2 = Vector2;
  605. var Vector3 = (function () {
  606. function Vector3(x, y, z) {
  607. this.x = x;
  608. this.y = y;
  609. this.z = z;
  610. }
  611. Vector3.prototype.toString = function () {
  612. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  613. };
  614. Vector3.prototype.getClassName = function () {
  615. return "Vector3";
  616. };
  617. Vector3.prototype.getHashCode = function () {
  618. var hash = this.x || 0;
  619. hash = (hash * 397) ^ (this.y || 0);
  620. hash = (hash * 397) ^ (this.z || 0);
  621. return hash;
  622. };
  623. // Operators
  624. Vector3.prototype.asArray = function () {
  625. var result = [];
  626. this.toArray(result, 0);
  627. return result;
  628. };
  629. Vector3.prototype.toArray = function (array, index) {
  630. if (index === void 0) { index = 0; }
  631. array[index] = this.x;
  632. array[index + 1] = this.y;
  633. array[index + 2] = this.z;
  634. return this;
  635. };
  636. Vector3.prototype.toQuaternion = function () {
  637. var result = new Quaternion(0, 0, 0, 1);
  638. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  639. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  640. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  641. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  642. var cosy = Math.cos(this.y * 0.5);
  643. var siny = Math.sin(this.y * 0.5);
  644. result.x = coszMinusx * siny;
  645. result.y = -sinzMinusx * siny;
  646. result.z = sinxPlusz * cosy;
  647. result.w = cosxPlusz * cosy;
  648. return result;
  649. };
  650. Vector3.prototype.addInPlace = function (otherVector) {
  651. this.x += otherVector.x;
  652. this.y += otherVector.y;
  653. this.z += otherVector.z;
  654. return this;
  655. };
  656. Vector3.prototype.add = function (otherVector) {
  657. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  658. };
  659. Vector3.prototype.addToRef = function (otherVector, result) {
  660. result.x = this.x + otherVector.x;
  661. result.y = this.y + otherVector.y;
  662. result.z = this.z + otherVector.z;
  663. return this;
  664. };
  665. Vector3.prototype.subtractInPlace = function (otherVector) {
  666. this.x -= otherVector.x;
  667. this.y -= otherVector.y;
  668. this.z -= otherVector.z;
  669. return this;
  670. };
  671. Vector3.prototype.subtract = function (otherVector) {
  672. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  673. };
  674. Vector3.prototype.subtractToRef = function (otherVector, result) {
  675. result.x = this.x - otherVector.x;
  676. result.y = this.y - otherVector.y;
  677. result.z = this.z - otherVector.z;
  678. return this;
  679. };
  680. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  681. return new Vector3(this.x - x, this.y - y, this.z - z);
  682. };
  683. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  684. result.x = this.x - x;
  685. result.y = this.y - y;
  686. result.z = this.z - z;
  687. return this;
  688. };
  689. Vector3.prototype.negate = function () {
  690. return new Vector3(-this.x, -this.y, -this.z);
  691. };
  692. Vector3.prototype.scaleInPlace = function (scale) {
  693. this.x *= scale;
  694. this.y *= scale;
  695. this.z *= scale;
  696. return this;
  697. };
  698. Vector3.prototype.scale = function (scale) {
  699. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  700. };
  701. Vector3.prototype.scaleToRef = function (scale, result) {
  702. result.x = this.x * scale;
  703. result.y = this.y * scale;
  704. result.z = this.z * scale;
  705. };
  706. Vector3.prototype.equals = function (otherVector) {
  707. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  708. };
  709. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  710. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  711. return otherVector && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon) && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon) && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon);
  712. };
  713. Vector3.prototype.equalsToFloats = function (x, y, z) {
  714. return this.x === x && this.y === y && this.z === z;
  715. };
  716. Vector3.prototype.multiplyInPlace = function (otherVector) {
  717. this.x *= otherVector.x;
  718. this.y *= otherVector.y;
  719. this.z *= otherVector.z;
  720. return this;
  721. };
  722. Vector3.prototype.multiply = function (otherVector) {
  723. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  724. };
  725. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  726. result.x = this.x * otherVector.x;
  727. result.y = this.y * otherVector.y;
  728. result.z = this.z * otherVector.z;
  729. return this;
  730. };
  731. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  732. return new Vector3(this.x * x, this.y * y, this.z * z);
  733. };
  734. Vector3.prototype.divide = function (otherVector) {
  735. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  736. };
  737. Vector3.prototype.divideToRef = function (otherVector, result) {
  738. result.x = this.x / otherVector.x;
  739. result.y = this.y / otherVector.y;
  740. result.z = this.z / otherVector.z;
  741. return this;
  742. };
  743. Vector3.prototype.MinimizeInPlace = function (other) {
  744. if (other.x < this.x)
  745. this.x = other.x;
  746. if (other.y < this.y)
  747. this.y = other.y;
  748. if (other.z < this.z)
  749. this.z = other.z;
  750. return this;
  751. };
  752. Vector3.prototype.MaximizeInPlace = function (other) {
  753. if (other.x > this.x)
  754. this.x = other.x;
  755. if (other.y > this.y)
  756. this.y = other.y;
  757. if (other.z > this.z)
  758. this.z = other.z;
  759. return this;
  760. };
  761. // Properties
  762. Vector3.prototype.length = function () {
  763. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  764. };
  765. Vector3.prototype.lengthSquared = function () {
  766. return (this.x * this.x + this.y * this.y + this.z * this.z);
  767. };
  768. // Methods
  769. Vector3.prototype.normalize = function () {
  770. var len = this.length();
  771. if (len === 0 || len === 1.0)
  772. return this;
  773. var num = 1.0 / len;
  774. this.x *= num;
  775. this.y *= num;
  776. this.z *= num;
  777. return this;
  778. };
  779. Vector3.prototype.clone = function () {
  780. return new Vector3(this.x, this.y, this.z);
  781. };
  782. Vector3.prototype.copyFrom = function (source) {
  783. this.x = source.x;
  784. this.y = source.y;
  785. this.z = source.z;
  786. return this;
  787. };
  788. Vector3.prototype.copyFromFloats = function (x, y, z) {
  789. this.x = x;
  790. this.y = y;
  791. this.z = z;
  792. return this;
  793. };
  794. // Statics
  795. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  796. var d0 = Vector3.Dot(vector0, axis) - size;
  797. var d1 = Vector3.Dot(vector1, axis) - size;
  798. var s = d0 / (d0 - d1);
  799. return s;
  800. };
  801. Vector3.FromArray = function (array, offset) {
  802. if (!offset) {
  803. offset = 0;
  804. }
  805. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  806. };
  807. Vector3.FromFloatArray = function (array, offset) {
  808. if (!offset) {
  809. offset = 0;
  810. }
  811. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  812. };
  813. Vector3.FromArrayToRef = function (array, offset, result) {
  814. result.x = array[offset];
  815. result.y = array[offset + 1];
  816. result.z = array[offset + 2];
  817. };
  818. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  819. result.x = array[offset];
  820. result.y = array[offset + 1];
  821. result.z = array[offset + 2];
  822. };
  823. Vector3.FromFloatsToRef = function (x, y, z, result) {
  824. result.x = x;
  825. result.y = y;
  826. result.z = z;
  827. };
  828. Vector3.Zero = function () {
  829. return new Vector3(0, 0, 0);
  830. };
  831. Vector3.Up = function () {
  832. return new Vector3(0, 1.0, 0);
  833. };
  834. Vector3.Forward = function () {
  835. return new Vector3(0, 0, 1.0);
  836. };
  837. Vector3.Right = function () {
  838. return new Vector3(1.0, 0, 0);
  839. };
  840. Vector3.Left = function () {
  841. return new Vector3(-1.0, 0, 0);
  842. };
  843. Vector3.TransformCoordinates = function (vector, transformation) {
  844. var result = Vector3.Zero();
  845. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  846. return result;
  847. };
  848. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  849. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  850. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  851. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  852. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  853. result.x = x / w;
  854. result.y = y / w;
  855. result.z = z / w;
  856. };
  857. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  858. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  859. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  860. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  861. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  862. result.x = rx / rw;
  863. result.y = ry / rw;
  864. result.z = rz / rw;
  865. };
  866. Vector3.TransformNormal = function (vector, transformation) {
  867. var result = Vector3.Zero();
  868. Vector3.TransformNormalToRef(vector, transformation, result);
  869. return result;
  870. };
  871. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  872. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  873. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  874. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  875. result.x = x;
  876. result.y = y;
  877. result.z = z;
  878. };
  879. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  880. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  881. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  882. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  883. };
  884. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  885. var squared = amount * amount;
  886. var cubed = amount * squared;
  887. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  888. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  889. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  890. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  891. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  892. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  893. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  894. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  895. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  896. return new Vector3(x, y, z);
  897. };
  898. Vector3.Clamp = function (value, min, max) {
  899. var x = value.x;
  900. x = (x > max.x) ? max.x : x;
  901. x = (x < min.x) ? min.x : x;
  902. var y = value.y;
  903. y = (y > max.y) ? max.y : y;
  904. y = (y < min.y) ? min.y : y;
  905. var z = value.z;
  906. z = (z > max.z) ? max.z : z;
  907. z = (z < min.z) ? min.z : z;
  908. return new Vector3(x, y, z);
  909. };
  910. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  911. var squared = amount * amount;
  912. var cubed = amount * squared;
  913. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  914. var part2 = (-2.0 * cubed) + (3.0 * squared);
  915. var part3 = (cubed - (2.0 * squared)) + amount;
  916. var part4 = cubed - squared;
  917. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  918. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  919. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  920. return new Vector3(x, y, z);
  921. };
  922. Vector3.Lerp = function (start, end, amount) {
  923. var result = new Vector3(0, 0, 0);
  924. Vector3.LerpToRef(start, end, amount, result);
  925. return result;
  926. };
  927. Vector3.LerpToRef = function (start, end, amount, result) {
  928. result.x = start.x + ((end.x - start.x) * amount);
  929. result.y = start.y + ((end.y - start.y) * amount);
  930. result.z = start.z + ((end.z - start.z) * amount);
  931. };
  932. Vector3.Dot = function (left, right) {
  933. return (left.x * right.x + left.y * right.y + left.z * right.z);
  934. };
  935. Vector3.Cross = function (left, right) {
  936. var result = Vector3.Zero();
  937. Vector3.CrossToRef(left, right, result);
  938. return result;
  939. };
  940. Vector3.CrossToRef = function (left, right, result) {
  941. Tmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  942. Tmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  943. Tmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  944. result.copyFrom(Tmp.Vector3[0]);
  945. };
  946. Vector3.Normalize = function (vector) {
  947. var result = Vector3.Zero();
  948. Vector3.NormalizeToRef(vector, result);
  949. return result;
  950. };
  951. Vector3.NormalizeToRef = function (vector, result) {
  952. result.copyFrom(vector);
  953. result.normalize();
  954. };
  955. Vector3.Project = function (vector, world, transform, viewport) {
  956. var cw = viewport.width;
  957. var ch = viewport.height;
  958. var cx = viewport.x;
  959. var cy = viewport.y;
  960. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  961. Matrix.FromValuesToRef(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, viewportMatrix);
  962. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  963. world.multiplyToRef(transform, matrix);
  964. matrix.multiplyToRef(viewportMatrix, matrix);
  965. return Vector3.TransformCoordinates(vector, matrix);
  966. };
  967. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  968. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  969. world.multiplyToRef(transform, matrix);
  970. matrix.invert();
  971. source.x = source.x / viewportWidth * 2 - 1;
  972. source.y = -(source.y / viewportHeight * 2 - 1);
  973. var vector = Vector3.TransformCoordinates(source, matrix);
  974. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  975. if (MathTools.WithinEpsilon(num, 1.0)) {
  976. vector = vector.scale(1.0 / num);
  977. }
  978. return vector;
  979. };
  980. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  981. var matrix = Vector3._matrixCache ? Vector3._matrixCache : (Vector3._matrixCache = new Matrix());
  982. world.multiplyToRef(view, matrix);
  983. matrix.multiplyToRef(projection, matrix);
  984. matrix.invert();
  985. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  986. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  987. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  988. if (MathTools.WithinEpsilon(num, 1.0)) {
  989. vector = vector.scale(1.0 / num);
  990. }
  991. return vector;
  992. };
  993. Vector3.Minimize = function (left, right) {
  994. var min = left.clone();
  995. min.MinimizeInPlace(right);
  996. return min;
  997. };
  998. Vector3.Maximize = function (left, right) {
  999. var max = left.clone();
  1000. max.MaximizeInPlace(right);
  1001. return max;
  1002. };
  1003. Vector3.Distance = function (value1, value2) {
  1004. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1005. };
  1006. Vector3.DistanceSquared = function (value1, value2) {
  1007. var x = value1.x - value2.x;
  1008. var y = value1.y - value2.y;
  1009. var z = value1.z - value2.z;
  1010. return (x * x) + (y * y) + (z * z);
  1011. };
  1012. Vector3.Center = function (value1, value2) {
  1013. var center = value1.add(value2);
  1014. center.scaleInPlace(0.5);
  1015. return center;
  1016. };
  1017. /**
  1018. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1019. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1020. * to something in order to rotate it from its local system to the given target system.
  1021. */
  1022. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1023. var rotation = Vector3.Zero();
  1024. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1025. return rotation;
  1026. };
  1027. /**
  1028. * The same than RotationFromAxis but updates the passed ref Vector3 parameter.
  1029. */
  1030. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1031. var u = axis1.normalize();
  1032. var w = axis3.normalize();
  1033. // world axis
  1034. var X = Axis.X;
  1035. var Y = Axis.Y;
  1036. // equation unknowns and vars
  1037. var yaw = 0.0;
  1038. var pitch = 0.0;
  1039. var roll = 0.0;
  1040. var x = 0.0;
  1041. var y = 0.0;
  1042. var z = 0.0;
  1043. var t = 0.0;
  1044. var sign = -1.0;
  1045. var nbRevert = 0;
  1046. var cross = Tmp.Vector3[0];
  1047. var dot = 0.0;
  1048. // step 1 : rotation around w
  1049. // Rv3(u) = u1, and u1 belongs to plane xOz
  1050. // Rv3(w) = w1 = w invariant
  1051. var u1 = Tmp.Vector3[1];
  1052. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1053. z = 1.0;
  1054. }
  1055. else if (MathTools.WithinEpsilon(w.x, 0, BABYLON.Epsilon)) {
  1056. x = 1.0;
  1057. }
  1058. else {
  1059. t = w.z / w.x;
  1060. x = -t * Math.sqrt(1 / (1 + t * t));
  1061. z = Math.sqrt(1 / (1 + t * t));
  1062. }
  1063. u1.x = x;
  1064. u1.y = y;
  1065. u1.z = z;
  1066. u1.normalize();
  1067. Vector3.CrossToRef(u, u1, cross); // returns same direction as w (=local z) if positive angle : cross(source, image)
  1068. cross.normalize();
  1069. if (Vector3.Dot(w, cross) < 0) {
  1070. sign = 1.0;
  1071. }
  1072. dot = Vector3.Dot(u, u1);
  1073. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1074. roll = Math.acos(dot) * sign;
  1075. if (Vector3.Dot(u1, X) < 0) {
  1076. roll = Math.PI + roll;
  1077. u1 = u1.scaleInPlace(-1);
  1078. nbRevert++;
  1079. }
  1080. // step 2 : rotate around u1
  1081. // Ru1(w1) = Ru1(w) = w2, and w2 belongs to plane xOz
  1082. // u1 is yet in xOz and invariant by Ru1, so after this step u1 and w2 will be in xOz
  1083. var w2 = Tmp.Vector3[2];
  1084. var v2 = Tmp.Vector3[3];
  1085. x = 0.0;
  1086. y = 0.0;
  1087. z = 0.0;
  1088. sign = -1.0;
  1089. if (MathTools.WithinEpsilon(w.z, 0, BABYLON.Epsilon)) {
  1090. x = 1.0;
  1091. }
  1092. else {
  1093. t = u1.z / u1.x;
  1094. x = -t * Math.sqrt(1 / (1 + t * t));
  1095. z = Math.sqrt(1 / (1 + t * t));
  1096. }
  1097. w2.x = x;
  1098. w2.y = y;
  1099. w2.z = z;
  1100. w2.normalize();
  1101. Vector3.CrossToRef(w2, u1, v2); // v2 image of v1 through rotation around u1
  1102. v2.normalize();
  1103. Vector3.CrossToRef(w, w2, cross); // returns same direction as u1 (=local x) if positive angle : cross(source, image)
  1104. cross.normalize();
  1105. if (Vector3.Dot(u1, cross) < 0) {
  1106. sign = 1.0;
  1107. }
  1108. dot = Vector3.Dot(w, w2);
  1109. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1110. pitch = Math.acos(dot) * sign;
  1111. if (Vector3.Dot(v2, Y) < 0) {
  1112. pitch = Math.PI + pitch;
  1113. nbRevert++;
  1114. }
  1115. // step 3 : rotate around v2
  1116. // Rv2(u1) = X, same as Rv2(w2) = Z, with X=(1,0,0) and Z=(0,0,1)
  1117. sign = -1.0;
  1118. Vector3.CrossToRef(X, u1, cross); // returns same direction as Y if positive angle : cross(source, image)
  1119. cross.normalize();
  1120. if (Vector3.Dot(cross, Y) < 0) {
  1121. sign = 1.0;
  1122. }
  1123. dot = Vector3.Dot(u1, X);
  1124. dot = (Math.min(1.0, Math.max(-1.0, dot))); // to force dot to be in the range [-1, 1]
  1125. yaw = -Math.acos(dot) * sign; // negative : plane zOx oriented clockwise
  1126. if (dot < 0 && nbRevert < 2) {
  1127. yaw = Math.PI + yaw;
  1128. }
  1129. ref.x = pitch;
  1130. ref.y = yaw;
  1131. ref.z = roll;
  1132. };
  1133. return Vector3;
  1134. }());
  1135. BABYLON.Vector3 = Vector3;
  1136. //Vector4 class created for EulerAngle class conversion to Quaternion
  1137. var Vector4 = (function () {
  1138. function Vector4(x, y, z, w) {
  1139. this.x = x;
  1140. this.y = y;
  1141. this.z = z;
  1142. this.w = w;
  1143. }
  1144. Vector4.prototype.toString = function () {
  1145. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1146. };
  1147. Vector4.prototype.getClassName = function () {
  1148. return "Vector4";
  1149. };
  1150. Vector4.prototype.getHashCode = function () {
  1151. var hash = this.x || 0;
  1152. hash = (hash * 397) ^ (this.y || 0);
  1153. hash = (hash * 397) ^ (this.z || 0);
  1154. hash = (hash * 397) ^ (this.w || 0);
  1155. return hash;
  1156. };
  1157. // Operators
  1158. Vector4.prototype.asArray = function () {
  1159. var result = [];
  1160. this.toArray(result, 0);
  1161. return result;
  1162. };
  1163. Vector4.prototype.toArray = function (array, index) {
  1164. if (index === undefined) {
  1165. index = 0;
  1166. }
  1167. array[index] = this.x;
  1168. array[index + 1] = this.y;
  1169. array[index + 2] = this.z;
  1170. array[index + 3] = this.w;
  1171. return this;
  1172. };
  1173. Vector4.prototype.addInPlace = function (otherVector) {
  1174. this.x += otherVector.x;
  1175. this.y += otherVector.y;
  1176. this.z += otherVector.z;
  1177. this.w += otherVector.w;
  1178. return this;
  1179. };
  1180. Vector4.prototype.add = function (otherVector) {
  1181. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1182. };
  1183. Vector4.prototype.addToRef = function (otherVector, result) {
  1184. result.x = this.x + otherVector.x;
  1185. result.y = this.y + otherVector.y;
  1186. result.z = this.z + otherVector.z;
  1187. result.w = this.w + otherVector.w;
  1188. return this;
  1189. };
  1190. Vector4.prototype.subtractInPlace = function (otherVector) {
  1191. this.x -= otherVector.x;
  1192. this.y -= otherVector.y;
  1193. this.z -= otherVector.z;
  1194. this.w -= otherVector.w;
  1195. return this;
  1196. };
  1197. Vector4.prototype.subtract = function (otherVector) {
  1198. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1199. };
  1200. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1201. result.x = this.x - otherVector.x;
  1202. result.y = this.y - otherVector.y;
  1203. result.z = this.z - otherVector.z;
  1204. result.w = this.w - otherVector.w;
  1205. return this;
  1206. };
  1207. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1208. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1209. };
  1210. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1211. result.x = this.x - x;
  1212. result.y = this.y - y;
  1213. result.z = this.z - z;
  1214. result.w = this.w - w;
  1215. return this;
  1216. };
  1217. Vector4.prototype.negate = function () {
  1218. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1219. };
  1220. Vector4.prototype.scaleInPlace = function (scale) {
  1221. this.x *= scale;
  1222. this.y *= scale;
  1223. this.z *= scale;
  1224. this.w *= scale;
  1225. return this;
  1226. };
  1227. Vector4.prototype.scale = function (scale) {
  1228. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1229. };
  1230. Vector4.prototype.scaleToRef = function (scale, result) {
  1231. result.x = this.x * scale;
  1232. result.y = this.y * scale;
  1233. result.z = this.z * scale;
  1234. result.w = this.w * scale;
  1235. };
  1236. Vector4.prototype.equals = function (otherVector) {
  1237. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1238. };
  1239. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1240. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1241. return otherVector
  1242. && MathTools.WithinEpsilon(this.x, otherVector.x, epsilon)
  1243. && MathTools.WithinEpsilon(this.y, otherVector.y, epsilon)
  1244. && MathTools.WithinEpsilon(this.z, otherVector.z, epsilon)
  1245. && MathTools.WithinEpsilon(this.w, otherVector.w, epsilon);
  1246. };
  1247. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1248. return this.x === x && this.y === y && this.z === z && this.w === w;
  1249. };
  1250. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1251. this.x *= otherVector.x;
  1252. this.y *= otherVector.y;
  1253. this.z *= otherVector.z;
  1254. this.w *= otherVector.w;
  1255. return this;
  1256. };
  1257. Vector4.prototype.multiply = function (otherVector) {
  1258. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1259. };
  1260. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1261. result.x = this.x * otherVector.x;
  1262. result.y = this.y * otherVector.y;
  1263. result.z = this.z * otherVector.z;
  1264. result.w = this.w * otherVector.w;
  1265. return this;
  1266. };
  1267. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1268. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1269. };
  1270. Vector4.prototype.divide = function (otherVector) {
  1271. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1272. };
  1273. Vector4.prototype.divideToRef = function (otherVector, result) {
  1274. result.x = this.x / otherVector.x;
  1275. result.y = this.y / otherVector.y;
  1276. result.z = this.z / otherVector.z;
  1277. result.w = this.w / otherVector.w;
  1278. return this;
  1279. };
  1280. Vector4.prototype.MinimizeInPlace = function (other) {
  1281. if (other.x < this.x)
  1282. this.x = other.x;
  1283. if (other.y < this.y)
  1284. this.y = other.y;
  1285. if (other.z < this.z)
  1286. this.z = other.z;
  1287. if (other.w < this.w)
  1288. this.w = other.w;
  1289. return this;
  1290. };
  1291. Vector4.prototype.MaximizeInPlace = function (other) {
  1292. if (other.x > this.x)
  1293. this.x = other.x;
  1294. if (other.y > this.y)
  1295. this.y = other.y;
  1296. if (other.z > this.z)
  1297. this.z = other.z;
  1298. if (other.w > this.w)
  1299. this.w = other.w;
  1300. return this;
  1301. };
  1302. // Properties
  1303. Vector4.prototype.length = function () {
  1304. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1305. };
  1306. Vector4.prototype.lengthSquared = function () {
  1307. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1308. };
  1309. // Methods
  1310. Vector4.prototype.normalize = function () {
  1311. var len = this.length();
  1312. if (len === 0)
  1313. return this;
  1314. var num = 1.0 / len;
  1315. this.x *= num;
  1316. this.y *= num;
  1317. this.z *= num;
  1318. this.w *= num;
  1319. return this;
  1320. };
  1321. Vector4.prototype.toVector3 = function () {
  1322. return new Vector3(this.x, this.y, this.z);
  1323. };
  1324. Vector4.prototype.clone = function () {
  1325. return new Vector4(this.x, this.y, this.z, this.w);
  1326. };
  1327. Vector4.prototype.copyFrom = function (source) {
  1328. this.x = source.x;
  1329. this.y = source.y;
  1330. this.z = source.z;
  1331. this.w = source.w;
  1332. return this;
  1333. };
  1334. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1335. this.x = x;
  1336. this.y = y;
  1337. this.z = z;
  1338. this.w = w;
  1339. return this;
  1340. };
  1341. // Statics
  1342. Vector4.FromArray = function (array, offset) {
  1343. if (!offset) {
  1344. offset = 0;
  1345. }
  1346. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1347. };
  1348. Vector4.FromArrayToRef = function (array, offset, result) {
  1349. result.x = array[offset];
  1350. result.y = array[offset + 1];
  1351. result.z = array[offset + 2];
  1352. result.w = array[offset + 3];
  1353. };
  1354. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  1355. result.x = array[offset];
  1356. result.y = array[offset + 1];
  1357. result.z = array[offset + 2];
  1358. result.w = array[offset + 3];
  1359. };
  1360. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  1361. result.x = x;
  1362. result.y = y;
  1363. result.z = z;
  1364. result.w = w;
  1365. };
  1366. Vector4.Zero = function () {
  1367. return new Vector4(0, 0, 0, 0);
  1368. };
  1369. Vector4.Normalize = function (vector) {
  1370. var result = Vector4.Zero();
  1371. Vector4.NormalizeToRef(vector, result);
  1372. return result;
  1373. };
  1374. Vector4.NormalizeToRef = function (vector, result) {
  1375. result.copyFrom(vector);
  1376. result.normalize();
  1377. };
  1378. Vector4.Minimize = function (left, right) {
  1379. var min = left.clone();
  1380. min.MinimizeInPlace(right);
  1381. return min;
  1382. };
  1383. Vector4.Maximize = function (left, right) {
  1384. var max = left.clone();
  1385. max.MaximizeInPlace(right);
  1386. return max;
  1387. };
  1388. Vector4.Distance = function (value1, value2) {
  1389. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  1390. };
  1391. Vector4.DistanceSquared = function (value1, value2) {
  1392. var x = value1.x - value2.x;
  1393. var y = value1.y - value2.y;
  1394. var z = value1.z - value2.z;
  1395. var w = value1.w - value2.w;
  1396. return (x * x) + (y * y) + (z * z) + (w * w);
  1397. };
  1398. Vector4.Center = function (value1, value2) {
  1399. var center = value1.add(value2);
  1400. center.scaleInPlace(0.5);
  1401. return center;
  1402. };
  1403. return Vector4;
  1404. }());
  1405. BABYLON.Vector4 = Vector4;
  1406. var Size = (function () {
  1407. function Size(width, height) {
  1408. this.width = width;
  1409. this.height = height;
  1410. }
  1411. Size.prototype.toString = function () {
  1412. return "{W: " + this.width + ", H: " + this.height + "}";
  1413. };
  1414. Size.prototype.getClassName = function () {
  1415. return "Size";
  1416. };
  1417. Size.prototype.getHashCode = function () {
  1418. var hash = this.width || 0;
  1419. hash = (hash * 397) ^ (this.height || 0);
  1420. return hash;
  1421. };
  1422. Size.prototype.copyFrom = function (src) {
  1423. this.width = src.width;
  1424. this.height = src.height;
  1425. };
  1426. Size.prototype.copyFromFloats = function (width, height) {
  1427. this.width = width;
  1428. this.height = height;
  1429. };
  1430. Size.prototype.multiplyByFloats = function (w, h) {
  1431. return new Size(this.width * w, this.height * h);
  1432. };
  1433. Size.prototype.clone = function () {
  1434. return new Size(this.width, this.height);
  1435. };
  1436. Size.prototype.equals = function (other) {
  1437. if (!other) {
  1438. return false;
  1439. }
  1440. return (this.width === other.width) && (this.height === other.height);
  1441. };
  1442. Object.defineProperty(Size.prototype, "surface", {
  1443. get: function () {
  1444. return this.width * this.height;
  1445. },
  1446. enumerable: true,
  1447. configurable: true
  1448. });
  1449. Size.Zero = function () {
  1450. return new Size(0, 0);
  1451. };
  1452. Size.prototype.add = function (otherSize) {
  1453. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  1454. return r;
  1455. };
  1456. Size.prototype.substract = function (otherSize) {
  1457. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  1458. return r;
  1459. };
  1460. Size.Lerp = function (start, end, amount) {
  1461. var w = start.width + ((end.width - start.width) * amount);
  1462. var h = start.height + ((end.height - start.height) * amount);
  1463. return new Size(w, h);
  1464. };
  1465. return Size;
  1466. }());
  1467. BABYLON.Size = Size;
  1468. var Quaternion = (function () {
  1469. function Quaternion(x, y, z, w) {
  1470. if (x === void 0) { x = 0; }
  1471. if (y === void 0) { y = 0; }
  1472. if (z === void 0) { z = 0; }
  1473. if (w === void 0) { w = 1; }
  1474. this.x = x;
  1475. this.y = y;
  1476. this.z = z;
  1477. this.w = w;
  1478. }
  1479. Quaternion.prototype.toString = function () {
  1480. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1481. };
  1482. Quaternion.prototype.getClassName = function () {
  1483. return "Quaternion";
  1484. };
  1485. Quaternion.prototype.getHashCode = function () {
  1486. var hash = this.x || 0;
  1487. hash = (hash * 397) ^ (this.y || 0);
  1488. hash = (hash * 397) ^ (this.z || 0);
  1489. hash = (hash * 397) ^ (this.w || 0);
  1490. return hash;
  1491. };
  1492. Quaternion.prototype.asArray = function () {
  1493. return [this.x, this.y, this.z, this.w];
  1494. };
  1495. Quaternion.prototype.equals = function (otherQuaternion) {
  1496. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  1497. };
  1498. Quaternion.prototype.clone = function () {
  1499. return new Quaternion(this.x, this.y, this.z, this.w);
  1500. };
  1501. Quaternion.prototype.copyFrom = function (other) {
  1502. this.x = other.x;
  1503. this.y = other.y;
  1504. this.z = other.z;
  1505. this.w = other.w;
  1506. return this;
  1507. };
  1508. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  1509. this.x = x;
  1510. this.y = y;
  1511. this.z = z;
  1512. this.w = w;
  1513. return this;
  1514. };
  1515. Quaternion.prototype.add = function (other) {
  1516. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  1517. };
  1518. Quaternion.prototype.subtract = function (other) {
  1519. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  1520. };
  1521. Quaternion.prototype.scale = function (value) {
  1522. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  1523. };
  1524. Quaternion.prototype.multiply = function (q1) {
  1525. var result = new Quaternion(0, 0, 0, 1.0);
  1526. this.multiplyToRef(q1, result);
  1527. return result;
  1528. };
  1529. Quaternion.prototype.multiplyToRef = function (q1, result) {
  1530. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  1531. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  1532. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  1533. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  1534. result.copyFromFloats(x, y, z, w);
  1535. return this;
  1536. };
  1537. Quaternion.prototype.multiplyInPlace = function (q1) {
  1538. this.multiplyToRef(q1, this);
  1539. return this;
  1540. };
  1541. Quaternion.prototype.conjugateToRef = function (ref) {
  1542. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  1543. return this;
  1544. };
  1545. Quaternion.prototype.conjugateInPlace = function () {
  1546. this.x *= -1;
  1547. this.y *= -1;
  1548. this.z *= -1;
  1549. return this;
  1550. };
  1551. Quaternion.prototype.conjugate = function () {
  1552. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  1553. return result;
  1554. };
  1555. Quaternion.prototype.length = function () {
  1556. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  1557. };
  1558. Quaternion.prototype.normalize = function () {
  1559. var length = 1.0 / this.length();
  1560. this.x *= length;
  1561. this.y *= length;
  1562. this.z *= length;
  1563. this.w *= length;
  1564. return this;
  1565. };
  1566. Quaternion.prototype.toEulerAngles = function (order) {
  1567. if (order === void 0) { order = "YZX"; }
  1568. var result = Vector3.Zero();
  1569. this.toEulerAnglesToRef(result, order);
  1570. return result;
  1571. };
  1572. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  1573. if (order === void 0) { order = "YZX"; }
  1574. var qz = this.z;
  1575. var qx = this.x;
  1576. var qy = this.y;
  1577. var qw = this.w;
  1578. var sqw = qw * qw;
  1579. var sqz = qz * qz;
  1580. var sqx = qx * qx;
  1581. var sqy = qy * qy;
  1582. var zAxisY = qy * qz - qx * qw;
  1583. var limit = .4999999;
  1584. if (zAxisY < -limit) {
  1585. result.y = 2 * Math.atan2(qy, qw);
  1586. result.x = Math.PI / 2;
  1587. result.z = 0;
  1588. }
  1589. else if (zAxisY > limit) {
  1590. result.y = 2 * Math.atan2(qy, qw);
  1591. result.x = -Math.PI / 2;
  1592. result.z = 0;
  1593. }
  1594. else {
  1595. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  1596. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  1597. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  1598. }
  1599. return this;
  1600. };
  1601. Quaternion.prototype.toRotationMatrix = function (result) {
  1602. var xx = this.x * this.x;
  1603. var yy = this.y * this.y;
  1604. var zz = this.z * this.z;
  1605. var xy = this.x * this.y;
  1606. var zw = this.z * this.w;
  1607. var zx = this.z * this.x;
  1608. var yw = this.y * this.w;
  1609. var yz = this.y * this.z;
  1610. var xw = this.x * this.w;
  1611. result.m[0] = 1.0 - (2.0 * (yy + zz));
  1612. result.m[1] = 2.0 * (xy + zw);
  1613. result.m[2] = 2.0 * (zx - yw);
  1614. result.m[3] = 0;
  1615. result.m[4] = 2.0 * (xy - zw);
  1616. result.m[5] = 1.0 - (2.0 * (zz + xx));
  1617. result.m[6] = 2.0 * (yz + xw);
  1618. result.m[7] = 0;
  1619. result.m[8] = 2.0 * (zx + yw);
  1620. result.m[9] = 2.0 * (yz - xw);
  1621. result.m[10] = 1.0 - (2.0 * (yy + xx));
  1622. result.m[11] = 0;
  1623. result.m[12] = 0;
  1624. result.m[13] = 0;
  1625. result.m[14] = 0;
  1626. result.m[15] = 1.0;
  1627. return this;
  1628. };
  1629. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  1630. Quaternion.FromRotationMatrixToRef(matrix, this);
  1631. return this;
  1632. };
  1633. // Statics
  1634. Quaternion.FromRotationMatrix = function (matrix) {
  1635. var result = new Quaternion();
  1636. Quaternion.FromRotationMatrixToRef(matrix, result);
  1637. return result;
  1638. };
  1639. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  1640. var data = matrix.m;
  1641. var m11 = data[0], m12 = data[4], m13 = data[8];
  1642. var m21 = data[1], m22 = data[5], m23 = data[9];
  1643. var m31 = data[2], m32 = data[6], m33 = data[10];
  1644. var trace = m11 + m22 + m33;
  1645. var s;
  1646. if (trace > 0) {
  1647. s = 0.5 / Math.sqrt(trace + 1.0);
  1648. result.w = 0.25 / s;
  1649. result.x = (m32 - m23) * s;
  1650. result.y = (m13 - m31) * s;
  1651. result.z = (m21 - m12) * s;
  1652. }
  1653. else if (m11 > m22 && m11 > m33) {
  1654. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  1655. result.w = (m32 - m23) / s;
  1656. result.x = 0.25 * s;
  1657. result.y = (m12 + m21) / s;
  1658. result.z = (m13 + m31) / s;
  1659. }
  1660. else if (m22 > m33) {
  1661. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  1662. result.w = (m13 - m31) / s;
  1663. result.x = (m12 + m21) / s;
  1664. result.y = 0.25 * s;
  1665. result.z = (m23 + m32) / s;
  1666. }
  1667. else {
  1668. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  1669. result.w = (m21 - m12) / s;
  1670. result.x = (m13 + m31) / s;
  1671. result.y = (m23 + m32) / s;
  1672. result.z = 0.25 * s;
  1673. }
  1674. };
  1675. Quaternion.Inverse = function (q) {
  1676. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  1677. };
  1678. Quaternion.Identity = function () {
  1679. return new Quaternion(0, 0, 0, 1);
  1680. };
  1681. Quaternion.RotationAxis = function (axis, angle) {
  1682. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  1683. };
  1684. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  1685. var sin = Math.sin(angle / 2);
  1686. axis.normalize();
  1687. result.w = Math.cos(angle / 2);
  1688. result.x = axis.x * sin;
  1689. result.y = axis.y * sin;
  1690. result.z = axis.z * sin;
  1691. return result;
  1692. };
  1693. Quaternion.FromArray = function (array, offset) {
  1694. if (!offset) {
  1695. offset = 0;
  1696. }
  1697. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1698. };
  1699. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  1700. var q = new Quaternion();
  1701. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  1702. return q;
  1703. };
  1704. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  1705. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  1706. var halfRoll = roll * 0.5;
  1707. var halfPitch = pitch * 0.5;
  1708. var halfYaw = yaw * 0.5;
  1709. var sinRoll = Math.sin(halfRoll);
  1710. var cosRoll = Math.cos(halfRoll);
  1711. var sinPitch = Math.sin(halfPitch);
  1712. var cosPitch = Math.cos(halfPitch);
  1713. var sinYaw = Math.sin(halfYaw);
  1714. var cosYaw = Math.cos(halfYaw);
  1715. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  1716. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  1717. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  1718. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  1719. };
  1720. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  1721. var result = new Quaternion();
  1722. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  1723. return result;
  1724. };
  1725. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  1726. // Produces a quaternion from Euler angles in the z-x-z orientation
  1727. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  1728. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  1729. var halfBeta = beta * 0.5;
  1730. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1731. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  1732. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1733. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  1734. };
  1735. Quaternion.Slerp = function (left, right, amount) {
  1736. var result = Quaternion.Identity();
  1737. Quaternion.SlerpToRef(left, right, amount, result);
  1738. return result;
  1739. };
  1740. Quaternion.SlerpToRef = function (left, right, amount, result) {
  1741. var num2;
  1742. var num3;
  1743. var num = amount;
  1744. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  1745. var flag = false;
  1746. if (num4 < 0) {
  1747. flag = true;
  1748. num4 = -num4;
  1749. }
  1750. if (num4 > 0.999999) {
  1751. num3 = 1 - num;
  1752. num2 = flag ? -num : num;
  1753. }
  1754. else {
  1755. var num5 = Math.acos(num4);
  1756. var num6 = (1.0 / Math.sin(num5));
  1757. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  1758. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  1759. }
  1760. result.x = (num3 * left.x) + (num2 * right.x);
  1761. result.y = (num3 * left.y) + (num2 * right.y);
  1762. result.z = (num3 * left.z) + (num2 * right.z);
  1763. result.w = (num3 * left.w) + (num2 * right.w);
  1764. };
  1765. return Quaternion;
  1766. }());
  1767. BABYLON.Quaternion = Quaternion;
  1768. var Matrix = (function () {
  1769. function Matrix() {
  1770. this.m = new Float32Array(16);
  1771. }
  1772. // Properties
  1773. Matrix.prototype.isIdentity = function () {
  1774. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[10] !== 1.0 || this.m[15] !== 1.0)
  1775. return false;
  1776. if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  1777. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  1778. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  1779. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0)
  1780. return false;
  1781. return true;
  1782. };
  1783. Matrix.prototype.determinant = function () {
  1784. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  1785. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  1786. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  1787. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  1788. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  1789. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  1790. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  1791. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  1792. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  1793. };
  1794. // Methods
  1795. Matrix.prototype.toArray = function () {
  1796. return this.m;
  1797. };
  1798. Matrix.prototype.asArray = function () {
  1799. return this.toArray();
  1800. };
  1801. Matrix.prototype.invert = function () {
  1802. this.invertToRef(this);
  1803. return this;
  1804. };
  1805. Matrix.prototype.reset = function () {
  1806. for (var index = 0; index < 16; index++) {
  1807. this.m[index] = 0;
  1808. }
  1809. return this;
  1810. };
  1811. Matrix.prototype.add = function (other) {
  1812. var result = new Matrix();
  1813. this.addToRef(other, result);
  1814. return result;
  1815. };
  1816. Matrix.prototype.addToRef = function (other, result) {
  1817. for (var index = 0; index < 16; index++) {
  1818. result.m[index] = this.m[index] + other.m[index];
  1819. }
  1820. return this;
  1821. };
  1822. Matrix.prototype.addToSelf = function (other) {
  1823. for (var index = 0; index < 16; index++) {
  1824. this.m[index] += other.m[index];
  1825. }
  1826. return this;
  1827. };
  1828. Matrix.prototype.invertToRef = function (other) {
  1829. var l1 = this.m[0];
  1830. var l2 = this.m[1];
  1831. var l3 = this.m[2];
  1832. var l4 = this.m[3];
  1833. var l5 = this.m[4];
  1834. var l6 = this.m[5];
  1835. var l7 = this.m[6];
  1836. var l8 = this.m[7];
  1837. var l9 = this.m[8];
  1838. var l10 = this.m[9];
  1839. var l11 = this.m[10];
  1840. var l12 = this.m[11];
  1841. var l13 = this.m[12];
  1842. var l14 = this.m[13];
  1843. var l15 = this.m[14];
  1844. var l16 = this.m[15];
  1845. var l17 = (l11 * l16) - (l12 * l15);
  1846. var l18 = (l10 * l16) - (l12 * l14);
  1847. var l19 = (l10 * l15) - (l11 * l14);
  1848. var l20 = (l9 * l16) - (l12 * l13);
  1849. var l21 = (l9 * l15) - (l11 * l13);
  1850. var l22 = (l9 * l14) - (l10 * l13);
  1851. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  1852. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  1853. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  1854. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  1855. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  1856. var l28 = (l7 * l16) - (l8 * l15);
  1857. var l29 = (l6 * l16) - (l8 * l14);
  1858. var l30 = (l6 * l15) - (l7 * l14);
  1859. var l31 = (l5 * l16) - (l8 * l13);
  1860. var l32 = (l5 * l15) - (l7 * l13);
  1861. var l33 = (l5 * l14) - (l6 * l13);
  1862. var l34 = (l7 * l12) - (l8 * l11);
  1863. var l35 = (l6 * l12) - (l8 * l10);
  1864. var l36 = (l6 * l11) - (l7 * l10);
  1865. var l37 = (l5 * l12) - (l8 * l9);
  1866. var l38 = (l5 * l11) - (l7 * l9);
  1867. var l39 = (l5 * l10) - (l6 * l9);
  1868. other.m[0] = l23 * l27;
  1869. other.m[4] = l24 * l27;
  1870. other.m[8] = l25 * l27;
  1871. other.m[12] = l26 * l27;
  1872. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  1873. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  1874. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  1875. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  1876. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  1877. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  1878. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  1879. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  1880. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  1881. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  1882. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  1883. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  1884. return this;
  1885. };
  1886. Matrix.prototype.setTranslation = function (vector3) {
  1887. this.m[12] = vector3.x;
  1888. this.m[13] = vector3.y;
  1889. this.m[14] = vector3.z;
  1890. return this;
  1891. };
  1892. Matrix.prototype.getTranslation = function () {
  1893. return new Vector3(this.m[12], this.m[13], this.m[14]);
  1894. };
  1895. Matrix.prototype.multiply = function (other) {
  1896. var result = new Matrix();
  1897. this.multiplyToRef(other, result);
  1898. return result;
  1899. };
  1900. Matrix.prototype.copyFrom = function (other) {
  1901. for (var index = 0; index < 16; index++) {
  1902. this.m[index] = other.m[index];
  1903. }
  1904. return this;
  1905. };
  1906. Matrix.prototype.copyToArray = function (array, offset) {
  1907. if (offset === void 0) { offset = 0; }
  1908. for (var index = 0; index < 16; index++) {
  1909. array[offset + index] = this.m[index];
  1910. }
  1911. return this;
  1912. };
  1913. Matrix.prototype.multiplyToRef = function (other, result) {
  1914. this.multiplyToArray(other, result.m, 0);
  1915. return this;
  1916. };
  1917. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  1918. var tm0 = this.m[0];
  1919. var tm1 = this.m[1];
  1920. var tm2 = this.m[2];
  1921. var tm3 = this.m[3];
  1922. var tm4 = this.m[4];
  1923. var tm5 = this.m[5];
  1924. var tm6 = this.m[6];
  1925. var tm7 = this.m[7];
  1926. var tm8 = this.m[8];
  1927. var tm9 = this.m[9];
  1928. var tm10 = this.m[10];
  1929. var tm11 = this.m[11];
  1930. var tm12 = this.m[12];
  1931. var tm13 = this.m[13];
  1932. var tm14 = this.m[14];
  1933. var tm15 = this.m[15];
  1934. var om0 = other.m[0];
  1935. var om1 = other.m[1];
  1936. var om2 = other.m[2];
  1937. var om3 = other.m[3];
  1938. var om4 = other.m[4];
  1939. var om5 = other.m[5];
  1940. var om6 = other.m[6];
  1941. var om7 = other.m[7];
  1942. var om8 = other.m[8];
  1943. var om9 = other.m[9];
  1944. var om10 = other.m[10];
  1945. var om11 = other.m[11];
  1946. var om12 = other.m[12];
  1947. var om13 = other.m[13];
  1948. var om14 = other.m[14];
  1949. var om15 = other.m[15];
  1950. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  1951. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  1952. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  1953. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  1954. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  1955. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  1956. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  1957. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  1958. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  1959. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  1960. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  1961. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  1962. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  1963. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  1964. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  1965. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  1966. return this;
  1967. };
  1968. Matrix.prototype.equals = function (value) {
  1969. return value &&
  1970. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  1971. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  1972. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  1973. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  1974. };
  1975. Matrix.prototype.clone = function () {
  1976. 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]);
  1977. };
  1978. Matrix.prototype.getClassName = function () {
  1979. return "Matrix";
  1980. };
  1981. Matrix.prototype.getHashCode = function () {
  1982. var hash = this.m[0] || 0;
  1983. for (var i = 1; i < 16; i++) {
  1984. hash = (hash * 397) ^ (this.m[i] || 0);
  1985. }
  1986. return hash;
  1987. };
  1988. Matrix.prototype.decompose = function (scale, rotation, translation) {
  1989. translation.x = this.m[12];
  1990. translation.y = this.m[13];
  1991. translation.z = this.m[14];
  1992. var xs = MathTools.Sign(this.m[0] * this.m[1] * this.m[2] * this.m[3]) < 0 ? -1 : 1;
  1993. var ys = MathTools.Sign(this.m[4] * this.m[5] * this.m[6] * this.m[7]) < 0 ? -1 : 1;
  1994. var zs = MathTools.Sign(this.m[8] * this.m[9] * this.m[10] * this.m[11]) < 0 ? -1 : 1;
  1995. scale.x = xs * Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  1996. scale.y = ys * Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  1997. scale.z = zs * Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  1998. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  1999. rotation.x = 0;
  2000. rotation.y = 0;
  2001. rotation.z = 0;
  2002. rotation.w = 1;
  2003. return false;
  2004. }
  2005. Matrix.FromValuesToRef(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, Tmp.Matrix[0]);
  2006. Quaternion.FromRotationMatrixToRef(Tmp.Matrix[0], rotation);
  2007. return true;
  2008. };
  2009. Matrix.prototype.getRotationMatrix = function () {
  2010. var result = Matrix.Identity();
  2011. this.getRotationMatrixToRef(result);
  2012. return result;
  2013. };
  2014. Matrix.prototype.getRotationMatrixToRef = function (result) {
  2015. var m = this.m;
  2016. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  2017. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  2018. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  2019. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  2020. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  2021. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  2022. Matrix.FromValuesToRef(m[0] / sx, m[1] / sx, m[2] / sx, 0, m[4] / sy, m[5] / sy, m[6] / sy, 0, m[8] / sz, m[9] / sz, m[10] / sz, 0, 0, 0, 0, 1, result);
  2023. };
  2024. // Statics
  2025. Matrix.FromArray = function (array, offset) {
  2026. var result = new Matrix();
  2027. if (!offset) {
  2028. offset = 0;
  2029. }
  2030. Matrix.FromArrayToRef(array, offset, result);
  2031. return result;
  2032. };
  2033. Matrix.FromArrayToRef = function (array, offset, result) {
  2034. for (var index = 0; index < 16; index++) {
  2035. result.m[index] = array[index + offset];
  2036. }
  2037. };
  2038. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  2039. for (var index = 0; index < 16; index++) {
  2040. result.m[index] = array[index + offset] * scale;
  2041. }
  2042. };
  2043. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  2044. result.m[0] = initialM11;
  2045. result.m[1] = initialM12;
  2046. result.m[2] = initialM13;
  2047. result.m[3] = initialM14;
  2048. result.m[4] = initialM21;
  2049. result.m[5] = initialM22;
  2050. result.m[6] = initialM23;
  2051. result.m[7] = initialM24;
  2052. result.m[8] = initialM31;
  2053. result.m[9] = initialM32;
  2054. result.m[10] = initialM33;
  2055. result.m[11] = initialM34;
  2056. result.m[12] = initialM41;
  2057. result.m[13] = initialM42;
  2058. result.m[14] = initialM43;
  2059. result.m[15] = initialM44;
  2060. };
  2061. Matrix.prototype.getRow = function (index) {
  2062. if (index < 0 || index > 3) {
  2063. return null;
  2064. }
  2065. var i = index * 4;
  2066. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  2067. };
  2068. Matrix.prototype.setRow = function (index, row) {
  2069. if (index < 0 || index > 3) {
  2070. return this;
  2071. }
  2072. var i = index * 4;
  2073. this.m[i + 0] = row.x;
  2074. this.m[i + 1] = row.y;
  2075. this.m[i + 2] = row.z;
  2076. this.m[i + 3] = row.w;
  2077. return this;
  2078. };
  2079. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  2080. var result = new Matrix();
  2081. result.m[0] = initialM11;
  2082. result.m[1] = initialM12;
  2083. result.m[2] = initialM13;
  2084. result.m[3] = initialM14;
  2085. result.m[4] = initialM21;
  2086. result.m[5] = initialM22;
  2087. result.m[6] = initialM23;
  2088. result.m[7] = initialM24;
  2089. result.m[8] = initialM31;
  2090. result.m[9] = initialM32;
  2091. result.m[10] = initialM33;
  2092. result.m[11] = initialM34;
  2093. result.m[12] = initialM41;
  2094. result.m[13] = initialM42;
  2095. result.m[14] = initialM43;
  2096. result.m[15] = initialM44;
  2097. return result;
  2098. };
  2099. Matrix.Compose = function (scale, rotation, translation) {
  2100. var result = Matrix.FromValues(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1);
  2101. var rotationMatrix = Matrix.Identity();
  2102. rotation.toRotationMatrix(rotationMatrix);
  2103. result = result.multiply(rotationMatrix);
  2104. result.setTranslation(translation);
  2105. return result;
  2106. };
  2107. Matrix.Identity = function () {
  2108. return Matrix.FromValues(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0);
  2109. };
  2110. Matrix.IdentityToRef = function (result) {
  2111. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, result);
  2112. };
  2113. Matrix.Zero = function () {
  2114. return Matrix.FromValues(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0);
  2115. };
  2116. Matrix.RotationX = function (angle) {
  2117. var result = new Matrix();
  2118. Matrix.RotationXToRef(angle, result);
  2119. return result;
  2120. };
  2121. Matrix.Invert = function (source) {
  2122. var result = new Matrix();
  2123. source.invertToRef(result);
  2124. return result;
  2125. };
  2126. Matrix.RotationXToRef = function (angle, result) {
  2127. var s = Math.sin(angle);
  2128. var c = Math.cos(angle);
  2129. result.m[0] = 1.0;
  2130. result.m[15] = 1.0;
  2131. result.m[5] = c;
  2132. result.m[10] = c;
  2133. result.m[9] = -s;
  2134. result.m[6] = s;
  2135. result.m[1] = 0;
  2136. result.m[2] = 0;
  2137. result.m[3] = 0;
  2138. result.m[4] = 0;
  2139. result.m[7] = 0;
  2140. result.m[8] = 0;
  2141. result.m[11] = 0;
  2142. result.m[12] = 0;
  2143. result.m[13] = 0;
  2144. result.m[14] = 0;
  2145. };
  2146. Matrix.RotationY = function (angle) {
  2147. var result = new Matrix();
  2148. Matrix.RotationYToRef(angle, result);
  2149. return result;
  2150. };
  2151. Matrix.RotationYToRef = function (angle, result) {
  2152. var s = Math.sin(angle);
  2153. var c = Math.cos(angle);
  2154. result.m[5] = 1.0;
  2155. result.m[15] = 1.0;
  2156. result.m[0] = c;
  2157. result.m[2] = -s;
  2158. result.m[8] = s;
  2159. result.m[10] = c;
  2160. result.m[1] = 0;
  2161. result.m[3] = 0;
  2162. result.m[4] = 0;
  2163. result.m[6] = 0;
  2164. result.m[7] = 0;
  2165. result.m[9] = 0;
  2166. result.m[11] = 0;
  2167. result.m[12] = 0;
  2168. result.m[13] = 0;
  2169. result.m[14] = 0;
  2170. };
  2171. Matrix.RotationZ = function (angle) {
  2172. var result = new Matrix();
  2173. Matrix.RotationZToRef(angle, result);
  2174. return result;
  2175. };
  2176. Matrix.RotationZToRef = function (angle, result) {
  2177. var s = Math.sin(angle);
  2178. var c = Math.cos(angle);
  2179. result.m[10] = 1.0;
  2180. result.m[15] = 1.0;
  2181. result.m[0] = c;
  2182. result.m[1] = s;
  2183. result.m[4] = -s;
  2184. result.m[5] = c;
  2185. result.m[2] = 0;
  2186. result.m[3] = 0;
  2187. result.m[6] = 0;
  2188. result.m[7] = 0;
  2189. result.m[8] = 0;
  2190. result.m[9] = 0;
  2191. result.m[11] = 0;
  2192. result.m[12] = 0;
  2193. result.m[13] = 0;
  2194. result.m[14] = 0;
  2195. };
  2196. Matrix.RotationAxis = function (axis, angle) {
  2197. var result = Matrix.Zero();
  2198. Matrix.RotationAxisToRef(axis, angle, result);
  2199. return result;
  2200. };
  2201. Matrix.RotationAxisToRef = function (axis, angle, result) {
  2202. var s = Math.sin(-angle);
  2203. var c = Math.cos(-angle);
  2204. var c1 = 1 - c;
  2205. axis.normalize();
  2206. result.m[0] = (axis.x * axis.x) * c1 + c;
  2207. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  2208. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  2209. result.m[3] = 0.0;
  2210. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  2211. result.m[5] = (axis.y * axis.y) * c1 + c;
  2212. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  2213. result.m[7] = 0.0;
  2214. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  2215. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  2216. result.m[10] = (axis.z * axis.z) * c1 + c;
  2217. result.m[11] = 0.0;
  2218. result.m[15] = 1.0;
  2219. };
  2220. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2221. var result = new Matrix();
  2222. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  2223. return result;
  2224. };
  2225. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2226. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  2227. this._tempQuaternion.toRotationMatrix(result);
  2228. };
  2229. Matrix.Scaling = function (x, y, z) {
  2230. var result = Matrix.Zero();
  2231. Matrix.ScalingToRef(x, y, z, result);
  2232. return result;
  2233. };
  2234. Matrix.ScalingToRef = function (x, y, z, result) {
  2235. result.m[0] = x;
  2236. result.m[1] = 0;
  2237. result.m[2] = 0;
  2238. result.m[3] = 0;
  2239. result.m[4] = 0;
  2240. result.m[5] = y;
  2241. result.m[6] = 0;
  2242. result.m[7] = 0;
  2243. result.m[8] = 0;
  2244. result.m[9] = 0;
  2245. result.m[10] = z;
  2246. result.m[11] = 0;
  2247. result.m[12] = 0;
  2248. result.m[13] = 0;
  2249. result.m[14] = 0;
  2250. result.m[15] = 1.0;
  2251. };
  2252. Matrix.Translation = function (x, y, z) {
  2253. var result = Matrix.Identity();
  2254. Matrix.TranslationToRef(x, y, z, result);
  2255. return result;
  2256. };
  2257. Matrix.TranslationToRef = function (x, y, z, result) {
  2258. Matrix.FromValuesToRef(1.0, 0, 0, 0, 0, 1.0, 0, 0, 0, 0, 1.0, 0, x, y, z, 1.0, result);
  2259. };
  2260. Matrix.Lerp = function (startValue, endValue, gradient) {
  2261. var result = Matrix.Zero();
  2262. for (var index = 0; index < 16; index++) {
  2263. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  2264. }
  2265. return result;
  2266. };
  2267. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  2268. var startScale = new Vector3(0, 0, 0);
  2269. var startRotation = new Quaternion();
  2270. var startTranslation = new Vector3(0, 0, 0);
  2271. startValue.decompose(startScale, startRotation, startTranslation);
  2272. var endScale = new Vector3(0, 0, 0);
  2273. var endRotation = new Quaternion();
  2274. var endTranslation = new Vector3(0, 0, 0);
  2275. endValue.decompose(endScale, endRotation, endTranslation);
  2276. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  2277. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  2278. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  2279. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  2280. };
  2281. Matrix.LookAtLH = function (eye, target, up) {
  2282. var result = Matrix.Zero();
  2283. Matrix.LookAtLHToRef(eye, target, up, result);
  2284. return result;
  2285. };
  2286. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  2287. // Z axis
  2288. target.subtractToRef(eye, this._zAxis);
  2289. this._zAxis.normalize();
  2290. // X axis
  2291. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2292. if (this._xAxis.lengthSquared() === 0) {
  2293. this._xAxis.x = 1.0;
  2294. }
  2295. else {
  2296. this._xAxis.normalize();
  2297. }
  2298. // Y axis
  2299. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2300. this._yAxis.normalize();
  2301. // Eye angles
  2302. var ex = -Vector3.Dot(this._xAxis, eye);
  2303. var ey = -Vector3.Dot(this._yAxis, eye);
  2304. var ez = -Vector3.Dot(this._zAxis, eye);
  2305. 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);
  2306. };
  2307. Matrix.LookAtRH = function (eye, target, up) {
  2308. var result = Matrix.Zero();
  2309. Matrix.LookAtRHToRef(eye, target, up, result);
  2310. return result;
  2311. };
  2312. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  2313. // Z axis
  2314. eye.subtractToRef(target, this._zAxis);
  2315. this._zAxis.normalize();
  2316. // X axis
  2317. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  2318. if (this._xAxis.lengthSquared() === 0) {
  2319. this._xAxis.x = 1.0;
  2320. }
  2321. else {
  2322. this._xAxis.normalize();
  2323. }
  2324. // Y axis
  2325. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  2326. this._yAxis.normalize();
  2327. // Eye angles
  2328. var ex = -Vector3.Dot(this._xAxis, eye);
  2329. var ey = -Vector3.Dot(this._yAxis, eye);
  2330. var ez = -Vector3.Dot(this._zAxis, eye);
  2331. 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);
  2332. };
  2333. Matrix.OrthoLH = function (width, height, znear, zfar) {
  2334. var matrix = Matrix.Zero();
  2335. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  2336. return matrix;
  2337. };
  2338. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  2339. var n = znear;
  2340. var f = zfar;
  2341. var a = 2.0 / width;
  2342. var b = 2.0 / height;
  2343. var c = 2.0 / (f - n);
  2344. var d = -(f + n) / (f - n);
  2345. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, 0, 0, d, 1, result);
  2346. };
  2347. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  2348. var matrix = Matrix.Zero();
  2349. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  2350. return matrix;
  2351. };
  2352. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2353. var n = znear;
  2354. var f = zfar;
  2355. var a = 2.0 / (right - left);
  2356. var b = 2.0 / (top - bottom);
  2357. var c = 2.0 / (f - n);
  2358. var d = -(f + n) / (f - n);
  2359. var i0 = (left + right) / (left - right);
  2360. var i1 = (top + bottom) / (bottom - top);
  2361. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 0, i0, i1, d, 1, result);
  2362. };
  2363. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  2364. var matrix = Matrix.Zero();
  2365. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  2366. return matrix;
  2367. };
  2368. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  2369. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  2370. result.m[10] *= -1.0;
  2371. };
  2372. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  2373. var matrix = Matrix.Zero();
  2374. var n = znear;
  2375. var f = zfar;
  2376. var a = 2.0 * n / width;
  2377. var b = 2.0 * n / height;
  2378. var c = (f + n) / (f - n);
  2379. var d = -2.0 * f * n / (f - n);
  2380. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, matrix);
  2381. return matrix;
  2382. };
  2383. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  2384. var matrix = Matrix.Zero();
  2385. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  2386. return matrix;
  2387. };
  2388. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2389. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2390. var n = znear;
  2391. var f = zfar;
  2392. var t = 1.0 / (Math.tan(fov * 0.5));
  2393. var a = isVerticalFovFixed ? (t / aspect) : t;
  2394. var b = isVerticalFovFixed ? t : (t * aspect);
  2395. var c = (f + n) / (f - n);
  2396. var d = -2.0 * f * n / (f - n);
  2397. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, 1, 0, 0, d, 0, result);
  2398. };
  2399. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  2400. var matrix = Matrix.Zero();
  2401. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  2402. return matrix;
  2403. };
  2404. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  2405. //alternatively this could be expressed as:
  2406. // m = PerspectiveFovLHToRef
  2407. // m[10] *= -1.0;
  2408. // m[11] *= -1.0;
  2409. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2410. var n = znear;
  2411. var f = zfar;
  2412. var t = 1.0 / (Math.tan(fov * 0.5));
  2413. var a = isVerticalFovFixed ? (t / aspect) : t;
  2414. var b = isVerticalFovFixed ? t : (t * aspect);
  2415. var c = -(f + n) / (f - n);
  2416. var d = -2 * f * n / (f - n);
  2417. BABYLON.Matrix.FromValuesToRef(a, 0, 0, 0, 0, b, 0, 0, 0, 0, c, -1, 0, 0, d, 0, result);
  2418. };
  2419. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, isVerticalFovFixed) {
  2420. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  2421. //left handed
  2422. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  2423. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  2424. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  2425. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  2426. var xScale = 2.0 / (leftTan + rightTan);
  2427. var yScale = 2.0 / (upTan + downTan);
  2428. result.m[0] = xScale;
  2429. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  2430. result.m[5] = yScale;
  2431. result.m[6] = result.m[7] = 0.0;
  2432. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  2433. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  2434. result.m[10] = -(znear + zfar) / (zfar - znear);
  2435. // result.m[10] = -zfar / (znear - zfar);
  2436. result.m[11] = 1.0;
  2437. result.m[12] = result.m[13] = result.m[15] = 0.0;
  2438. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  2439. // result.m[14] = (znear * zfar) / (znear - zfar);
  2440. };
  2441. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  2442. var cw = viewport.width;
  2443. var ch = viewport.height;
  2444. var cx = viewport.x;
  2445. var cy = viewport.y;
  2446. 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);
  2447. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  2448. };
  2449. Matrix.GetAsMatrix2x2 = function (matrix) {
  2450. return new Float32Array([
  2451. matrix.m[0], matrix.m[1],
  2452. matrix.m[4], matrix.m[5]
  2453. ]);
  2454. };
  2455. Matrix.GetAsMatrix3x3 = function (matrix) {
  2456. return new Float32Array([
  2457. matrix.m[0], matrix.m[1], matrix.m[2],
  2458. matrix.m[4], matrix.m[5], matrix.m[6],
  2459. matrix.m[8], matrix.m[9], matrix.m[10]
  2460. ]);
  2461. };
  2462. Matrix.Transpose = function (matrix) {
  2463. var result = new Matrix();
  2464. result.m[0] = matrix.m[0];
  2465. result.m[1] = matrix.m[4];
  2466. result.m[2] = matrix.m[8];
  2467. result.m[3] = matrix.m[12];
  2468. result.m[4] = matrix.m[1];
  2469. result.m[5] = matrix.m[5];
  2470. result.m[6] = matrix.m[9];
  2471. result.m[7] = matrix.m[13];
  2472. result.m[8] = matrix.m[2];
  2473. result.m[9] = matrix.m[6];
  2474. result.m[10] = matrix.m[10];
  2475. result.m[11] = matrix.m[14];
  2476. result.m[12] = matrix.m[3];
  2477. result.m[13] = matrix.m[7];
  2478. result.m[14] = matrix.m[11];
  2479. result.m[15] = matrix.m[15];
  2480. return result;
  2481. };
  2482. Matrix.Reflection = function (plane) {
  2483. var matrix = new Matrix();
  2484. Matrix.ReflectionToRef(plane, matrix);
  2485. return matrix;
  2486. };
  2487. Matrix.ReflectionToRef = function (plane, result) {
  2488. plane.normalize();
  2489. var x = plane.normal.x;
  2490. var y = plane.normal.y;
  2491. var z = plane.normal.z;
  2492. var temp = -2 * x;
  2493. var temp2 = -2 * y;
  2494. var temp3 = -2 * z;
  2495. result.m[0] = (temp * x) + 1;
  2496. result.m[1] = temp2 * x;
  2497. result.m[2] = temp3 * x;
  2498. result.m[3] = 0.0;
  2499. result.m[4] = temp * y;
  2500. result.m[5] = (temp2 * y) + 1;
  2501. result.m[6] = temp3 * y;
  2502. result.m[7] = 0.0;
  2503. result.m[8] = temp * z;
  2504. result.m[9] = temp2 * z;
  2505. result.m[10] = (temp3 * z) + 1;
  2506. result.m[11] = 0.0;
  2507. result.m[12] = temp * plane.d;
  2508. result.m[13] = temp2 * plane.d;
  2509. result.m[14] = temp3 * plane.d;
  2510. result.m[15] = 1.0;
  2511. };
  2512. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, mat) {
  2513. mat.m[0] = xaxis.x;
  2514. mat.m[1] = xaxis.y;
  2515. mat.m[2] = xaxis.z;
  2516. mat.m[3] = 0;
  2517. mat.m[4] = yaxis.x;
  2518. mat.m[5] = yaxis.y;
  2519. mat.m[6] = yaxis.z;
  2520. mat.m[7] = 0;
  2521. mat.m[8] = zaxis.x;
  2522. mat.m[9] = zaxis.y;
  2523. mat.m[10] = zaxis.z;
  2524. mat.m[11] = 0;
  2525. mat.m[12] = 0;
  2526. mat.m[13] = 0;
  2527. mat.m[14] = 0;
  2528. mat.m[15] = 1;
  2529. };
  2530. Matrix.FromQuaternionToRef = function (quat, result) {
  2531. var xx = quat.x * quat.x;
  2532. var yy = quat.y * quat.y;
  2533. var zz = quat.z * quat.z;
  2534. var xy = quat.x * quat.y;
  2535. var zw = quat.z * quat.w;
  2536. var zx = quat.z * quat.x;
  2537. var yw = quat.y * quat.w;
  2538. var yz = quat.y * quat.z;
  2539. var xw = quat.x * quat.w;
  2540. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2541. result.m[1] = 2.0 * (xy + zw);
  2542. result.m[2] = 2.0 * (zx - yw);
  2543. result.m[3] = 0;
  2544. result.m[4] = 2.0 * (xy - zw);
  2545. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2546. result.m[6] = 2.0 * (yz + xw);
  2547. result.m[7] = 0;
  2548. result.m[8] = 2.0 * (zx + yw);
  2549. result.m[9] = 2.0 * (yz - xw);
  2550. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2551. result.m[11] = 0;
  2552. result.m[12] = 0;
  2553. result.m[13] = 0;
  2554. result.m[14] = 0;
  2555. result.m[15] = 1.0;
  2556. };
  2557. return Matrix;
  2558. }());
  2559. Matrix._tempQuaternion = new Quaternion();
  2560. Matrix._xAxis = Vector3.Zero();
  2561. Matrix._yAxis = Vector3.Zero();
  2562. Matrix._zAxis = Vector3.Zero();
  2563. BABYLON.Matrix = Matrix;
  2564. var Plane = (function () {
  2565. function Plane(a, b, c, d) {
  2566. this.normal = new Vector3(a, b, c);
  2567. this.d = d;
  2568. }
  2569. Plane.prototype.asArray = function () {
  2570. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  2571. };
  2572. // Methods
  2573. Plane.prototype.clone = function () {
  2574. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  2575. };
  2576. Plane.prototype.getClassName = function () {
  2577. return "Plane";
  2578. };
  2579. Plane.prototype.getHashCode = function () {
  2580. var hash = this.normal.getHashCode();
  2581. hash = (hash * 397) ^ (this.d || 0);
  2582. return hash;
  2583. };
  2584. Plane.prototype.normalize = function () {
  2585. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  2586. var magnitude = 0;
  2587. if (norm !== 0) {
  2588. magnitude = 1.0 / norm;
  2589. }
  2590. this.normal.x *= magnitude;
  2591. this.normal.y *= magnitude;
  2592. this.normal.z *= magnitude;
  2593. this.d *= magnitude;
  2594. return this;
  2595. };
  2596. Plane.prototype.transform = function (transformation) {
  2597. var transposedMatrix = Matrix.Transpose(transformation);
  2598. var x = this.normal.x;
  2599. var y = this.normal.y;
  2600. var z = this.normal.z;
  2601. var d = this.d;
  2602. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  2603. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  2604. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  2605. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  2606. return new Plane(normalX, normalY, normalZ, finalD);
  2607. };
  2608. Plane.prototype.dotCoordinate = function (point) {
  2609. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  2610. };
  2611. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  2612. var x1 = point2.x - point1.x;
  2613. var y1 = point2.y - point1.y;
  2614. var z1 = point2.z - point1.z;
  2615. var x2 = point3.x - point1.x;
  2616. var y2 = point3.y - point1.y;
  2617. var z2 = point3.z - point1.z;
  2618. var yz = (y1 * z2) - (z1 * y2);
  2619. var xz = (z1 * x2) - (x1 * z2);
  2620. var xy = (x1 * y2) - (y1 * x2);
  2621. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  2622. var invPyth;
  2623. if (pyth !== 0) {
  2624. invPyth = 1.0 / pyth;
  2625. }
  2626. else {
  2627. invPyth = 0;
  2628. }
  2629. this.normal.x = yz * invPyth;
  2630. this.normal.y = xz * invPyth;
  2631. this.normal.z = xy * invPyth;
  2632. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  2633. return this;
  2634. };
  2635. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  2636. var dot = Vector3.Dot(this.normal, direction);
  2637. return (dot <= epsilon);
  2638. };
  2639. Plane.prototype.signedDistanceTo = function (point) {
  2640. return Vector3.Dot(point, this.normal) + this.d;
  2641. };
  2642. // Statics
  2643. Plane.FromArray = function (array) {
  2644. return new Plane(array[0], array[1], array[2], array[3]);
  2645. };
  2646. Plane.FromPoints = function (point1, point2, point3) {
  2647. var result = new Plane(0, 0, 0, 0);
  2648. result.copyFromPoints(point1, point2, point3);
  2649. return result;
  2650. };
  2651. Plane.FromPositionAndNormal = function (origin, normal) {
  2652. var result = new Plane(0, 0, 0, 0);
  2653. normal.normalize();
  2654. result.normal = normal;
  2655. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2656. return result;
  2657. };
  2658. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  2659. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  2660. return Vector3.Dot(point, normal) + d;
  2661. };
  2662. return Plane;
  2663. }());
  2664. BABYLON.Plane = Plane;
  2665. var Viewport = (function () {
  2666. function Viewport(x, y, width, height) {
  2667. this.x = x;
  2668. this.y = y;
  2669. this.width = width;
  2670. this.height = height;
  2671. }
  2672. Viewport.prototype.toGlobal = function (renderWidth, renderHeight) {
  2673. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  2674. };
  2675. return Viewport;
  2676. }());
  2677. BABYLON.Viewport = Viewport;
  2678. var Frustum = (function () {
  2679. function Frustum() {
  2680. }
  2681. Frustum.GetPlanes = function (transform) {
  2682. var frustumPlanes = [];
  2683. for (var index = 0; index < 6; index++) {
  2684. frustumPlanes.push(new Plane(0, 0, 0, 0));
  2685. }
  2686. Frustum.GetPlanesToRef(transform, frustumPlanes);
  2687. return frustumPlanes;
  2688. };
  2689. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  2690. // Near
  2691. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  2692. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  2693. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  2694. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  2695. frustumPlanes[0].normalize();
  2696. // Far
  2697. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  2698. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  2699. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  2700. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  2701. frustumPlanes[1].normalize();
  2702. // Left
  2703. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  2704. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  2705. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  2706. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  2707. frustumPlanes[2].normalize();
  2708. // Right
  2709. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  2710. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  2711. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  2712. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  2713. frustumPlanes[3].normalize();
  2714. // Top
  2715. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  2716. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  2717. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  2718. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  2719. frustumPlanes[4].normalize();
  2720. // Bottom
  2721. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  2722. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  2723. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  2724. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  2725. frustumPlanes[5].normalize();
  2726. };
  2727. return Frustum;
  2728. }());
  2729. BABYLON.Frustum = Frustum;
  2730. var Space;
  2731. (function (Space) {
  2732. Space[Space["LOCAL"] = 0] = "LOCAL";
  2733. Space[Space["WORLD"] = 1] = "WORLD";
  2734. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  2735. var Axis = (function () {
  2736. function Axis() {
  2737. }
  2738. return Axis;
  2739. }());
  2740. Axis.X = new Vector3(1, 0, 0);
  2741. Axis.Y = new Vector3(0, 1, 0);
  2742. Axis.Z = new Vector3(0, 0, 1);
  2743. BABYLON.Axis = Axis;
  2744. ;
  2745. var BezierCurve = (function () {
  2746. function BezierCurve() {
  2747. }
  2748. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  2749. // Extract X (which is equal to time here)
  2750. var f0 = 1 - 3 * x2 + 3 * x1;
  2751. var f1 = 3 * x2 - 6 * x1;
  2752. var f2 = 3 * x1;
  2753. var refinedT = t;
  2754. for (var i = 0; i < 5; i++) {
  2755. var refinedT2 = refinedT * refinedT;
  2756. var refinedT3 = refinedT2 * refinedT;
  2757. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  2758. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  2759. refinedT -= (x - t) * slope;
  2760. refinedT = Math.min(1, Math.max(0, refinedT));
  2761. }
  2762. // Resolve cubic bezier for the given x
  2763. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  2764. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  2765. Math.pow(refinedT, 3);
  2766. };
  2767. return BezierCurve;
  2768. }());
  2769. BABYLON.BezierCurve = BezierCurve;
  2770. var Orientation;
  2771. (function (Orientation) {
  2772. Orientation[Orientation["CW"] = 0] = "CW";
  2773. Orientation[Orientation["CCW"] = 1] = "CCW";
  2774. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  2775. var Angle = (function () {
  2776. function Angle(radians) {
  2777. var _this = this;
  2778. this.degrees = function () { return _this._radians * 180 / Math.PI; };
  2779. this.radians = function () { return _this._radians; };
  2780. this._radians = radians;
  2781. if (this._radians < 0)
  2782. this._radians += (2 * Math.PI);
  2783. }
  2784. Angle.BetweenTwoPoints = function (a, b) {
  2785. var delta = b.subtract(a);
  2786. var theta = Math.atan2(delta.y, delta.x);
  2787. return new Angle(theta);
  2788. };
  2789. Angle.FromRadians = function (radians) {
  2790. return new Angle(radians);
  2791. };
  2792. Angle.FromDegrees = function (degrees) {
  2793. return new Angle(degrees * Math.PI / 180);
  2794. };
  2795. return Angle;
  2796. }());
  2797. BABYLON.Angle = Angle;
  2798. var Arc2 = (function () {
  2799. function Arc2(startPoint, midPoint, endPoint) {
  2800. this.startPoint = startPoint;
  2801. this.midPoint = midPoint;
  2802. this.endPoint = endPoint;
  2803. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  2804. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  2805. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  2806. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  2807. 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);
  2808. this.radius = this.centerPoint.subtract(this.startPoint).length();
  2809. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  2810. var a1 = this.startAngle.degrees();
  2811. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  2812. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  2813. // angles correction
  2814. if (a2 - a1 > +180.0)
  2815. a2 -= 360.0;
  2816. if (a2 - a1 < -180.0)
  2817. a2 += 360.0;
  2818. if (a3 - a2 > +180.0)
  2819. a3 -= 360.0;
  2820. if (a3 - a2 < -180.0)
  2821. a3 += 360.0;
  2822. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  2823. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  2824. }
  2825. return Arc2;
  2826. }());
  2827. BABYLON.Arc2 = Arc2;
  2828. var Path2 = (function () {
  2829. function Path2(x, y) {
  2830. this._points = new Array();
  2831. this._length = 0;
  2832. this.closed = false;
  2833. this._points.push(new Vector2(x, y));
  2834. }
  2835. Path2.prototype.addLineTo = function (x, y) {
  2836. if (closed) {
  2837. //Tools.Error("cannot add lines to closed paths");
  2838. return this;
  2839. }
  2840. var newPoint = new Vector2(x, y);
  2841. var previousPoint = this._points[this._points.length - 1];
  2842. this._points.push(newPoint);
  2843. this._length += newPoint.subtract(previousPoint).length();
  2844. return this;
  2845. };
  2846. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  2847. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  2848. if (closed) {
  2849. //Tools.Error("cannot add arcs to closed paths");
  2850. return this;
  2851. }
  2852. var startPoint = this._points[this._points.length - 1];
  2853. var midPoint = new Vector2(midX, midY);
  2854. var endPoint = new Vector2(endX, endY);
  2855. var arc = new Arc2(startPoint, midPoint, endPoint);
  2856. var increment = arc.angle.radians() / numberOfSegments;
  2857. if (arc.orientation === Orientation.CW)
  2858. increment *= -1;
  2859. var currentAngle = arc.startAngle.radians() + increment;
  2860. for (var i = 0; i < numberOfSegments; i++) {
  2861. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  2862. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  2863. this.addLineTo(x, y);
  2864. currentAngle += increment;
  2865. }
  2866. return this;
  2867. };
  2868. Path2.prototype.close = function () {
  2869. this.closed = true;
  2870. return this;
  2871. };
  2872. Path2.prototype.length = function () {
  2873. var result = this._length;
  2874. if (!this.closed) {
  2875. var lastPoint = this._points[this._points.length - 1];
  2876. var firstPoint = this._points[0];
  2877. result += (firstPoint.subtract(lastPoint).length());
  2878. }
  2879. return result;
  2880. };
  2881. Path2.prototype.getPoints = function () {
  2882. return this._points;
  2883. };
  2884. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  2885. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  2886. //Tools.Error("normalized length position should be between 0 and 1.");
  2887. return Vector2.Zero();
  2888. }
  2889. var lengthPosition = normalizedLengthPosition * this.length();
  2890. var previousOffset = 0;
  2891. for (var i = 0; i < this._points.length; i++) {
  2892. var j = (i + 1) % this._points.length;
  2893. var a = this._points[i];
  2894. var b = this._points[j];
  2895. var bToA = b.subtract(a);
  2896. var nextOffset = (bToA.length() + previousOffset);
  2897. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  2898. var dir = bToA.normalize();
  2899. var localOffset = lengthPosition - previousOffset;
  2900. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  2901. }
  2902. previousOffset = nextOffset;
  2903. }
  2904. //Tools.Error("internal error");
  2905. return Vector2.Zero();
  2906. };
  2907. Path2.StartingAt = function (x, y) {
  2908. return new Path2(x, y);
  2909. };
  2910. return Path2;
  2911. }());
  2912. BABYLON.Path2 = Path2;
  2913. var Path3D = (function () {
  2914. /**
  2915. * new Path3D(path, normal, raw)
  2916. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  2917. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  2918. * path : an array of Vector3, the curve axis of the Path3D
  2919. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  2920. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  2921. */
  2922. function Path3D(path, firstNormal, raw) {
  2923. this.path = path;
  2924. this._curve = new Array();
  2925. this._distances = new Array();
  2926. this._tangents = new Array();
  2927. this._normals = new Array();
  2928. this._binormals = new Array();
  2929. for (var p = 0; p < path.length; p++) {
  2930. this._curve[p] = path[p].clone(); // hard copy
  2931. }
  2932. this._raw = raw || false;
  2933. this._compute(firstNormal);
  2934. }
  2935. /**
  2936. * Returns the Path3D array of successive Vector3 designing its curve.
  2937. */
  2938. Path3D.prototype.getCurve = function () {
  2939. return this._curve;
  2940. };
  2941. /**
  2942. * Returns an array populated with tangent vectors on each Path3D curve point.
  2943. */
  2944. Path3D.prototype.getTangents = function () {
  2945. return this._tangents;
  2946. };
  2947. /**
  2948. * Returns an array populated with normal vectors on each Path3D curve point.
  2949. */
  2950. Path3D.prototype.getNormals = function () {
  2951. return this._normals;
  2952. };
  2953. /**
  2954. * Returns an array populated with binormal vectors on each Path3D curve point.
  2955. */
  2956. Path3D.prototype.getBinormals = function () {
  2957. return this._binormals;
  2958. };
  2959. /**
  2960. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  2961. */
  2962. Path3D.prototype.getDistances = function () {
  2963. return this._distances;
  2964. };
  2965. /**
  2966. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  2967. * Returns the same object updated.
  2968. */
  2969. Path3D.prototype.update = function (path, firstNormal) {
  2970. for (var p = 0; p < path.length; p++) {
  2971. this._curve[p].x = path[p].x;
  2972. this._curve[p].y = path[p].y;
  2973. this._curve[p].z = path[p].z;
  2974. }
  2975. this._compute(firstNormal);
  2976. return this;
  2977. };
  2978. // private function compute() : computes tangents, normals and binormals
  2979. Path3D.prototype._compute = function (firstNormal) {
  2980. var l = this._curve.length;
  2981. // first and last tangents
  2982. this._tangents[0] = this._getFirstNonNullVector(0);
  2983. if (!this._raw) {
  2984. this._tangents[0].normalize();
  2985. }
  2986. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  2987. if (!this._raw) {
  2988. this._tangents[l - 1].normalize();
  2989. }
  2990. // normals and binormals at first point : arbitrary vector with _normalVector()
  2991. var tg0 = this._tangents[0];
  2992. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  2993. this._normals[0] = pp0;
  2994. if (!this._raw) {
  2995. this._normals[0].normalize();
  2996. }
  2997. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  2998. if (!this._raw) {
  2999. this._binormals[0].normalize();
  3000. }
  3001. this._distances[0] = 0.0;
  3002. // normals and binormals : next points
  3003. var prev; // previous vector (segment)
  3004. var cur; // current vector (segment)
  3005. var curTang; // current tangent
  3006. // previous normal
  3007. var prevBinor; // previous binormal
  3008. for (var i = 1; i < l; i++) {
  3009. // tangents
  3010. prev = this._getLastNonNullVector(i);
  3011. if (i < l - 1) {
  3012. cur = this._getFirstNonNullVector(i);
  3013. this._tangents[i] = prev.add(cur);
  3014. this._tangents[i].normalize();
  3015. }
  3016. this._distances[i] = this._distances[i - 1] + prev.length();
  3017. // normals and binormals
  3018. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  3019. curTang = this._tangents[i];
  3020. prevBinor = this._binormals[i - 1];
  3021. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  3022. if (!this._raw) {
  3023. this._normals[i].normalize();
  3024. }
  3025. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  3026. if (!this._raw) {
  3027. this._binormals[i].normalize();
  3028. }
  3029. }
  3030. };
  3031. // private function getFirstNonNullVector(index)
  3032. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  3033. Path3D.prototype._getFirstNonNullVector = function (index) {
  3034. var i = 1;
  3035. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  3036. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  3037. i++;
  3038. nNVector = this._curve[index + i].subtract(this._curve[index]);
  3039. }
  3040. return nNVector;
  3041. };
  3042. // private function getLastNonNullVector(index)
  3043. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  3044. Path3D.prototype._getLastNonNullVector = function (index) {
  3045. var i = 1;
  3046. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  3047. while (nLVector.length() === 0 && index > i + 1) {
  3048. i++;
  3049. nLVector = this._curve[index].subtract(this._curve[index - i]);
  3050. }
  3051. return nLVector;
  3052. };
  3053. // private function normalVector(v0, vt, va) :
  3054. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  3055. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  3056. Path3D.prototype._normalVector = function (v0, vt, va) {
  3057. var normal0;
  3058. var tgl = vt.length();
  3059. if (tgl === 0.0) {
  3060. tgl = 1.0;
  3061. }
  3062. if (va === undefined || va === null) {
  3063. var point;
  3064. if (!MathTools.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  3065. point = new Vector3(0.0, -1.0, 0.0);
  3066. }
  3067. else if (!MathTools.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  3068. point = new Vector3(1.0, 0.0, 0.0);
  3069. }
  3070. else if (!MathTools.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  3071. point = new Vector3(0.0, 0.0, 1.0);
  3072. }
  3073. normal0 = Vector3.Cross(vt, point);
  3074. }
  3075. else {
  3076. normal0 = Vector3.Cross(vt, va);
  3077. Vector3.CrossToRef(normal0, vt, normal0);
  3078. }
  3079. normal0.normalize();
  3080. return normal0;
  3081. };
  3082. return Path3D;
  3083. }());
  3084. BABYLON.Path3D = Path3D;
  3085. var Curve3 = (function () {
  3086. /**
  3087. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  3088. * A Curve3 is designed from a series of successive Vector3.
  3089. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  3090. */
  3091. function Curve3(points) {
  3092. this._length = 0.0;
  3093. this._points = points;
  3094. this._length = this._computeLength(points);
  3095. }
  3096. /**
  3097. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  3098. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  3099. * @param v1 (Vector3) the control point
  3100. * @param v2 (Vector3) the end point of the Quadratic Bezier
  3101. * @param nbPoints (integer) the wanted number of points in the curve
  3102. */
  3103. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  3104. nbPoints = nbPoints > 2 ? nbPoints : 3;
  3105. var bez = new Array();
  3106. var equation = function (t, val0, val1, val2) {
  3107. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  3108. return res;
  3109. };
  3110. for (var i = 0; i <= nbPoints; i++) {
  3111. 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)));
  3112. }
  3113. return new Curve3(bez);
  3114. };
  3115. /**
  3116. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  3117. * @param v0 (Vector3) the origin point of the Cubic Bezier
  3118. * @param v1 (Vector3) the first control point
  3119. * @param v2 (Vector3) the second control point
  3120. * @param v3 (Vector3) the end point of the Cubic Bezier
  3121. * @param nbPoints (integer) the wanted number of points in the curve
  3122. */
  3123. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  3124. nbPoints = nbPoints > 3 ? nbPoints : 4;
  3125. var bez = new Array();
  3126. var equation = function (t, val0, val1, val2, val3) {
  3127. var res = (1.0 - t) * (1.0 - t) * (1.0 - t) * val0 + 3.0 * t * (1.0 - t) * (1.0 - t) * val1 + 3.0 * t * t * (1.0 - t) * val2 + t * t * t * val3;
  3128. return res;
  3129. };
  3130. for (var i = 0; i <= nbPoints; i++) {
  3131. 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)));
  3132. }
  3133. return new Curve3(bez);
  3134. };
  3135. /**
  3136. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  3137. * @param p1 (Vector3) the origin point of the Hermite Spline
  3138. * @param t1 (Vector3) the tangent vector at the origin point
  3139. * @param p2 (Vector3) the end point of the Hermite Spline
  3140. * @param t2 (Vector3) the tangent vector at the end point
  3141. * @param nbPoints (integer) the wanted number of points in the curve
  3142. */
  3143. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  3144. var hermite = new Array();
  3145. var step = 1.0 / nbPoints;
  3146. for (var i = 0; i <= nbPoints; i++) {
  3147. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  3148. }
  3149. return new Curve3(hermite);
  3150. };
  3151. /**
  3152. * Returns the Curve3 stored array of successive Vector3
  3153. */
  3154. Curve3.prototype.getPoints = function () {
  3155. return this._points;
  3156. };
  3157. /**
  3158. * Returns the computed length (float) of the curve.
  3159. */
  3160. Curve3.prototype.length = function () {
  3161. return this._length;
  3162. };
  3163. /**
  3164. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  3165. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  3166. * curveA and curveB keep unchanged.
  3167. */
  3168. Curve3.prototype.continue = function (curve) {
  3169. var lastPoint = this._points[this._points.length - 1];
  3170. var continuedPoints = this._points.slice();
  3171. var curvePoints = curve.getPoints();
  3172. for (var i = 1; i < curvePoints.length; i++) {
  3173. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  3174. }
  3175. var continuedCurve = new Curve3(continuedPoints);
  3176. return continuedCurve;
  3177. };
  3178. Curve3.prototype._computeLength = function (path) {
  3179. var l = 0;
  3180. for (var i = 1; i < path.length; i++) {
  3181. l += (path[i].subtract(path[i - 1])).length();
  3182. }
  3183. return l;
  3184. };
  3185. return Curve3;
  3186. }());
  3187. BABYLON.Curve3 = Curve3;
  3188. // SphericalHarmonics
  3189. var SphericalHarmonics = (function () {
  3190. function SphericalHarmonics() {
  3191. this.L00 = Vector3.Zero();
  3192. this.L1_1 = Vector3.Zero();
  3193. this.L10 = Vector3.Zero();
  3194. this.L11 = Vector3.Zero();
  3195. this.L2_2 = Vector3.Zero();
  3196. this.L2_1 = Vector3.Zero();
  3197. this.L20 = Vector3.Zero();
  3198. this.L21 = Vector3.Zero();
  3199. this.L22 = Vector3.Zero();
  3200. }
  3201. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  3202. var colorVector = new Vector3(color.r, color.g, color.b);
  3203. var c = colorVector.scale(deltaSolidAngle);
  3204. this.L00 = this.L00.add(c.scale(0.282095));
  3205. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  3206. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  3207. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  3208. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  3209. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  3210. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  3211. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  3212. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  3213. };
  3214. SphericalHarmonics.prototype.scale = function (scale) {
  3215. this.L00 = this.L00.scale(scale);
  3216. this.L1_1 = this.L1_1.scale(scale);
  3217. this.L10 = this.L10.scale(scale);
  3218. this.L11 = this.L11.scale(scale);
  3219. this.L2_2 = this.L2_2.scale(scale);
  3220. this.L2_1 = this.L2_1.scale(scale);
  3221. this.L20 = this.L20.scale(scale);
  3222. this.L21 = this.L21.scale(scale);
  3223. this.L22 = this.L22.scale(scale);
  3224. };
  3225. return SphericalHarmonics;
  3226. }());
  3227. BABYLON.SphericalHarmonics = SphericalHarmonics;
  3228. // SphericalPolynomial
  3229. var SphericalPolynomial = (function () {
  3230. function SphericalPolynomial() {
  3231. this.x = Vector3.Zero();
  3232. this.y = Vector3.Zero();
  3233. this.z = Vector3.Zero();
  3234. this.xx = Vector3.Zero();
  3235. this.yy = Vector3.Zero();
  3236. this.zz = Vector3.Zero();
  3237. this.xy = Vector3.Zero();
  3238. this.yz = Vector3.Zero();
  3239. this.zx = Vector3.Zero();
  3240. }
  3241. SphericalPolynomial.prototype.addAmbient = function (color) {
  3242. var colorVector = new Vector3(color.r, color.g, color.b);
  3243. this.xx = this.xx.add(colorVector);
  3244. this.yy = this.yy.add(colorVector);
  3245. this.zz = this.zz.add(colorVector);
  3246. };
  3247. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  3248. var result = new SphericalPolynomial();
  3249. result.x = harmonics.L11.scale(1.02333);
  3250. result.y = harmonics.L1_1.scale(1.02333);
  3251. result.z = harmonics.L10.scale(1.02333);
  3252. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  3253. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  3254. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  3255. result.yz = harmonics.L2_1.scale(0.858086);
  3256. result.zx = harmonics.L21.scale(0.858086);
  3257. result.xy = harmonics.L2_2.scale(0.858086);
  3258. return result;
  3259. };
  3260. return SphericalPolynomial;
  3261. }());
  3262. BABYLON.SphericalPolynomial = SphericalPolynomial;
  3263. // Vertex formats
  3264. var PositionNormalVertex = (function () {
  3265. function PositionNormalVertex(position, normal) {
  3266. if (position === void 0) { position = Vector3.Zero(); }
  3267. if (normal === void 0) { normal = Vector3.Up(); }
  3268. this.position = position;
  3269. this.normal = normal;
  3270. }
  3271. PositionNormalVertex.prototype.clone = function () {
  3272. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  3273. };
  3274. return PositionNormalVertex;
  3275. }());
  3276. BABYLON.PositionNormalVertex = PositionNormalVertex;
  3277. var PositionNormalTextureVertex = (function () {
  3278. function PositionNormalTextureVertex(position, normal, uv) {
  3279. if (position === void 0) { position = Vector3.Zero(); }
  3280. if (normal === void 0) { normal = Vector3.Up(); }
  3281. if (uv === void 0) { uv = Vector2.Zero(); }
  3282. this.position = position;
  3283. this.normal = normal;
  3284. this.uv = uv;
  3285. }
  3286. PositionNormalTextureVertex.prototype.clone = function () {
  3287. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  3288. };
  3289. return PositionNormalTextureVertex;
  3290. }());
  3291. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  3292. // Temporary pre-allocated objects for engine internal use
  3293. // usage in any internal function :
  3294. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  3295. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  3296. var Tmp = (function () {
  3297. function Tmp() {
  3298. }
  3299. return Tmp;
  3300. }());
  3301. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  3302. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  3303. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  3304. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  3305. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  3306. Tmp.Quaternion = [new Quaternion(0, 0, 0, 0)]; // 1 temp Quaternion at once should be enough
  3307. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  3308. Matrix.Zero(), Matrix.Zero(),
  3309. Matrix.Zero(), Matrix.Zero(),
  3310. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  3311. BABYLON.Tmp = Tmp;
  3312. })(BABYLON || (BABYLON = {}));
  3313. //# sourceMappingURL=babylon.math.js.map
  3314. //# sourceMappingURL=babylon.mixins.js.map
  3315. var BABYLON;
  3316. (function (BABYLON) {
  3317. function generateSerializableMember(type, sourceName) {
  3318. return function (target, propertyKey) {
  3319. if (!target.__serializableMembers) {
  3320. target.__serializableMembers = {};
  3321. }
  3322. if (!target.__serializableMembers[propertyKey]) {
  3323. target.__serializableMembers[propertyKey] = { type: type, sourceName: sourceName };
  3324. }
  3325. };
  3326. }
  3327. function serialize(sourceName) {
  3328. return generateSerializableMember(0, sourceName); // value member
  3329. }
  3330. BABYLON.serialize = serialize;
  3331. function serializeAsTexture(sourceName) {
  3332. return generateSerializableMember(1, sourceName); // texture member
  3333. }
  3334. BABYLON.serializeAsTexture = serializeAsTexture;
  3335. function serializeAsColor3(sourceName) {
  3336. return generateSerializableMember(2, sourceName); // color3 member
  3337. }
  3338. BABYLON.serializeAsColor3 = serializeAsColor3;
  3339. function serializeAsFresnelParameters(sourceName) {
  3340. return generateSerializableMember(3, sourceName); // fresnel parameters member
  3341. }
  3342. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  3343. function serializeAsVector2(sourceName) {
  3344. return generateSerializableMember(4, sourceName); // vector2 member
  3345. }
  3346. BABYLON.serializeAsVector2 = serializeAsVector2;
  3347. function serializeAsVector3(sourceName) {
  3348. return generateSerializableMember(5, sourceName); // vector3 member
  3349. }
  3350. BABYLON.serializeAsVector3 = serializeAsVector3;
  3351. function serializeAsMeshReference(sourceName) {
  3352. return generateSerializableMember(6, sourceName); // mesh reference member
  3353. }
  3354. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  3355. function serializeAsColorCurves(sourceName) {
  3356. return generateSerializableMember(7, sourceName); // color curves
  3357. }
  3358. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  3359. var SerializationHelper = (function () {
  3360. function SerializationHelper() {
  3361. }
  3362. SerializationHelper.Serialize = function (entity, serializationObject) {
  3363. if (!serializationObject) {
  3364. serializationObject = {};
  3365. }
  3366. // Tags
  3367. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  3368. // Properties
  3369. for (var property in entity.__serializableMembers) {
  3370. var propertyDescriptor = entity.__serializableMembers[property];
  3371. var targetPropertyName = propertyDescriptor.sourceName || property;
  3372. var propertyType = propertyDescriptor.type;
  3373. var sourceProperty = entity[property];
  3374. if (sourceProperty !== undefined && sourceProperty !== null) {
  3375. switch (propertyType) {
  3376. case 0:
  3377. serializationObject[targetPropertyName] = sourceProperty;
  3378. break;
  3379. case 1:
  3380. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3381. break;
  3382. case 2:
  3383. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3384. break;
  3385. case 3:
  3386. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3387. break;
  3388. case 4:
  3389. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3390. break;
  3391. case 5:
  3392. serializationObject[targetPropertyName] = sourceProperty.asArray();
  3393. break;
  3394. case 6:
  3395. serializationObject[targetPropertyName] = sourceProperty.id;
  3396. break;
  3397. case 7:
  3398. serializationObject[targetPropertyName] = sourceProperty.serialize();
  3399. break;
  3400. }
  3401. }
  3402. }
  3403. return serializationObject;
  3404. };
  3405. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  3406. var destination = creationFunction();
  3407. // Tags
  3408. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3409. // Properties
  3410. for (var property in destination.__serializableMembers) {
  3411. var propertyDescriptor = destination.__serializableMembers[property];
  3412. var sourceProperty = source[propertyDescriptor.sourceName || property];
  3413. var propertyType = propertyDescriptor.type;
  3414. if (sourceProperty !== undefined && sourceProperty !== null) {
  3415. switch (propertyType) {
  3416. case 0:
  3417. destination[property] = sourceProperty;
  3418. break;
  3419. case 1:
  3420. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  3421. break;
  3422. case 2:
  3423. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  3424. break;
  3425. case 3:
  3426. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  3427. break;
  3428. case 4:
  3429. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  3430. break;
  3431. case 5:
  3432. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  3433. break;
  3434. case 6:
  3435. destination[property] = scene.getLastMeshByID(sourceProperty);
  3436. break;
  3437. case 7:
  3438. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  3439. break;
  3440. }
  3441. }
  3442. }
  3443. return destination;
  3444. };
  3445. SerializationHelper.Clone = function (creationFunction, source) {
  3446. var destination = creationFunction();
  3447. // Tags
  3448. BABYLON.Tags.AddTagsTo(destination, source.tags);
  3449. // Properties
  3450. for (var property in destination.__serializableMembers) {
  3451. var propertyDescriptor = destination.__serializableMembers[property];
  3452. var sourceProperty = source[property];
  3453. var propertyType = propertyDescriptor.type;
  3454. if (sourceProperty !== undefined && sourceProperty !== null) {
  3455. switch (propertyType) {
  3456. case 0: // Value
  3457. case 6:
  3458. destination[property] = sourceProperty;
  3459. break;
  3460. case 1: // Texture
  3461. case 2: // Color3
  3462. case 3: // FresnelParameters
  3463. case 4: // Vector2
  3464. case 5: // Vector3
  3465. case 7:
  3466. destination[property] = sourceProperty.clone();
  3467. break;
  3468. }
  3469. }
  3470. }
  3471. return destination;
  3472. };
  3473. return SerializationHelper;
  3474. }());
  3475. BABYLON.SerializationHelper = SerializationHelper;
  3476. })(BABYLON || (BABYLON = {}));
  3477. //# sourceMappingURL=babylon.decorators.js.map
  3478. var BABYLON;
  3479. (function (BABYLON) {
  3480. /**
  3481. * A class serves as a medium between the observable and its observers
  3482. */
  3483. var EventState = (function () {
  3484. /**
  3485. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  3486. */
  3487. function EventState(mask, skipNextObservers) {
  3488. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3489. this.initalize(mask, skipNextObservers);
  3490. }
  3491. EventState.prototype.initalize = function (mask, skipNextObservers) {
  3492. if (skipNextObservers === void 0) { skipNextObservers = false; }
  3493. this.mask = mask;
  3494. this.skipNextObservers = skipNextObservers;
  3495. return this;
  3496. };
  3497. return EventState;
  3498. }());
  3499. BABYLON.EventState = EventState;
  3500. /**
  3501. * Represent an Observer registered to a given Observable object.
  3502. */
  3503. var Observer = (function () {
  3504. function Observer(callback, mask) {
  3505. this.callback = callback;
  3506. this.mask = mask;
  3507. }
  3508. return Observer;
  3509. }());
  3510. BABYLON.Observer = Observer;
  3511. /**
  3512. * The Observable class is a simple implementation of the Observable pattern.
  3513. * There's one slight particularity though: a given Observable can notify its observer using a particular mask value, only the Observers registered with this mask value will be notified.
  3514. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  3515. * For instance you may have a given Observable that have four different types of notifications: Move (mask = 0x01), Stop (mask = 0x02), Turn Right (mask = 0X04), Turn Left (mask = 0X08).
  3516. * A given observer can register itself with only Move and Stop (mask = 0x03), then it will only be notified when one of these two occurs and will never be for Turn Left/Right.
  3517. */
  3518. var Observable = (function () {
  3519. function Observable() {
  3520. this._observers = new Array();
  3521. this._eventState = new EventState(0);
  3522. }
  3523. /**
  3524. * Create a new Observer with the specified callback
  3525. * @param callback the callback that will be executed for that Observer
  3526. * @param mask the mask used to filter observers
  3527. * @param insertFirst if true the callback will be inserted at the first position, hence executed before the others ones. If false (default behavior) the callback will be inserted at the last position, executed after all the others already present.
  3528. */
  3529. Observable.prototype.add = function (callback, mask, insertFirst) {
  3530. if (mask === void 0) { mask = -1; }
  3531. if (insertFirst === void 0) { insertFirst = false; }
  3532. if (!callback) {
  3533. return null;
  3534. }
  3535. var observer = new Observer(callback, mask);
  3536. if (insertFirst) {
  3537. this._observers.unshift(observer);
  3538. }
  3539. else {
  3540. this._observers.push(observer);
  3541. }
  3542. return observer;
  3543. };
  3544. /**
  3545. * Remove an Observer from the Observable object
  3546. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  3547. */
  3548. Observable.prototype.remove = function (observer) {
  3549. var index = this._observers.indexOf(observer);
  3550. if (index !== -1) {
  3551. this._observers.splice(index, 1);
  3552. return true;
  3553. }
  3554. return false;
  3555. };
  3556. /**
  3557. * Remove a callback from the Observable object
  3558. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  3559. */
  3560. Observable.prototype.removeCallback = function (callback) {
  3561. for (var index = 0; index < this._observers.length; index++) {
  3562. if (this._observers[index].callback === callback) {
  3563. this._observers.splice(index, 1);
  3564. return true;
  3565. }
  3566. }
  3567. return false;
  3568. };
  3569. /**
  3570. * Notify all Observers by calling their respective callback with the given data
  3571. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  3572. * @param eventData
  3573. * @param mask
  3574. */
  3575. Observable.prototype.notifyObservers = function (eventData, mask) {
  3576. if (mask === void 0) { mask = -1; }
  3577. var state = this._eventState;
  3578. state.mask = mask;
  3579. state.skipNextObservers = false;
  3580. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  3581. var obs = _a[_i];
  3582. if (obs.mask & mask) {
  3583. obs.callback(eventData, state);
  3584. }
  3585. if (state.skipNextObservers) {
  3586. return false;
  3587. }
  3588. }
  3589. return true;
  3590. };
  3591. /**
  3592. * return true is the Observable has at least one Observer registered
  3593. */
  3594. Observable.prototype.hasObservers = function () {
  3595. return this._observers.length > 0;
  3596. };
  3597. /**
  3598. * Clear the list of observers
  3599. */
  3600. Observable.prototype.clear = function () {
  3601. this._observers = new Array();
  3602. };
  3603. /**
  3604. * Clone the current observable
  3605. */
  3606. Observable.prototype.clone = function () {
  3607. var result = new Observable();
  3608. result._observers = this._observers.slice(0);
  3609. return result;
  3610. };
  3611. return Observable;
  3612. }());
  3613. BABYLON.Observable = Observable;
  3614. })(BABYLON || (BABYLON = {}));
  3615. //# sourceMappingURL=babylon.observable.js.map
  3616. var BABYLON;
  3617. (function (BABYLON) {
  3618. var Database = (function () {
  3619. function Database(urlToScene, callbackManifestChecked) {
  3620. // Handling various flavors of prefixed version of IndexedDB
  3621. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  3622. this.callbackManifestChecked = callbackManifestChecked;
  3623. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  3624. this.db = null;
  3625. this.enableSceneOffline = false;
  3626. this.enableTexturesOffline = false;
  3627. this.manifestVersionFound = 0;
  3628. this.mustUpdateRessources = false;
  3629. this.hasReachedQuota = false;
  3630. if (!Database.IDBStorageEnabled) {
  3631. this.callbackManifestChecked(true);
  3632. }
  3633. else {
  3634. this.checkManifestFile();
  3635. }
  3636. }
  3637. Database.prototype.checkManifestFile = function () {
  3638. var _this = this;
  3639. function noManifestFile() {
  3640. that.enableSceneOffline = false;
  3641. that.enableTexturesOffline = false;
  3642. that.callbackManifestChecked(false);
  3643. }
  3644. var that = this;
  3645. var timeStampUsed = false;
  3646. var manifestURL = this.currentSceneUrl + ".manifest";
  3647. var xhr = new XMLHttpRequest();
  3648. if (navigator.onLine) {
  3649. // Adding a timestamp to by-pass browsers' cache
  3650. timeStampUsed = true;
  3651. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  3652. }
  3653. xhr.open("GET", manifestURL, true);
  3654. xhr.addEventListener("load", function () {
  3655. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  3656. try {
  3657. var manifestFile = JSON.parse(xhr.response);
  3658. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  3659. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  3660. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  3661. _this.manifestVersionFound = manifestFile.version;
  3662. }
  3663. if (_this.callbackManifestChecked) {
  3664. _this.callbackManifestChecked(true);
  3665. }
  3666. }
  3667. catch (ex) {
  3668. noManifestFile();
  3669. }
  3670. }
  3671. else {
  3672. noManifestFile();
  3673. }
  3674. }, false);
  3675. xhr.addEventListener("error", function (event) {
  3676. if (timeStampUsed) {
  3677. timeStampUsed = false;
  3678. // Let's retry without the timeStamp
  3679. // It could fail when coupled with HTML5 Offline API
  3680. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  3681. xhr.open("GET", retryManifestURL, true);
  3682. xhr.send();
  3683. }
  3684. else {
  3685. noManifestFile();
  3686. }
  3687. }, false);
  3688. try {
  3689. xhr.send();
  3690. }
  3691. catch (ex) {
  3692. BABYLON.Tools.Error("Error on XHR send request.");
  3693. that.callbackManifestChecked(false);
  3694. }
  3695. };
  3696. Database.prototype.openAsync = function (successCallback, errorCallback) {
  3697. var _this = this;
  3698. function handleError() {
  3699. that.isSupported = false;
  3700. if (errorCallback)
  3701. errorCallback();
  3702. }
  3703. var that = this;
  3704. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  3705. // Your browser doesn't support IndexedDB
  3706. this.isSupported = false;
  3707. if (errorCallback)
  3708. errorCallback();
  3709. }
  3710. else {
  3711. // If the DB hasn't been opened or created yet
  3712. if (!this.db) {
  3713. this.hasReachedQuota = false;
  3714. this.isSupported = true;
  3715. var request = this.idbFactory.open("babylonjs", 1);
  3716. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  3717. request.onerror = function (event) {
  3718. handleError();
  3719. };
  3720. // executes when a version change transaction cannot complete due to other active transactions
  3721. request.onblocked = function (event) {
  3722. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  3723. handleError();
  3724. };
  3725. // DB has been opened successfully
  3726. request.onsuccess = function (event) {
  3727. _this.db = request.result;
  3728. successCallback();
  3729. };
  3730. // Initialization of the DB. Creating Scenes & Textures stores
  3731. request.onupgradeneeded = function (event) {
  3732. _this.db = (event.target).result;
  3733. try {
  3734. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  3735. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  3736. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  3737. }
  3738. catch (ex) {
  3739. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  3740. handleError();
  3741. }
  3742. };
  3743. }
  3744. else {
  3745. if (successCallback)
  3746. successCallback();
  3747. }
  3748. }
  3749. };
  3750. Database.prototype.loadImageFromDB = function (url, image) {
  3751. var _this = this;
  3752. var completeURL = Database.ReturnFullUrlLocation(url);
  3753. var saveAndLoadImage = function () {
  3754. if (!_this.hasReachedQuota && _this.db !== null) {
  3755. // the texture is not yet in the DB, let's try to save it
  3756. _this._saveImageIntoDBAsync(completeURL, image);
  3757. }
  3758. else {
  3759. image.src = url;
  3760. }
  3761. };
  3762. if (!this.mustUpdateRessources) {
  3763. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  3764. }
  3765. else {
  3766. saveAndLoadImage();
  3767. }
  3768. };
  3769. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  3770. if (this.isSupported && this.db !== null) {
  3771. var texture;
  3772. var transaction = this.db.transaction(["textures"]);
  3773. transaction.onabort = function (event) {
  3774. image.src = url;
  3775. };
  3776. transaction.oncomplete = function (event) {
  3777. var blobTextureURL;
  3778. if (texture) {
  3779. var URL = window.URL || window.webkitURL;
  3780. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  3781. image.onerror = function () {
  3782. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  3783. image.src = url;
  3784. };
  3785. image.src = blobTextureURL;
  3786. }
  3787. else {
  3788. notInDBCallback();
  3789. }
  3790. };
  3791. var getRequest = transaction.objectStore("textures").get(url);
  3792. getRequest.onsuccess = function (event) {
  3793. texture = (event.target).result;
  3794. };
  3795. getRequest.onerror = function (event) {
  3796. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  3797. image.src = url;
  3798. };
  3799. }
  3800. else {
  3801. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3802. image.src = url;
  3803. }
  3804. };
  3805. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  3806. var _this = this;
  3807. if (this.isSupported) {
  3808. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  3809. var generateBlobUrl = function () {
  3810. var blobTextureURL;
  3811. if (blob) {
  3812. var URL = window.URL || window.webkitURL;
  3813. try {
  3814. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  3815. }
  3816. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  3817. catch (ex) {
  3818. blobTextureURL = URL.createObjectURL(blob);
  3819. }
  3820. }
  3821. image.src = blobTextureURL;
  3822. };
  3823. if (Database.IsUASupportingBlobStorage) {
  3824. var xhr = new XMLHttpRequest(), blob;
  3825. xhr.open("GET", url, true);
  3826. xhr.responseType = "blob";
  3827. xhr.addEventListener("load", function () {
  3828. if (xhr.status === 200) {
  3829. // Blob as response (XHR2)
  3830. blob = xhr.response;
  3831. var transaction = _this.db.transaction(["textures"], "readwrite");
  3832. // the transaction could abort because of a QuotaExceededError error
  3833. transaction.onabort = function (event) {
  3834. try {
  3835. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  3836. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3837. _this.hasReachedQuota = true;
  3838. }
  3839. }
  3840. catch (ex) { }
  3841. generateBlobUrl();
  3842. };
  3843. transaction.oncomplete = function (event) {
  3844. generateBlobUrl();
  3845. };
  3846. var newTexture = { textureUrl: url, data: blob };
  3847. try {
  3848. // Put the blob into the dabase
  3849. var addRequest = transaction.objectStore("textures").put(newTexture);
  3850. addRequest.onsuccess = function (event) {
  3851. };
  3852. addRequest.onerror = function (event) {
  3853. generateBlobUrl();
  3854. };
  3855. }
  3856. catch (ex) {
  3857. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  3858. if (ex.code === 25) {
  3859. Database.IsUASupportingBlobStorage = false;
  3860. }
  3861. image.src = url;
  3862. }
  3863. }
  3864. else {
  3865. image.src = url;
  3866. }
  3867. }, false);
  3868. xhr.addEventListener("error", function (event) {
  3869. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  3870. image.src = url;
  3871. }, false);
  3872. xhr.send();
  3873. }
  3874. else {
  3875. image.src = url;
  3876. }
  3877. }
  3878. else {
  3879. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3880. image.src = url;
  3881. }
  3882. };
  3883. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  3884. var _this = this;
  3885. var updateVersion = function (event) {
  3886. // the version is not yet in the DB or we need to update it
  3887. _this._saveVersionIntoDBAsync(url, versionLoaded);
  3888. };
  3889. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  3890. };
  3891. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  3892. var _this = this;
  3893. if (this.isSupported) {
  3894. var version;
  3895. try {
  3896. var transaction = this.db.transaction(["versions"]);
  3897. transaction.oncomplete = function (event) {
  3898. if (version) {
  3899. // If the version in the JSON file is > than the version in DB
  3900. if (_this.manifestVersionFound > version.data) {
  3901. _this.mustUpdateRessources = true;
  3902. updateInDBCallback();
  3903. }
  3904. else {
  3905. callback(version.data);
  3906. }
  3907. }
  3908. else {
  3909. _this.mustUpdateRessources = true;
  3910. updateInDBCallback();
  3911. }
  3912. };
  3913. transaction.onabort = function (event) {
  3914. callback(-1);
  3915. };
  3916. var getRequest = transaction.objectStore("versions").get(url);
  3917. getRequest.onsuccess = function (event) {
  3918. version = (event.target).result;
  3919. };
  3920. getRequest.onerror = function (event) {
  3921. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  3922. callback(-1);
  3923. };
  3924. }
  3925. catch (ex) {
  3926. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  3927. callback(-1);
  3928. }
  3929. }
  3930. else {
  3931. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  3932. callback(-1);
  3933. }
  3934. };
  3935. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  3936. var _this = this;
  3937. if (this.isSupported && !this.hasReachedQuota) {
  3938. try {
  3939. // Open a transaction to the database
  3940. var transaction = this.db.transaction(["versions"], "readwrite");
  3941. // the transaction could abort because of a QuotaExceededError error
  3942. transaction.onabort = function (event) {
  3943. try {
  3944. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  3945. _this.hasReachedQuota = true;
  3946. }
  3947. }
  3948. catch (ex) { }
  3949. callback(-1);
  3950. };
  3951. transaction.oncomplete = function (event) {
  3952. callback(_this.manifestVersionFound);
  3953. };
  3954. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  3955. // Put the scene into the database
  3956. var addRequest = transaction.objectStore("versions").put(newVersion);
  3957. addRequest.onsuccess = function (event) {
  3958. };
  3959. addRequest.onerror = function (event) {
  3960. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  3961. };
  3962. }
  3963. catch (ex) {
  3964. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  3965. callback(-1);
  3966. }
  3967. }
  3968. else {
  3969. callback(-1);
  3970. }
  3971. };
  3972. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  3973. var _this = this;
  3974. var completeUrl = Database.ReturnFullUrlLocation(url);
  3975. var saveAndLoadFile = function (event) {
  3976. // the scene is not yet in the DB, let's try to save it
  3977. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  3978. };
  3979. this._checkVersionFromDB(completeUrl, function (version) {
  3980. if (version !== -1) {
  3981. if (!_this.mustUpdateRessources) {
  3982. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  3983. }
  3984. else {
  3985. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  3986. }
  3987. }
  3988. else {
  3989. errorCallback();
  3990. }
  3991. });
  3992. };
  3993. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  3994. if (this.isSupported) {
  3995. var targetStore;
  3996. if (url.indexOf(".babylon") !== -1) {
  3997. targetStore = "scenes";
  3998. }
  3999. else {
  4000. targetStore = "textures";
  4001. }
  4002. var file;
  4003. var transaction = this.db.transaction([targetStore]);
  4004. transaction.oncomplete = function (event) {
  4005. if (file) {
  4006. callback(file.data);
  4007. }
  4008. else {
  4009. notInDBCallback();
  4010. }
  4011. };
  4012. transaction.onabort = function (event) {
  4013. notInDBCallback();
  4014. };
  4015. var getRequest = transaction.objectStore(targetStore).get(url);
  4016. getRequest.onsuccess = function (event) {
  4017. file = (event.target).result;
  4018. };
  4019. getRequest.onerror = function (event) {
  4020. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  4021. notInDBCallback();
  4022. };
  4023. }
  4024. else {
  4025. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4026. callback();
  4027. }
  4028. };
  4029. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  4030. var _this = this;
  4031. if (this.isSupported) {
  4032. var targetStore;
  4033. if (url.indexOf(".babylon") !== -1) {
  4034. targetStore = "scenes";
  4035. }
  4036. else {
  4037. targetStore = "textures";
  4038. }
  4039. // Create XHR
  4040. var xhr = new XMLHttpRequest(), fileData;
  4041. xhr.open("GET", url, true);
  4042. if (useArrayBuffer) {
  4043. xhr.responseType = "arraybuffer";
  4044. }
  4045. xhr.onprogress = progressCallback;
  4046. xhr.addEventListener("load", function () {
  4047. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  4048. // Blob as response (XHR2)
  4049. //fileData = xhr.responseText;
  4050. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  4051. if (!_this.hasReachedQuota) {
  4052. // Open a transaction to the database
  4053. var transaction = _this.db.transaction([targetStore], "readwrite");
  4054. // the transaction could abort because of a QuotaExceededError error
  4055. transaction.onabort = function (event) {
  4056. try {
  4057. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  4058. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  4059. _this.hasReachedQuota = true;
  4060. }
  4061. }
  4062. catch (ex) { }
  4063. callback(fileData);
  4064. };
  4065. transaction.oncomplete = function (event) {
  4066. callback(fileData);
  4067. };
  4068. var newFile;
  4069. if (targetStore === "scenes") {
  4070. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  4071. }
  4072. else {
  4073. newFile = { textureUrl: url, data: fileData };
  4074. }
  4075. try {
  4076. // Put the scene into the database
  4077. var addRequest = transaction.objectStore(targetStore).put(newFile);
  4078. addRequest.onsuccess = function (event) {
  4079. };
  4080. addRequest.onerror = function (event) {
  4081. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  4082. };
  4083. }
  4084. catch (ex) {
  4085. callback(fileData);
  4086. }
  4087. }
  4088. else {
  4089. callback(fileData);
  4090. }
  4091. }
  4092. else {
  4093. callback();
  4094. }
  4095. }, false);
  4096. xhr.addEventListener("error", function (event) {
  4097. BABYLON.Tools.Error("error on XHR request.");
  4098. callback();
  4099. }, false);
  4100. xhr.send();
  4101. }
  4102. else {
  4103. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  4104. callback();
  4105. }
  4106. };
  4107. return Database;
  4108. }());
  4109. Database.IsUASupportingBlobStorage = true;
  4110. Database.IDBStorageEnabled = true;
  4111. Database.parseURL = function (url) {
  4112. var a = document.createElement('a');
  4113. a.href = url;
  4114. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  4115. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  4116. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  4117. return absLocation;
  4118. };
  4119. Database.ReturnFullUrlLocation = function (url) {
  4120. if (url.indexOf("http:/") === -1) {
  4121. return (Database.parseURL(window.location.href) + url);
  4122. }
  4123. else {
  4124. return url;
  4125. }
  4126. };
  4127. BABYLON.Database = Database;
  4128. })(BABYLON || (BABYLON = {}));
  4129. //# sourceMappingURL=babylon.database.js.map
  4130. var BABYLON;
  4131. (function (BABYLON) {
  4132. var Internals;
  4133. (function (Internals) {
  4134. /*
  4135. * Based on jsTGALoader - Javascript loader for TGA file
  4136. * By Vincent Thibault
  4137. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  4138. */
  4139. var TGATools = (function () {
  4140. function TGATools() {
  4141. }
  4142. TGATools.GetTGAHeader = function (data) {
  4143. var offset = 0;
  4144. var header = {
  4145. id_length: data[offset++],
  4146. colormap_type: data[offset++],
  4147. image_type: data[offset++],
  4148. colormap_index: data[offset++] | data[offset++] << 8,
  4149. colormap_length: data[offset++] | data[offset++] << 8,
  4150. colormap_size: data[offset++],
  4151. origin: [
  4152. data[offset++] | data[offset++] << 8,
  4153. data[offset++] | data[offset++] << 8
  4154. ],
  4155. width: data[offset++] | data[offset++] << 8,
  4156. height: data[offset++] | data[offset++] << 8,
  4157. pixel_size: data[offset++],
  4158. flags: data[offset++]
  4159. };
  4160. return header;
  4161. };
  4162. TGATools.UploadContent = function (gl, data) {
  4163. // Not enough data to contain header ?
  4164. if (data.length < 19) {
  4165. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  4166. return;
  4167. }
  4168. // Read Header
  4169. var offset = 18;
  4170. var header = TGATools.GetTGAHeader(data);
  4171. // Assume it's a valid Targa file.
  4172. if (header.id_length + offset > data.length) {
  4173. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  4174. return;
  4175. }
  4176. // Skip not needed data
  4177. offset += header.id_length;
  4178. var use_rle = false;
  4179. var use_pal = false;
  4180. var use_rgb = false;
  4181. var use_grey = false;
  4182. // Get some informations.
  4183. switch (header.image_type) {
  4184. case TGATools._TYPE_RLE_INDEXED:
  4185. use_rle = true;
  4186. case TGATools._TYPE_INDEXED:
  4187. use_pal = true;
  4188. break;
  4189. case TGATools._TYPE_RLE_RGB:
  4190. use_rle = true;
  4191. case TGATools._TYPE_RGB:
  4192. use_rgb = true;
  4193. break;
  4194. case TGATools._TYPE_RLE_GREY:
  4195. use_rle = true;
  4196. case TGATools._TYPE_GREY:
  4197. use_grey = true;
  4198. break;
  4199. }
  4200. var pixel_data;
  4201. var numAlphaBits = header.flags & 0xf;
  4202. var pixel_size = header.pixel_size >> 3;
  4203. var pixel_total = header.width * header.height * pixel_size;
  4204. // Read palettes
  4205. var palettes;
  4206. if (use_pal) {
  4207. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  4208. }
  4209. // Read LRE
  4210. if (use_rle) {
  4211. pixel_data = new Uint8Array(pixel_total);
  4212. var c, count, i;
  4213. var localOffset = 0;
  4214. var pixels = new Uint8Array(pixel_size);
  4215. while (offset < pixel_total && localOffset < pixel_total) {
  4216. c = data[offset++];
  4217. count = (c & 0x7f) + 1;
  4218. // RLE pixels
  4219. if (c & 0x80) {
  4220. // Bind pixel tmp array
  4221. for (i = 0; i < pixel_size; ++i) {
  4222. pixels[i] = data[offset++];
  4223. }
  4224. // Copy pixel array
  4225. for (i = 0; i < count; ++i) {
  4226. pixel_data.set(pixels, localOffset + i * pixel_size);
  4227. }
  4228. localOffset += pixel_size * count;
  4229. }
  4230. else {
  4231. count *= pixel_size;
  4232. for (i = 0; i < count; ++i) {
  4233. pixel_data[localOffset + i] = data[offset++];
  4234. }
  4235. localOffset += count;
  4236. }
  4237. }
  4238. }
  4239. else {
  4240. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  4241. }
  4242. // Load to texture
  4243. var x_start, y_start, x_step, y_step, y_end, x_end;
  4244. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  4245. default:
  4246. case TGATools._ORIGIN_UL:
  4247. x_start = 0;
  4248. x_step = 1;
  4249. x_end = header.width;
  4250. y_start = 0;
  4251. y_step = 1;
  4252. y_end = header.height;
  4253. break;
  4254. case TGATools._ORIGIN_BL:
  4255. x_start = 0;
  4256. x_step = 1;
  4257. x_end = header.width;
  4258. y_start = header.height - 1;
  4259. y_step = -1;
  4260. y_end = -1;
  4261. break;
  4262. case TGATools._ORIGIN_UR:
  4263. x_start = header.width - 1;
  4264. x_step = -1;
  4265. x_end = -1;
  4266. y_start = 0;
  4267. y_step = 1;
  4268. y_end = header.height;
  4269. break;
  4270. case TGATools._ORIGIN_BR:
  4271. x_start = header.width - 1;
  4272. x_step = -1;
  4273. x_end = -1;
  4274. y_start = header.height - 1;
  4275. y_step = -1;
  4276. y_end = -1;
  4277. break;
  4278. }
  4279. // Load the specify method
  4280. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  4281. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  4282. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  4283. };
  4284. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4285. var image = pixel_data, colormap = palettes;
  4286. var width = header.width, height = header.height;
  4287. var color, i = 0, x, y;
  4288. var imageData = new Uint8Array(width * height * 4);
  4289. for (y = y_start; y !== y_end; y += y_step) {
  4290. for (x = x_start; x !== x_end; x += x_step, i++) {
  4291. color = image[i];
  4292. imageData[(x + width * y) * 4 + 3] = 255;
  4293. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  4294. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  4295. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  4296. }
  4297. }
  4298. return imageData;
  4299. };
  4300. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4301. var image = pixel_data;
  4302. var width = header.width, height = header.height;
  4303. var color, i = 0, x, y;
  4304. var imageData = new Uint8Array(width * height * 4);
  4305. for (y = y_start; y !== y_end; y += y_step) {
  4306. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4307. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  4308. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  4309. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  4310. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  4311. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  4312. }
  4313. }
  4314. return imageData;
  4315. };
  4316. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4317. var image = pixel_data;
  4318. var width = header.width, height = header.height;
  4319. var i = 0, x, y;
  4320. var imageData = new Uint8Array(width * height * 4);
  4321. for (y = y_start; y !== y_end; y += y_step) {
  4322. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  4323. imageData[(x + width * y) * 4 + 3] = 255;
  4324. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4325. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4326. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4327. }
  4328. }
  4329. return imageData;
  4330. };
  4331. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4332. var image = pixel_data;
  4333. var width = header.width, height = header.height;
  4334. var i = 0, x, y;
  4335. var imageData = new Uint8Array(width * height * 4);
  4336. for (y = y_start; y !== y_end; y += y_step) {
  4337. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  4338. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4339. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  4340. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  4341. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  4342. }
  4343. }
  4344. return imageData;
  4345. };
  4346. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4347. var image = pixel_data;
  4348. var width = header.width, height = header.height;
  4349. var color, i = 0, x, y;
  4350. var imageData = new Uint8Array(width * height * 4);
  4351. for (y = y_start; y !== y_end; y += y_step) {
  4352. for (x = x_start; x !== x_end; x += x_step, i++) {
  4353. color = image[i];
  4354. imageData[(x + width * y) * 4 + 0] = color;
  4355. imageData[(x + width * y) * 4 + 1] = color;
  4356. imageData[(x + width * y) * 4 + 2] = color;
  4357. imageData[(x + width * y) * 4 + 3] = 255;
  4358. }
  4359. }
  4360. return imageData;
  4361. };
  4362. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  4363. var image = pixel_data;
  4364. var width = header.width, height = header.height;
  4365. var i = 0, x, y;
  4366. var imageData = new Uint8Array(width * height * 4);
  4367. for (y = y_start; y !== y_end; y += y_step) {
  4368. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  4369. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  4370. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  4371. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  4372. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  4373. }
  4374. }
  4375. return imageData;
  4376. };
  4377. return TGATools;
  4378. }());
  4379. TGATools._TYPE_NO_DATA = 0;
  4380. TGATools._TYPE_INDEXED = 1;
  4381. TGATools._TYPE_RGB = 2;
  4382. TGATools._TYPE_GREY = 3;
  4383. TGATools._TYPE_RLE_INDEXED = 9;
  4384. TGATools._TYPE_RLE_RGB = 10;
  4385. TGATools._TYPE_RLE_GREY = 11;
  4386. TGATools._ORIGIN_MASK = 0x30;
  4387. TGATools._ORIGIN_SHIFT = 0x04;
  4388. TGATools._ORIGIN_BL = 0x00;
  4389. TGATools._ORIGIN_BR = 0x01;
  4390. TGATools._ORIGIN_UL = 0x02;
  4391. TGATools._ORIGIN_UR = 0x03;
  4392. Internals.TGATools = TGATools;
  4393. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  4394. })(BABYLON || (BABYLON = {}));
  4395. //# sourceMappingURL=babylon.tools.tga.js.map
  4396. var BABYLON;
  4397. (function (BABYLON) {
  4398. var SmartArray = (function () {
  4399. function SmartArray(capacity) {
  4400. this.length = 0;
  4401. this._duplicateId = 0;
  4402. this.data = new Array(capacity);
  4403. this._id = SmartArray._GlobalId++;
  4404. }
  4405. SmartArray.prototype.push = function (value) {
  4406. this.data[this.length++] = value;
  4407. if (this.length > this.data.length) {
  4408. this.data.length *= 2;
  4409. }
  4410. if (!value.__smartArrayFlags) {
  4411. value.__smartArrayFlags = {};
  4412. }
  4413. value.__smartArrayFlags[this._id] = this._duplicateId;
  4414. };
  4415. SmartArray.prototype.pushNoDuplicate = function (value) {
  4416. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  4417. return false;
  4418. }
  4419. this.push(value);
  4420. return true;
  4421. };
  4422. SmartArray.prototype.sort = function (compareFn) {
  4423. this.data.sort(compareFn);
  4424. };
  4425. SmartArray.prototype.reset = function () {
  4426. this.length = 0;
  4427. this._duplicateId++;
  4428. };
  4429. SmartArray.prototype.concat = function (array) {
  4430. if (array.length === 0) {
  4431. return;
  4432. }
  4433. if (this.length + array.length > this.data.length) {
  4434. this.data.length = (this.length + array.length) * 2;
  4435. }
  4436. for (var index = 0; index < array.length; index++) {
  4437. this.data[this.length++] = (array.data || array)[index];
  4438. }
  4439. };
  4440. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  4441. if (array.length === 0) {
  4442. return;
  4443. }
  4444. if (this.length + array.length > this.data.length) {
  4445. this.data.length = (this.length + array.length) * 2;
  4446. }
  4447. for (var index = 0; index < array.length; index++) {
  4448. var item = (array.data || array)[index];
  4449. this.pushNoDuplicate(item);
  4450. }
  4451. };
  4452. SmartArray.prototype.indexOf = function (value) {
  4453. var position = this.data.indexOf(value);
  4454. if (position >= this.length) {
  4455. return -1;
  4456. }
  4457. return position;
  4458. };
  4459. return SmartArray;
  4460. }());
  4461. // Statics
  4462. SmartArray._GlobalId = 0;
  4463. BABYLON.SmartArray = SmartArray;
  4464. })(BABYLON || (BABYLON = {}));
  4465. //# sourceMappingURL=babylon.smartArray.js.map
  4466. var BABYLON;
  4467. (function (BABYLON) {
  4468. /**
  4469. * This class implement a typical dictionary using a string as key and the generic type T as value.
  4470. * The underlying implementation relies on an associative array to ensure the best performances.
  4471. * The value can be anything including 'null' but except 'undefined'
  4472. */
  4473. var StringDictionary = (function () {
  4474. function StringDictionary() {
  4475. this._count = 0;
  4476. this._data = {};
  4477. }
  4478. /**
  4479. * This will clear this dictionary and copy the content from the 'source' one.
  4480. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  4481. * @param source the dictionary to take the content from and copy to this dictionary
  4482. */
  4483. StringDictionary.prototype.copyFrom = function (source) {
  4484. var _this = this;
  4485. this.clear();
  4486. source.forEach(function (t, v) { return _this.add(t, v); });
  4487. };
  4488. /**
  4489. * Get a value based from its key
  4490. * @param key the given key to get the matching value from
  4491. * @return the value if found, otherwise undefined is returned
  4492. */
  4493. StringDictionary.prototype.get = function (key) {
  4494. var val = this._data[key];
  4495. if (val !== undefined) {
  4496. return val;
  4497. }
  4498. return undefined;
  4499. };
  4500. /**
  4501. * Get a value from its key or add it if it doesn't exist.
  4502. * This method will ensure you that a given key/data will be present in the dictionary.
  4503. * @param key the given key to get the matching value from
  4504. * @param factory the factory that will create the value if the key is not present in the dictionary.
  4505. * The factory will only be invoked if there's no data for the given key.
  4506. * @return the value corresponding to the key.
  4507. */
  4508. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  4509. var val = this.get(key);
  4510. if (val !== undefined) {
  4511. return val;
  4512. }
  4513. val = factory(key);
  4514. if (val) {
  4515. this.add(key, val);
  4516. }
  4517. return val;
  4518. };
  4519. /**
  4520. * Get a value from its key if present in the dictionary otherwise add it
  4521. * @param key the key to get the value from
  4522. * @param val if there's no such key/value pair in the dictionary add it with this value
  4523. * @return the value corresponding to the key
  4524. */
  4525. StringDictionary.prototype.getOrAdd = function (key, val) {
  4526. var curVal = this.get(key);
  4527. if (curVal !== undefined) {
  4528. return curVal;
  4529. }
  4530. this.add(key, val);
  4531. return val;
  4532. };
  4533. /**
  4534. * Check if there's a given key in the dictionary
  4535. * @param key the key to check for
  4536. * @return true if the key is present, false otherwise
  4537. */
  4538. StringDictionary.prototype.contains = function (key) {
  4539. return this._data[key] !== undefined;
  4540. };
  4541. /**
  4542. * Add a new key and its corresponding value
  4543. * @param key the key to add
  4544. * @param value the value corresponding to the key
  4545. * @return true if the operation completed successfully, false if we couldn't insert the key/value because there was already this key in the dictionary
  4546. */
  4547. StringDictionary.prototype.add = function (key, value) {
  4548. if (this._data[key] !== undefined) {
  4549. return false;
  4550. }
  4551. this._data[key] = value;
  4552. ++this._count;
  4553. return true;
  4554. };
  4555. StringDictionary.prototype.set = function (key, value) {
  4556. if (this._data[key] === undefined) {
  4557. return false;
  4558. }
  4559. this._data[key] = value;
  4560. return true;
  4561. };
  4562. /**
  4563. * Get the element of the given key and remove it from the dictionary
  4564. * @param key
  4565. */
  4566. StringDictionary.prototype.getAndRemove = function (key) {
  4567. var val = this.get(key);
  4568. if (val !== undefined) {
  4569. delete this._data[key];
  4570. --this._count;
  4571. return val;
  4572. }
  4573. return null;
  4574. };
  4575. /**
  4576. * Remove a key/value from the dictionary.
  4577. * @param key the key to remove
  4578. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  4579. */
  4580. StringDictionary.prototype.remove = function (key) {
  4581. if (this.contains(key)) {
  4582. delete this._data[key];
  4583. --this._count;
  4584. return true;
  4585. }
  4586. return false;
  4587. };
  4588. /**
  4589. * Clear the whole content of the dictionary
  4590. */
  4591. StringDictionary.prototype.clear = function () {
  4592. this._data = {};
  4593. this._count = 0;
  4594. };
  4595. Object.defineProperty(StringDictionary.prototype, "count", {
  4596. get: function () {
  4597. return this._count;
  4598. },
  4599. enumerable: true,
  4600. configurable: true
  4601. });
  4602. /**
  4603. * Execute a callback on each key/val of the dictionary.
  4604. * Note that you can remove any element in this dictionary in the callback implementation
  4605. * @param callback the callback to execute on a given key/value pair
  4606. */
  4607. StringDictionary.prototype.forEach = function (callback) {
  4608. for (var cur in this._data) {
  4609. var val = this._data[cur];
  4610. callback(cur, val);
  4611. }
  4612. };
  4613. /**
  4614. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  4615. * If the callback returns null or undefined the method will iterate to the next key/value pair
  4616. * Note that you can remove any element in this dictionary in the callback implementation
  4617. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  4618. */
  4619. StringDictionary.prototype.first = function (callback) {
  4620. for (var cur in this._data) {
  4621. var val = this._data[cur];
  4622. var res = callback(cur, val);
  4623. if (res) {
  4624. return res;
  4625. }
  4626. }
  4627. return null;
  4628. };
  4629. return StringDictionary;
  4630. }());
  4631. BABYLON.StringDictionary = StringDictionary;
  4632. })(BABYLON || (BABYLON = {}));
  4633. //# sourceMappingURL=babylon.stringDictionary.js.map
  4634. var BABYLON;
  4635. (function (BABYLON) {
  4636. // Screenshots
  4637. var screenshotCanvas;
  4638. var cloneValue = function (source, destinationObject) {
  4639. if (!source)
  4640. return null;
  4641. if (source instanceof BABYLON.Mesh) {
  4642. return null;
  4643. }
  4644. if (source instanceof BABYLON.SubMesh) {
  4645. return source.clone(destinationObject);
  4646. }
  4647. else if (source.clone) {
  4648. return source.clone();
  4649. }
  4650. return null;
  4651. };
  4652. var Tools = (function () {
  4653. function Tools() {
  4654. }
  4655. Tools.Instantiate = function (className) {
  4656. var arr = className.split(".");
  4657. var fn = (window || this);
  4658. for (var i = 0, len = arr.length; i < len; i++) {
  4659. fn = fn[arr[i]];
  4660. }
  4661. if (typeof fn !== "function") {
  4662. return null;
  4663. }
  4664. return fn;
  4665. };
  4666. Tools.SetImmediate = function (action) {
  4667. if (window.setImmediate) {
  4668. window.setImmediate(action);
  4669. }
  4670. else {
  4671. setTimeout(action, 1);
  4672. }
  4673. };
  4674. Tools.IsExponentOfTwo = function (value) {
  4675. var count = 1;
  4676. do {
  4677. count *= 2;
  4678. } while (count < value);
  4679. return count === value;
  4680. };
  4681. Tools.GetExponentOfTwo = function (value, max) {
  4682. var count = 1;
  4683. do {
  4684. count *= 2;
  4685. } while (count < value);
  4686. if (count > max)
  4687. count = max;
  4688. return count;
  4689. };
  4690. Tools.GetFilename = function (path) {
  4691. var index = path.lastIndexOf("/");
  4692. if (index < 0)
  4693. return path;
  4694. return path.substring(index + 1);
  4695. };
  4696. Tools.GetDOMTextContent = function (element) {
  4697. var result = "";
  4698. var child = element.firstChild;
  4699. while (child) {
  4700. if (child.nodeType === 3) {
  4701. result += child.textContent;
  4702. }
  4703. child = child.nextSibling;
  4704. }
  4705. return result;
  4706. };
  4707. Tools.ToDegrees = function (angle) {
  4708. return angle * 180 / Math.PI;
  4709. };
  4710. Tools.ToRadians = function (angle) {
  4711. return angle * Math.PI / 180;
  4712. };
  4713. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  4714. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  4715. var output = "";
  4716. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  4717. var i = 0;
  4718. var bytes = new Uint8Array(buffer);
  4719. while (i < bytes.length) {
  4720. chr1 = bytes[i++];
  4721. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  4722. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  4723. enc1 = chr1 >> 2;
  4724. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  4725. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  4726. enc4 = chr3 & 63;
  4727. if (isNaN(chr2)) {
  4728. enc3 = enc4 = 64;
  4729. }
  4730. else if (isNaN(chr3)) {
  4731. enc4 = 64;
  4732. }
  4733. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  4734. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  4735. }
  4736. return "data:image/png;base64," + output;
  4737. };
  4738. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  4739. if (bias === void 0) { bias = null; }
  4740. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4741. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4742. for (var index = indexStart; index < indexStart + indexCount; index++) {
  4743. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  4744. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4745. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4746. }
  4747. if (bias) {
  4748. minimum.x -= minimum.x * bias.x + bias.y;
  4749. minimum.y -= minimum.y * bias.x + bias.y;
  4750. minimum.z -= minimum.z * bias.x + bias.y;
  4751. maximum.x += maximum.x * bias.x + bias.y;
  4752. maximum.y += maximum.y * bias.x + bias.y;
  4753. maximum.z += maximum.z * bias.x + bias.y;
  4754. }
  4755. return {
  4756. minimum: minimum,
  4757. maximum: maximum
  4758. };
  4759. };
  4760. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  4761. if (bias === void 0) { bias = null; }
  4762. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  4763. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  4764. if (!stride) {
  4765. stride = 3;
  4766. }
  4767. for (var index = start; index < start + count; index++) {
  4768. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  4769. minimum = BABYLON.Vector3.Minimize(current, minimum);
  4770. maximum = BABYLON.Vector3.Maximize(current, maximum);
  4771. }
  4772. if (bias) {
  4773. minimum.x -= minimum.x * bias.x + bias.y;
  4774. minimum.y -= minimum.y * bias.x + bias.y;
  4775. minimum.z -= minimum.z * bias.x + bias.y;
  4776. maximum.x += maximum.x * bias.x + bias.y;
  4777. maximum.y += maximum.y * bias.x + bias.y;
  4778. maximum.z += maximum.z * bias.x + bias.y;
  4779. }
  4780. return {
  4781. minimum: minimum,
  4782. maximum: maximum
  4783. };
  4784. };
  4785. Tools.Vector2ArrayFeeder = function (array) {
  4786. return function (index) {
  4787. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  4788. var length = isFloatArray ? array.length / 2 : array.length;
  4789. if (index >= length) {
  4790. return null;
  4791. }
  4792. if (isFloatArray) {
  4793. var fa = array;
  4794. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  4795. }
  4796. var a = array;
  4797. return a[index];
  4798. };
  4799. };
  4800. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  4801. if (bias === void 0) { bias = null; }
  4802. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  4803. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  4804. var i = 0;
  4805. var cur = feeder(i++);
  4806. while (cur) {
  4807. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  4808. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  4809. cur = feeder(i++);
  4810. }
  4811. if (bias) {
  4812. minimum.x -= minimum.x * bias.x + bias.y;
  4813. minimum.y -= minimum.y * bias.x + bias.y;
  4814. maximum.x += maximum.x * bias.x + bias.y;
  4815. maximum.y += maximum.y * bias.x + bias.y;
  4816. }
  4817. return {
  4818. minimum: minimum,
  4819. maximum: maximum
  4820. };
  4821. };
  4822. Tools.MakeArray = function (obj, allowsNullUndefined) {
  4823. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  4824. return undefined;
  4825. return Array.isArray(obj) ? obj : [obj];
  4826. };
  4827. // Misc.
  4828. Tools.GetPointerPrefix = function () {
  4829. var eventPrefix = "pointer";
  4830. // Check if pointer events are supported
  4831. if (!window.PointerEvent && !navigator.pointerEnabled) {
  4832. eventPrefix = "mouse";
  4833. }
  4834. return eventPrefix;
  4835. };
  4836. /**
  4837. * @param func - the function to be called
  4838. * @param requester - the object that will request the next frame. Falls back to window.
  4839. */
  4840. Tools.QueueNewFrame = function (func, requester) {
  4841. if (requester === void 0) { requester = window; }
  4842. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  4843. /*if(requester.isPresenting) {
  4844. return;
  4845. } else*/ if (requester.requestAnimationFrame)
  4846. requester.requestAnimationFrame(func);
  4847. else if (requester.msRequestAnimationFrame)
  4848. requester.msRequestAnimationFrame(func);
  4849. else if (requester.webkitRequestAnimationFrame)
  4850. requester.webkitRequestAnimationFrame(func);
  4851. else if (requester.mozRequestAnimationFrame)
  4852. requester.mozRequestAnimationFrame(func);
  4853. else if (requester.oRequestAnimationFrame)
  4854. requester.oRequestAnimationFrame(func);
  4855. else {
  4856. window.setTimeout(func, 16);
  4857. }
  4858. };
  4859. Tools.RequestFullscreen = function (element) {
  4860. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  4861. if (!requestFunction)
  4862. return;
  4863. requestFunction.call(element);
  4864. };
  4865. Tools.ExitFullscreen = function () {
  4866. if (document.exitFullscreen) {
  4867. document.exitFullscreen();
  4868. }
  4869. else if (document.mozCancelFullScreen) {
  4870. document.mozCancelFullScreen();
  4871. }
  4872. else if (document.webkitCancelFullScreen) {
  4873. document.webkitCancelFullScreen();
  4874. }
  4875. else if (document.msCancelFullScreen) {
  4876. document.msCancelFullScreen();
  4877. }
  4878. };
  4879. Tools.SetCorsBehavior = function (url, img) {
  4880. if (Tools.CorsBehavior) {
  4881. switch (typeof (Tools.CorsBehavior)) {
  4882. case "function":
  4883. var result = Tools.CorsBehavior(url);
  4884. if (result) {
  4885. return result;
  4886. }
  4887. break;
  4888. case "string":
  4889. default:
  4890. img.crossOrigin = Tools.CorsBehavior;
  4891. break;
  4892. }
  4893. }
  4894. };
  4895. // External files
  4896. Tools.CleanUrl = function (url) {
  4897. url = url.replace(/#/mg, "%23");
  4898. return url;
  4899. };
  4900. Tools.LoadImage = function (url, onload, onerror, database) {
  4901. if (url instanceof ArrayBuffer) {
  4902. url = Tools.EncodeArrayBufferTobase64(url);
  4903. }
  4904. url = Tools.CleanUrl(url);
  4905. var img = new Image();
  4906. if (url.substr(0, 5) !== "data:") {
  4907. Tools.SetCorsBehavior(url, img);
  4908. }
  4909. img.onload = function () {
  4910. onload(img);
  4911. };
  4912. img.onerror = function (err) {
  4913. Tools.Error("Error while trying to load texture: " + url);
  4914. if (Tools.UseFallbackTexture) {
  4915. 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";
  4916. onload(img);
  4917. }
  4918. else {
  4919. onerror();
  4920. }
  4921. };
  4922. var noIndexedDB = function () {
  4923. img.src = url;
  4924. };
  4925. var loadFromIndexedDB = function () {
  4926. database.loadImageFromDB(url, img);
  4927. };
  4928. //ANY database to do!
  4929. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  4930. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4931. }
  4932. else {
  4933. if (url.indexOf("file:") === -1) {
  4934. noIndexedDB();
  4935. }
  4936. else {
  4937. try {
  4938. var textureName = url.substring(5).toLowerCase();
  4939. var blobURL;
  4940. try {
  4941. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName], { oneTimeOnly: true });
  4942. }
  4943. catch (ex) {
  4944. // Chrome doesn't support oneTimeOnly parameter
  4945. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesTextures[textureName]);
  4946. }
  4947. img.src = blobURL;
  4948. }
  4949. catch (e) {
  4950. img.src = null;
  4951. }
  4952. }
  4953. }
  4954. return img;
  4955. };
  4956. //ANY
  4957. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  4958. url = Tools.CleanUrl(url);
  4959. var noIndexedDB = function () {
  4960. var request = new XMLHttpRequest();
  4961. var loadUrl = Tools.BaseUrl + url;
  4962. request.open('GET', loadUrl, true);
  4963. if (useArrayBuffer) {
  4964. request.responseType = "arraybuffer";
  4965. }
  4966. request.onprogress = progressCallBack;
  4967. request.onreadystatechange = function () {
  4968. if (request.readyState === 4) {
  4969. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  4970. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  4971. callback(!useArrayBuffer ? request.responseText : request.response);
  4972. }
  4973. else {
  4974. if (onError) {
  4975. onError();
  4976. }
  4977. else {
  4978. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  4979. }
  4980. }
  4981. }
  4982. };
  4983. request.send(null);
  4984. };
  4985. var loadFromIndexedDB = function () {
  4986. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  4987. };
  4988. if (url.indexOf("file:") !== -1) {
  4989. var fileName = url.substring(5).toLowerCase();
  4990. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  4991. }
  4992. else {
  4993. // Caching all files
  4994. if (database && database.enableSceneOffline) {
  4995. database.openAsync(loadFromIndexedDB, noIndexedDB);
  4996. }
  4997. else {
  4998. noIndexedDB();
  4999. }
  5000. }
  5001. };
  5002. /**
  5003. * Load a script (identified by an url). When the url returns, the
  5004. * content of this file is added into a new script element, attached to the DOM (body element)
  5005. */
  5006. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5007. var head = document.getElementsByTagName('head')[0];
  5008. var script = document.createElement('script');
  5009. script.type = 'text/javascript';
  5010. script.src = scriptUrl;
  5011. var self = this;
  5012. script.onload = function () {
  5013. if (onSuccess) {
  5014. onSuccess();
  5015. }
  5016. };
  5017. script.onerror = function () {
  5018. if (onError) {
  5019. onError();
  5020. }
  5021. };
  5022. head.appendChild(script);
  5023. };
  5024. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5025. var reader = new FileReader();
  5026. reader.onload = function (e) {
  5027. //target doesn't have result from ts 1.3
  5028. callback(e.target['result']);
  5029. };
  5030. reader.onprogress = progressCallback;
  5031. reader.readAsDataURL(fileToLoad);
  5032. };
  5033. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5034. var reader = new FileReader();
  5035. reader.onerror = function (e) {
  5036. Tools.Log("Error while reading file: " + fileToLoad.name);
  5037. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5038. };
  5039. reader.onload = function (e) {
  5040. //target doesn't have result from ts 1.3
  5041. callback(e.target['result']);
  5042. };
  5043. reader.onprogress = progressCallBack;
  5044. if (!useArrayBuffer) {
  5045. // Asynchronous read
  5046. reader.readAsText(fileToLoad);
  5047. }
  5048. else {
  5049. reader.readAsArrayBuffer(fileToLoad);
  5050. }
  5051. };
  5052. //returns a downloadable url to a file content.
  5053. Tools.FileAsURL = function (content) {
  5054. var fileBlob = new Blob([content]);
  5055. var url = window.URL || window.webkitURL;
  5056. var link = url.createObjectURL(fileBlob);
  5057. return link;
  5058. };
  5059. // Misc.
  5060. Tools.Format = function (value, decimals) {
  5061. if (decimals === void 0) { decimals = 2; }
  5062. return value.toFixed(decimals);
  5063. };
  5064. Tools.CheckExtends = function (v, min, max) {
  5065. if (v.x < min.x)
  5066. min.x = v.x;
  5067. if (v.y < min.y)
  5068. min.y = v.y;
  5069. if (v.z < min.z)
  5070. min.z = v.z;
  5071. if (v.x > max.x)
  5072. max.x = v.x;
  5073. if (v.y > max.y)
  5074. max.y = v.y;
  5075. if (v.z > max.z)
  5076. max.z = v.z;
  5077. };
  5078. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5079. for (var prop in source) {
  5080. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5081. continue;
  5082. }
  5083. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5084. continue;
  5085. }
  5086. var sourceValue = source[prop];
  5087. var typeOfSourceValue = typeof sourceValue;
  5088. if (typeOfSourceValue === "function") {
  5089. continue;
  5090. }
  5091. if (typeOfSourceValue === "object") {
  5092. if (sourceValue instanceof Array) {
  5093. destination[prop] = [];
  5094. if (sourceValue.length > 0) {
  5095. if (typeof sourceValue[0] == "object") {
  5096. for (var index = 0; index < sourceValue.length; index++) {
  5097. var clonedValue = cloneValue(sourceValue[index], destination);
  5098. if (destination[prop].indexOf(clonedValue) === -1) {
  5099. destination[prop].push(clonedValue);
  5100. }
  5101. }
  5102. }
  5103. else {
  5104. destination[prop] = sourceValue.slice(0);
  5105. }
  5106. }
  5107. }
  5108. else {
  5109. destination[prop] = cloneValue(sourceValue, destination);
  5110. }
  5111. }
  5112. else {
  5113. destination[prop] = sourceValue;
  5114. }
  5115. }
  5116. };
  5117. Tools.IsEmpty = function (obj) {
  5118. for (var i in obj) {
  5119. return false;
  5120. }
  5121. return true;
  5122. };
  5123. Tools.RegisterTopRootEvents = function (events) {
  5124. for (var index = 0; index < events.length; index++) {
  5125. var event = events[index];
  5126. window.addEventListener(event.name, event.handler, false);
  5127. try {
  5128. if (window.parent) {
  5129. window.parent.addEventListener(event.name, event.handler, false);
  5130. }
  5131. }
  5132. catch (e) {
  5133. }
  5134. }
  5135. };
  5136. Tools.UnregisterTopRootEvents = function (events) {
  5137. for (var index = 0; index < events.length; index++) {
  5138. var event = events[index];
  5139. window.removeEventListener(event.name, event.handler);
  5140. try {
  5141. if (window.parent) {
  5142. window.parent.removeEventListener(event.name, event.handler);
  5143. }
  5144. }
  5145. catch (e) {
  5146. }
  5147. }
  5148. };
  5149. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5150. if (mimeType === void 0) { mimeType = "image/png"; }
  5151. // Read the contents of the framebuffer
  5152. var numberOfChannelsByLine = width * 4;
  5153. var halfHeight = height / 2;
  5154. //Reading datas from WebGL
  5155. var data = engine.readPixels(0, 0, width, height);
  5156. //To flip image on Y axis.
  5157. for (var i = 0; i < halfHeight; i++) {
  5158. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5159. var currentCell = j + i * numberOfChannelsByLine;
  5160. var targetLine = height - i - 1;
  5161. var targetCell = j + targetLine * numberOfChannelsByLine;
  5162. var temp = data[currentCell];
  5163. data[currentCell] = data[targetCell];
  5164. data[targetCell] = temp;
  5165. }
  5166. }
  5167. // Create a 2D canvas to store the result
  5168. if (!screenshotCanvas) {
  5169. screenshotCanvas = document.createElement('canvas');
  5170. }
  5171. screenshotCanvas.width = width;
  5172. screenshotCanvas.height = height;
  5173. var context = screenshotCanvas.getContext('2d');
  5174. // Copy the pixels to a 2D canvas
  5175. var imageData = context.createImageData(width, height);
  5176. var castData = (imageData.data);
  5177. castData.set(data);
  5178. context.putImageData(imageData, 0, 0);
  5179. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5180. };
  5181. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  5182. if (mimeType === void 0) { mimeType = "image/png"; }
  5183. var base64Image = screenshotCanvas.toDataURL(mimeType);
  5184. if (successCallback) {
  5185. successCallback(base64Image);
  5186. }
  5187. else {
  5188. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  5189. if (("download" in document.createElement("a"))) {
  5190. var a = window.document.createElement("a");
  5191. a.href = base64Image;
  5192. var date = new Date();
  5193. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  5194. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  5195. window.document.body.appendChild(a);
  5196. a.addEventListener("click", function () {
  5197. a.parentElement.removeChild(a);
  5198. });
  5199. a.click();
  5200. }
  5201. else {
  5202. var newWindow = window.open("");
  5203. var img = newWindow.document.createElement("img");
  5204. img.src = base64Image;
  5205. newWindow.document.body.appendChild(img);
  5206. }
  5207. }
  5208. };
  5209. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  5210. if (mimeType === void 0) { mimeType = "image/png"; }
  5211. var width;
  5212. var height;
  5213. // If a precision value is specified
  5214. if (size.precision) {
  5215. width = Math.round(engine.getRenderWidth() * size.precision);
  5216. height = Math.round(width / engine.getAspectRatio(camera));
  5217. }
  5218. else if (size.width && size.height) {
  5219. width = size.width;
  5220. height = size.height;
  5221. }
  5222. else if (size.width && !size.height) {
  5223. width = size.width;
  5224. height = Math.round(width / engine.getAspectRatio(camera));
  5225. }
  5226. else if (size.height && !size.width) {
  5227. height = size.height;
  5228. width = Math.round(height * engine.getAspectRatio(camera));
  5229. }
  5230. else if (!isNaN(size)) {
  5231. height = size;
  5232. width = size;
  5233. }
  5234. else {
  5235. Tools.Error("Invalid 'size' parameter !");
  5236. return;
  5237. }
  5238. if (!screenshotCanvas) {
  5239. screenshotCanvas = document.createElement('canvas');
  5240. }
  5241. screenshotCanvas.width = width;
  5242. screenshotCanvas.height = height;
  5243. var renderContext = screenshotCanvas.getContext("2d");
  5244. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  5245. var newWidth = width;
  5246. var newHeight = newWidth / ratio;
  5247. if (newHeight > height) {
  5248. newHeight = height;
  5249. newWidth = newHeight * ratio;
  5250. }
  5251. var offsetX = Math.max(0, width - newWidth) / 2;
  5252. var offsetY = Math.max(0, height - newHeight) / 2;
  5253. renderContext.fillStyle = camera.getScene().clearColor.toHexString();
  5254. renderContext.fillRect(0, 0, width, height);
  5255. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  5256. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5257. };
  5258. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType) {
  5259. if (mimeType === void 0) { mimeType = "image/png"; }
  5260. var width;
  5261. var height;
  5262. //If a precision value is specified
  5263. if (size.precision) {
  5264. width = Math.round(engine.getRenderWidth() * size.precision);
  5265. height = Math.round(width / engine.getAspectRatio(camera));
  5266. size = { width: width, height: height };
  5267. }
  5268. else if (size.width && size.height) {
  5269. width = size.width;
  5270. height = size.height;
  5271. }
  5272. else if (size.width && !size.height) {
  5273. width = size.width;
  5274. height = Math.round(width / engine.getAspectRatio(camera));
  5275. size = { width: width, height: height };
  5276. }
  5277. else if (size.height && !size.width) {
  5278. height = size.height;
  5279. width = Math.round(height * engine.getAspectRatio(camera));
  5280. size = { width: width, height: height };
  5281. }
  5282. else if (!isNaN(size)) {
  5283. height = size;
  5284. width = size;
  5285. }
  5286. else {
  5287. Tools.Error("Invalid 'size' parameter !");
  5288. return;
  5289. }
  5290. var scene = camera.getScene();
  5291. var previousCamera = null;
  5292. if (scene.activeCamera !== camera) {
  5293. previousCamera = scene.activeCamera;
  5294. scene.activeCamera = camera;
  5295. }
  5296. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  5297. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  5298. texture.renderList = scene.meshes;
  5299. texture.onAfterRenderObservable.add(function () {
  5300. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  5301. });
  5302. scene.incrementRenderId();
  5303. scene.resetCachedMaterial();
  5304. texture.render(true);
  5305. texture.dispose();
  5306. if (previousCamera) {
  5307. scene.activeCamera = previousCamera;
  5308. }
  5309. camera.getProjectionMatrix(true); // Force cache refresh;
  5310. };
  5311. // XHR response validator for local file scenario
  5312. Tools.ValidateXHRData = function (xhr, dataType) {
  5313. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  5314. if (dataType === void 0) { dataType = 7; }
  5315. try {
  5316. if (dataType & 1) {
  5317. if (xhr.responseText && xhr.responseText.length > 0) {
  5318. return true;
  5319. }
  5320. else if (dataType === 1) {
  5321. return false;
  5322. }
  5323. }
  5324. if (dataType & 2) {
  5325. // Check header width and height since there is no "TGA" magic number
  5326. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  5327. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  5328. return true;
  5329. }
  5330. else if (dataType === 2) {
  5331. return false;
  5332. }
  5333. }
  5334. if (dataType & 4) {
  5335. // Check for the "DDS" magic number
  5336. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  5337. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  5338. return true;
  5339. }
  5340. else {
  5341. return false;
  5342. }
  5343. }
  5344. }
  5345. catch (e) {
  5346. }
  5347. return false;
  5348. };
  5349. /**
  5350. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  5351. * Be aware Math.random() could cause collisions, but:
  5352. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  5353. */
  5354. Tools.RandomId = function () {
  5355. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  5356. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  5357. return v.toString(16);
  5358. });
  5359. };
  5360. Object.defineProperty(Tools, "NoneLogLevel", {
  5361. get: function () {
  5362. return Tools._NoneLogLevel;
  5363. },
  5364. enumerable: true,
  5365. configurable: true
  5366. });
  5367. Object.defineProperty(Tools, "MessageLogLevel", {
  5368. get: function () {
  5369. return Tools._MessageLogLevel;
  5370. },
  5371. enumerable: true,
  5372. configurable: true
  5373. });
  5374. Object.defineProperty(Tools, "WarningLogLevel", {
  5375. get: function () {
  5376. return Tools._WarningLogLevel;
  5377. },
  5378. enumerable: true,
  5379. configurable: true
  5380. });
  5381. Object.defineProperty(Tools, "ErrorLogLevel", {
  5382. get: function () {
  5383. return Tools._ErrorLogLevel;
  5384. },
  5385. enumerable: true,
  5386. configurable: true
  5387. });
  5388. Object.defineProperty(Tools, "AllLogLevel", {
  5389. get: function () {
  5390. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  5391. },
  5392. enumerable: true,
  5393. configurable: true
  5394. });
  5395. Tools._AddLogEntry = function (entry) {
  5396. Tools._LogCache = entry + Tools._LogCache;
  5397. if (Tools.OnNewCacheEntry) {
  5398. Tools.OnNewCacheEntry(entry);
  5399. }
  5400. };
  5401. Tools._FormatMessage = function (message) {
  5402. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  5403. var date = new Date();
  5404. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  5405. };
  5406. Tools._LogDisabled = function (message) {
  5407. // nothing to do
  5408. };
  5409. Tools._LogEnabled = function (message) {
  5410. var formattedMessage = Tools._FormatMessage(message);
  5411. console.log("BJS - " + formattedMessage);
  5412. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  5413. Tools._AddLogEntry(entry);
  5414. };
  5415. Tools._WarnDisabled = function (message) {
  5416. // nothing to do
  5417. };
  5418. Tools._WarnEnabled = function (message) {
  5419. var formattedMessage = Tools._FormatMessage(message);
  5420. console.warn("BJS - " + formattedMessage);
  5421. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  5422. Tools._AddLogEntry(entry);
  5423. };
  5424. Tools._ErrorDisabled = function (message) {
  5425. // nothing to do
  5426. };
  5427. Tools._ErrorEnabled = function (message) {
  5428. Tools.errorsCount++;
  5429. var formattedMessage = Tools._FormatMessage(message);
  5430. console.error("BJS - " + formattedMessage);
  5431. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  5432. Tools._AddLogEntry(entry);
  5433. };
  5434. Object.defineProperty(Tools, "LogCache", {
  5435. get: function () {
  5436. return Tools._LogCache;
  5437. },
  5438. enumerable: true,
  5439. configurable: true
  5440. });
  5441. Tools.ClearLogCache = function () {
  5442. Tools._LogCache = "";
  5443. Tools.errorsCount = 0;
  5444. };
  5445. Object.defineProperty(Tools, "LogLevels", {
  5446. set: function (level) {
  5447. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  5448. Tools.Log = Tools._LogEnabled;
  5449. }
  5450. else {
  5451. Tools.Log = Tools._LogDisabled;
  5452. }
  5453. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  5454. Tools.Warn = Tools._WarnEnabled;
  5455. }
  5456. else {
  5457. Tools.Warn = Tools._WarnDisabled;
  5458. }
  5459. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  5460. Tools.Error = Tools._ErrorEnabled;
  5461. }
  5462. else {
  5463. Tools.Error = Tools._ErrorDisabled;
  5464. }
  5465. },
  5466. enumerable: true,
  5467. configurable: true
  5468. });
  5469. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  5470. get: function () {
  5471. return Tools._PerformanceNoneLogLevel;
  5472. },
  5473. enumerable: true,
  5474. configurable: true
  5475. });
  5476. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  5477. get: function () {
  5478. return Tools._PerformanceUserMarkLogLevel;
  5479. },
  5480. enumerable: true,
  5481. configurable: true
  5482. });
  5483. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  5484. get: function () {
  5485. return Tools._PerformanceConsoleLogLevel;
  5486. },
  5487. enumerable: true,
  5488. configurable: true
  5489. });
  5490. Object.defineProperty(Tools, "PerformanceLogLevel", {
  5491. set: function (level) {
  5492. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  5493. Tools.StartPerformanceCounter = Tools._StartUserMark;
  5494. Tools.EndPerformanceCounter = Tools._EndUserMark;
  5495. return;
  5496. }
  5497. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  5498. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  5499. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  5500. return;
  5501. }
  5502. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5503. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5504. },
  5505. enumerable: true,
  5506. configurable: true
  5507. });
  5508. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  5509. };
  5510. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  5511. };
  5512. Tools._StartUserMark = function (counterName, condition) {
  5513. if (condition === void 0) { condition = true; }
  5514. if (!condition || !Tools._performance.mark) {
  5515. return;
  5516. }
  5517. Tools._performance.mark(counterName + "-Begin");
  5518. };
  5519. Tools._EndUserMark = function (counterName, condition) {
  5520. if (condition === void 0) { condition = true; }
  5521. if (!condition || !Tools._performance.mark) {
  5522. return;
  5523. }
  5524. Tools._performance.mark(counterName + "-End");
  5525. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  5526. };
  5527. Tools._StartPerformanceConsole = function (counterName, condition) {
  5528. if (condition === void 0) { condition = true; }
  5529. if (!condition) {
  5530. return;
  5531. }
  5532. Tools._StartUserMark(counterName, condition);
  5533. if (console.time) {
  5534. console.time(counterName);
  5535. }
  5536. };
  5537. Tools._EndPerformanceConsole = function (counterName, condition) {
  5538. if (condition === void 0) { condition = true; }
  5539. if (!condition) {
  5540. return;
  5541. }
  5542. Tools._EndUserMark(counterName, condition);
  5543. if (console.time) {
  5544. console.timeEnd(counterName);
  5545. }
  5546. };
  5547. Object.defineProperty(Tools, "Now", {
  5548. get: function () {
  5549. if (window.performance && window.performance.now) {
  5550. return window.performance.now();
  5551. }
  5552. return new Date().getTime();
  5553. },
  5554. enumerable: true,
  5555. configurable: true
  5556. });
  5557. /**
  5558. * This method will return the name of the class used to create the instance of the given object.
  5559. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  5560. * @param object the object to get the class name from
  5561. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  5562. */
  5563. Tools.getClassName = function (object, isType) {
  5564. if (isType === void 0) { isType = false; }
  5565. var name = null;
  5566. if (!isType && object.getClassName) {
  5567. name = object.getClassName();
  5568. }
  5569. else {
  5570. if (object instanceof Object) {
  5571. var classObj = isType ? object : Object.getPrototypeOf(object);
  5572. name = classObj.constructor["__bjsclassName__"];
  5573. }
  5574. if (!name) {
  5575. name = typeof object;
  5576. }
  5577. }
  5578. return name;
  5579. };
  5580. Tools.first = function (array, predicate) {
  5581. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  5582. var el = array_1[_i];
  5583. if (predicate(el)) {
  5584. return el;
  5585. }
  5586. }
  5587. };
  5588. /**
  5589. * This method will return the name of the full name of the class, including its owning module (if any).
  5590. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator or implementing a method getClassName():string (in which case the module won't be specified).
  5591. * @param object the object to get the class name from
  5592. * @return a string that can have two forms: "moduleName.className" if module was specified when the class' Name was registered or "className" if there was not module specified.
  5593. */
  5594. Tools.getFullClassName = function (object, isType) {
  5595. if (isType === void 0) { isType = false; }
  5596. var className = null;
  5597. var moduleName = null;
  5598. if (!isType && object.getClassName) {
  5599. className = object.getClassName();
  5600. }
  5601. else {
  5602. if (object instanceof Object) {
  5603. var classObj = isType ? object : Object.getPrototypeOf(object);
  5604. className = classObj.constructor["__bjsclassName__"];
  5605. moduleName = classObj.constructor["__bjsmoduleName__"];
  5606. }
  5607. if (!className) {
  5608. className = typeof object;
  5609. }
  5610. }
  5611. if (!className) {
  5612. return null;
  5613. }
  5614. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  5615. };
  5616. /**
  5617. * This method can be used with hashCodeFromStream when your input is an array of values that are either: number, string, boolean or custom type implementing the getHashCode():number method.
  5618. * @param array
  5619. */
  5620. Tools.arrayOrStringFeeder = function (array) {
  5621. return function (index) {
  5622. if (index >= array.length) {
  5623. return null;
  5624. }
  5625. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  5626. if (val && val.getHashCode) {
  5627. val = val.getHashCode();
  5628. }
  5629. if (typeof val === "string") {
  5630. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  5631. }
  5632. return val;
  5633. };
  5634. };
  5635. /**
  5636. * Compute the hashCode of a stream of number
  5637. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  5638. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  5639. * @return the hash code computed
  5640. */
  5641. Tools.hashCodeFromStream = function (feeder) {
  5642. // Based from here: http://stackoverflow.com/a/7616484/802124
  5643. var hash = 0;
  5644. var index = 0;
  5645. var chr = feeder(index++);
  5646. while (chr != null) {
  5647. hash = ((hash << 5) - hash) + chr;
  5648. hash |= 0; // Convert to 32bit integer
  5649. chr = feeder(index++);
  5650. }
  5651. return hash;
  5652. };
  5653. return Tools;
  5654. }());
  5655. Tools.BaseUrl = "";
  5656. Tools.CorsBehavior = "anonymous";
  5657. Tools.UseFallbackTexture = true;
  5658. // Logs
  5659. Tools._NoneLogLevel = 0;
  5660. Tools._MessageLogLevel = 1;
  5661. Tools._WarningLogLevel = 2;
  5662. Tools._ErrorLogLevel = 4;
  5663. Tools._LogCache = "";
  5664. Tools.errorsCount = 0;
  5665. Tools.Log = Tools._LogEnabled;
  5666. Tools.Warn = Tools._WarnEnabled;
  5667. Tools.Error = Tools._ErrorEnabled;
  5668. // Performances
  5669. Tools._PerformanceNoneLogLevel = 0;
  5670. Tools._PerformanceUserMarkLogLevel = 1;
  5671. Tools._PerformanceConsoleLogLevel = 2;
  5672. Tools._performance = window.performance;
  5673. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  5674. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  5675. BABYLON.Tools = Tools;
  5676. /**
  5677. * This class is used to track a performance counter which is number based.
  5678. * The user has access to many properties which give statistics of different nature
  5679. *
  5680. * The implementer can track two kinds of Performance Counter: time and count
  5681. * For time you can optionally call fetchNewFrame() to notify the start of a new frame to monitor, then call beginMonitoring() to start and endMonitoring() to record the lapsed time. endMonitoring takes a newFrame parameter for you to specify if the monitored time should be set for a new frame or accumulated to the current frame being monitored.
  5682. * For count you first have to call fetchNewFrame() to notify the start of a new frame to monitor, then call addCount() how many time required to increment the count value you monitor.
  5683. */
  5684. var PerfCounter = (function () {
  5685. function PerfCounter() {
  5686. this._startMonitoringTime = 0;
  5687. this._min = 0;
  5688. this._max = 0;
  5689. this._average = 0;
  5690. this._lastSecAverage = 0;
  5691. this._current = 0;
  5692. this._totalValueCount = 0;
  5693. this._totalAccumulated = 0;
  5694. this._lastSecAccumulated = 0;
  5695. this._lastSecTime = 0;
  5696. this._lastSecValueCount = 0;
  5697. }
  5698. Object.defineProperty(PerfCounter.prototype, "min", {
  5699. /**
  5700. * Returns the smallest value ever
  5701. */
  5702. get: function () {
  5703. return this._min;
  5704. },
  5705. enumerable: true,
  5706. configurable: true
  5707. });
  5708. Object.defineProperty(PerfCounter.prototype, "max", {
  5709. /**
  5710. * Returns the biggest value ever
  5711. */
  5712. get: function () {
  5713. return this._max;
  5714. },
  5715. enumerable: true,
  5716. configurable: true
  5717. });
  5718. Object.defineProperty(PerfCounter.prototype, "average", {
  5719. /**
  5720. * Returns the average value since the performance counter is running
  5721. */
  5722. get: function () {
  5723. return this._average;
  5724. },
  5725. enumerable: true,
  5726. configurable: true
  5727. });
  5728. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  5729. /**
  5730. * Returns the average value of the last second the counter was monitored
  5731. */
  5732. get: function () {
  5733. return this._lastSecAverage;
  5734. },
  5735. enumerable: true,
  5736. configurable: true
  5737. });
  5738. Object.defineProperty(PerfCounter.prototype, "current", {
  5739. /**
  5740. * Returns the current value
  5741. */
  5742. get: function () {
  5743. return this._current;
  5744. },
  5745. enumerable: true,
  5746. configurable: true
  5747. });
  5748. Object.defineProperty(PerfCounter.prototype, "total", {
  5749. get: function () {
  5750. return this._totalAccumulated;
  5751. },
  5752. enumerable: true,
  5753. configurable: true
  5754. });
  5755. /**
  5756. * Call this method to start monitoring a new frame.
  5757. * This scenario is typically used when you accumulate monitoring time many times for a single frame, you call this method at the start of the frame, then beginMonitoring to start recording and endMonitoring(false) to accumulated the recorded time to the PerfCounter or addCount() to accumulate a monitored count.
  5758. */
  5759. PerfCounter.prototype.fetchNewFrame = function () {
  5760. this._totalValueCount++;
  5761. this._current = 0;
  5762. this._lastSecValueCount++;
  5763. };
  5764. /**
  5765. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  5766. * @param newCount the count value to add to the monitored count
  5767. * @param fetchResult true when it's the last time in the frame you add to the counter and you wish to update the statistics properties (min/max/average), false if you only want to update statistics.
  5768. */
  5769. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  5770. this._current += newCount;
  5771. if (fetchResult) {
  5772. this._fetchResult();
  5773. }
  5774. };
  5775. /**
  5776. * Start monitoring this performance counter
  5777. */
  5778. PerfCounter.prototype.beginMonitoring = function () {
  5779. this._startMonitoringTime = Tools.Now;
  5780. };
  5781. /**
  5782. * Compute the time lapsed since the previous beginMonitoring() call.
  5783. * @param newFrame true by default to fetch the result and monitor a new frame, if false the time monitored will be added to the current frame counter
  5784. */
  5785. PerfCounter.prototype.endMonitoring = function (newFrame) {
  5786. if (newFrame === void 0) { newFrame = true; }
  5787. if (newFrame) {
  5788. this.fetchNewFrame();
  5789. }
  5790. var currentTime = Tools.Now;
  5791. this._current = currentTime - this._startMonitoringTime;
  5792. if (newFrame) {
  5793. this._fetchResult();
  5794. }
  5795. };
  5796. PerfCounter.prototype._fetchResult = function () {
  5797. this._totalAccumulated += this._current;
  5798. this._lastSecAccumulated += this._current;
  5799. // Min/Max update
  5800. this._min = Math.min(this._min, this._current);
  5801. this._max = Math.max(this._max, this._current);
  5802. this._average = this._totalAccumulated / this._totalValueCount;
  5803. // Reset last sec?
  5804. var now = Tools.Now;
  5805. if ((now - this._lastSecTime) > 1000) {
  5806. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  5807. this._lastSecTime = now;
  5808. this._lastSecAccumulated = 0;
  5809. this._lastSecValueCount = 0;
  5810. }
  5811. };
  5812. return PerfCounter;
  5813. }());
  5814. BABYLON.PerfCounter = PerfCounter;
  5815. /**
  5816. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  5817. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  5818. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  5819. * @param name The name of the class, case should be preserved
  5820. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  5821. */
  5822. function className(name, module) {
  5823. return function (target) {
  5824. target["__bjsclassName__"] = name;
  5825. target["__bjsmoduleName__"] = (module != null) ? module : null;
  5826. };
  5827. }
  5828. BABYLON.className = className;
  5829. /**
  5830. * An implementation of a loop for asynchronous functions.
  5831. */
  5832. var AsyncLoop = (function () {
  5833. /**
  5834. * Constroctor.
  5835. * @param iterations the number of iterations.
  5836. * @param _fn the function to run each iteration
  5837. * @param _successCallback the callback that will be called upon succesful execution
  5838. * @param offset starting offset.
  5839. */
  5840. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  5841. if (offset === void 0) { offset = 0; }
  5842. this.iterations = iterations;
  5843. this._fn = _fn;
  5844. this._successCallback = _successCallback;
  5845. this.index = offset - 1;
  5846. this._done = false;
  5847. }
  5848. /**
  5849. * Execute the next iteration. Must be called after the last iteration was finished.
  5850. */
  5851. AsyncLoop.prototype.executeNext = function () {
  5852. if (!this._done) {
  5853. if (this.index + 1 < this.iterations) {
  5854. ++this.index;
  5855. this._fn(this);
  5856. }
  5857. else {
  5858. this.breakLoop();
  5859. }
  5860. }
  5861. };
  5862. /**
  5863. * Break the loop and run the success callback.
  5864. */
  5865. AsyncLoop.prototype.breakLoop = function () {
  5866. this._done = true;
  5867. this._successCallback();
  5868. };
  5869. /**
  5870. * Helper function
  5871. */
  5872. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  5873. if (offset === void 0) { offset = 0; }
  5874. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  5875. loop.executeNext();
  5876. return loop;
  5877. };
  5878. /**
  5879. * A for-loop that will run a given number of iterations synchronous and the rest async.
  5880. * @param iterations total number of iterations
  5881. * @param syncedIterations number of synchronous iterations in each async iteration.
  5882. * @param fn the function to call each iteration.
  5883. * @param callback a success call back that will be called when iterating stops.
  5884. * @param breakFunction a break condition (optional)
  5885. * @param timeout timeout settings for the setTimeout function. default - 0.
  5886. * @constructor
  5887. */
  5888. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  5889. if (timeout === void 0) { timeout = 0; }
  5890. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  5891. if (breakFunction && breakFunction())
  5892. loop.breakLoop();
  5893. else {
  5894. setTimeout(function () {
  5895. for (var i = 0; i < syncedIterations; ++i) {
  5896. var iteration = (loop.index * syncedIterations) + i;
  5897. if (iteration >= iterations)
  5898. break;
  5899. fn(iteration);
  5900. if (breakFunction && breakFunction()) {
  5901. loop.breakLoop();
  5902. break;
  5903. }
  5904. }
  5905. loop.executeNext();
  5906. }, timeout);
  5907. }
  5908. }, callback);
  5909. };
  5910. return AsyncLoop;
  5911. }());
  5912. BABYLON.AsyncLoop = AsyncLoop;
  5913. })(BABYLON || (BABYLON = {}));
  5914. //# sourceMappingURL=babylon.tools.js.map
  5915. var BABYLON;
  5916. (function (BABYLON) {
  5917. var Internals;
  5918. (function (Internals) {
  5919. var _AlphaState = (function () {
  5920. /**
  5921. * Initializes the state.
  5922. */
  5923. function _AlphaState() {
  5924. this._isAlphaBlendDirty = false;
  5925. this._isBlendFunctionParametersDirty = false;
  5926. this._alphaBlend = false;
  5927. this._blendFunctionParameters = new Array(4);
  5928. this.reset();
  5929. }
  5930. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  5931. get: function () {
  5932. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  5933. },
  5934. enumerable: true,
  5935. configurable: true
  5936. });
  5937. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  5938. get: function () {
  5939. return this._alphaBlend;
  5940. },
  5941. set: function (value) {
  5942. if (this._alphaBlend === value) {
  5943. return;
  5944. }
  5945. this._alphaBlend = value;
  5946. this._isAlphaBlendDirty = true;
  5947. },
  5948. enumerable: true,
  5949. configurable: true
  5950. });
  5951. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  5952. if (this._blendFunctionParameters[0] === value0 &&
  5953. this._blendFunctionParameters[1] === value1 &&
  5954. this._blendFunctionParameters[2] === value2 &&
  5955. this._blendFunctionParameters[3] === value3) {
  5956. return;
  5957. }
  5958. this._blendFunctionParameters[0] = value0;
  5959. this._blendFunctionParameters[1] = value1;
  5960. this._blendFunctionParameters[2] = value2;
  5961. this._blendFunctionParameters[3] = value3;
  5962. this._isBlendFunctionParametersDirty = true;
  5963. };
  5964. _AlphaState.prototype.reset = function () {
  5965. this._alphaBlend = false;
  5966. this._blendFunctionParameters[0] = null;
  5967. this._blendFunctionParameters[1] = null;
  5968. this._blendFunctionParameters[2] = null;
  5969. this._blendFunctionParameters[3] = null;
  5970. this._isAlphaBlendDirty = true;
  5971. this._isBlendFunctionParametersDirty = false;
  5972. };
  5973. _AlphaState.prototype.apply = function (gl) {
  5974. if (!this.isDirty) {
  5975. return;
  5976. }
  5977. // Alpha blend
  5978. if (this._isAlphaBlendDirty) {
  5979. if (this._alphaBlend) {
  5980. gl.enable(gl.BLEND);
  5981. }
  5982. else {
  5983. gl.disable(gl.BLEND);
  5984. }
  5985. this._isAlphaBlendDirty = false;
  5986. }
  5987. // Alpha function
  5988. if (this._isBlendFunctionParametersDirty) {
  5989. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  5990. this._isBlendFunctionParametersDirty = false;
  5991. }
  5992. };
  5993. return _AlphaState;
  5994. }());
  5995. Internals._AlphaState = _AlphaState;
  5996. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  5997. })(BABYLON || (BABYLON = {}));
  5998. //# sourceMappingURL=babylon.alphaCullingState.js.map
  5999. var BABYLON;
  6000. (function (BABYLON) {
  6001. var Internals;
  6002. (function (Internals) {
  6003. var _DepthCullingState = (function () {
  6004. /**
  6005. * Initializes the state.
  6006. */
  6007. function _DepthCullingState() {
  6008. this._isDepthTestDirty = false;
  6009. this._isDepthMaskDirty = false;
  6010. this._isDepthFuncDirty = false;
  6011. this._isCullFaceDirty = false;
  6012. this._isCullDirty = false;
  6013. this._isZOffsetDirty = false;
  6014. this.reset();
  6015. }
  6016. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6017. get: function () {
  6018. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6019. },
  6020. enumerable: true,
  6021. configurable: true
  6022. });
  6023. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6024. get: function () {
  6025. return this._zOffset;
  6026. },
  6027. set: function (value) {
  6028. if (this._zOffset === value) {
  6029. return;
  6030. }
  6031. this._zOffset = value;
  6032. this._isZOffsetDirty = true;
  6033. },
  6034. enumerable: true,
  6035. configurable: true
  6036. });
  6037. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6038. get: function () {
  6039. return this._cullFace;
  6040. },
  6041. set: function (value) {
  6042. if (this._cullFace === value) {
  6043. return;
  6044. }
  6045. this._cullFace = value;
  6046. this._isCullFaceDirty = true;
  6047. },
  6048. enumerable: true,
  6049. configurable: true
  6050. });
  6051. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6052. get: function () {
  6053. return this._cull;
  6054. },
  6055. set: function (value) {
  6056. if (this._cull === value) {
  6057. return;
  6058. }
  6059. this._cull = value;
  6060. this._isCullDirty = true;
  6061. },
  6062. enumerable: true,
  6063. configurable: true
  6064. });
  6065. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6066. get: function () {
  6067. return this._depthFunc;
  6068. },
  6069. set: function (value) {
  6070. if (this._depthFunc === value) {
  6071. return;
  6072. }
  6073. this._depthFunc = value;
  6074. this._isDepthFuncDirty = true;
  6075. },
  6076. enumerable: true,
  6077. configurable: true
  6078. });
  6079. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6080. get: function () {
  6081. return this._depthMask;
  6082. },
  6083. set: function (value) {
  6084. if (this._depthMask === value) {
  6085. return;
  6086. }
  6087. this._depthMask = value;
  6088. this._isDepthMaskDirty = true;
  6089. },
  6090. enumerable: true,
  6091. configurable: true
  6092. });
  6093. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6094. get: function () {
  6095. return this._depthTest;
  6096. },
  6097. set: function (value) {
  6098. if (this._depthTest === value) {
  6099. return;
  6100. }
  6101. this._depthTest = value;
  6102. this._isDepthTestDirty = true;
  6103. },
  6104. enumerable: true,
  6105. configurable: true
  6106. });
  6107. _DepthCullingState.prototype.reset = function () {
  6108. this._depthMask = true;
  6109. this._depthTest = true;
  6110. this._depthFunc = null;
  6111. this._cullFace = null;
  6112. this._cull = null;
  6113. this._zOffset = 0;
  6114. this._isDepthTestDirty = true;
  6115. this._isDepthMaskDirty = true;
  6116. this._isDepthFuncDirty = false;
  6117. this._isCullFaceDirty = false;
  6118. this._isCullDirty = false;
  6119. this._isZOffsetDirty = false;
  6120. };
  6121. _DepthCullingState.prototype.apply = function (gl) {
  6122. if (!this.isDirty) {
  6123. return;
  6124. }
  6125. // Cull
  6126. if (this._isCullDirty) {
  6127. if (this.cull) {
  6128. gl.enable(gl.CULL_FACE);
  6129. }
  6130. else {
  6131. gl.disable(gl.CULL_FACE);
  6132. }
  6133. this._isCullDirty = false;
  6134. }
  6135. // Cull face
  6136. if (this._isCullFaceDirty) {
  6137. gl.cullFace(this.cullFace);
  6138. this._isCullFaceDirty = false;
  6139. }
  6140. // Depth mask
  6141. if (this._isDepthMaskDirty) {
  6142. gl.depthMask(this.depthMask);
  6143. this._isDepthMaskDirty = false;
  6144. }
  6145. // Depth test
  6146. if (this._isDepthTestDirty) {
  6147. if (this.depthTest) {
  6148. gl.enable(gl.DEPTH_TEST);
  6149. }
  6150. else {
  6151. gl.disable(gl.DEPTH_TEST);
  6152. }
  6153. this._isDepthTestDirty = false;
  6154. }
  6155. // Depth func
  6156. if (this._isDepthFuncDirty) {
  6157. gl.depthFunc(this.depthFunc);
  6158. this._isDepthFuncDirty = false;
  6159. }
  6160. // zOffset
  6161. if (this._isZOffsetDirty) {
  6162. if (this.zOffset) {
  6163. gl.enable(gl.POLYGON_OFFSET_FILL);
  6164. gl.polygonOffset(this.zOffset, 0);
  6165. }
  6166. else {
  6167. gl.disable(gl.POLYGON_OFFSET_FILL);
  6168. }
  6169. this._isZOffsetDirty = false;
  6170. }
  6171. };
  6172. return _DepthCullingState;
  6173. }());
  6174. Internals._DepthCullingState = _DepthCullingState;
  6175. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6176. })(BABYLON || (BABYLON = {}));
  6177. //# sourceMappingURL=babylon.depthCullingState.js.map
  6178. var BABYLON;
  6179. (function (BABYLON) {
  6180. var Internals;
  6181. (function (Internals) {
  6182. var _StencilState = (function () {
  6183. function _StencilState() {
  6184. this._isStencilTestDirty = false;
  6185. this._isStencilMaskDirty = false;
  6186. this._isStencilFuncDirty = false;
  6187. this._isStencilOpDirty = false;
  6188. this.reset();
  6189. }
  6190. Object.defineProperty(_StencilState.prototype, "isDirty", {
  6191. get: function () {
  6192. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  6193. },
  6194. enumerable: true,
  6195. configurable: true
  6196. });
  6197. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  6198. get: function () {
  6199. return this._stencilFunc;
  6200. },
  6201. set: function (value) {
  6202. if (this._stencilFunc === value) {
  6203. return;
  6204. }
  6205. this._stencilFunc = value;
  6206. this._isStencilFuncDirty = true;
  6207. },
  6208. enumerable: true,
  6209. configurable: true
  6210. });
  6211. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  6212. get: function () {
  6213. return this._stencilFuncRef;
  6214. },
  6215. set: function (value) {
  6216. if (this._stencilFuncRef === value) {
  6217. return;
  6218. }
  6219. this._stencilFuncRef = value;
  6220. this._isStencilFuncDirty = true;
  6221. },
  6222. enumerable: true,
  6223. configurable: true
  6224. });
  6225. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  6226. get: function () {
  6227. return this._stencilFuncMask;
  6228. },
  6229. set: function (value) {
  6230. if (this._stencilFuncMask === value) {
  6231. return;
  6232. }
  6233. this._stencilFuncMask = value;
  6234. this._isStencilFuncDirty = true;
  6235. },
  6236. enumerable: true,
  6237. configurable: true
  6238. });
  6239. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  6240. get: function () {
  6241. return this._stencilOpStencilFail;
  6242. },
  6243. set: function (value) {
  6244. if (this._stencilOpStencilFail === value) {
  6245. return;
  6246. }
  6247. this._stencilOpStencilFail = value;
  6248. this._isStencilOpDirty = true;
  6249. },
  6250. enumerable: true,
  6251. configurable: true
  6252. });
  6253. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  6254. get: function () {
  6255. return this._stencilOpDepthFail;
  6256. },
  6257. set: function (value) {
  6258. if (this._stencilOpDepthFail === value) {
  6259. return;
  6260. }
  6261. this._stencilOpDepthFail = value;
  6262. this._isStencilOpDirty = true;
  6263. },
  6264. enumerable: true,
  6265. configurable: true
  6266. });
  6267. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  6268. get: function () {
  6269. return this._stencilOpStencilDepthPass;
  6270. },
  6271. set: function (value) {
  6272. if (this._stencilOpStencilDepthPass === value) {
  6273. return;
  6274. }
  6275. this._stencilOpStencilDepthPass = value;
  6276. this._isStencilOpDirty = true;
  6277. },
  6278. enumerable: true,
  6279. configurable: true
  6280. });
  6281. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  6282. get: function () {
  6283. return this._stencilMask;
  6284. },
  6285. set: function (value) {
  6286. if (this._stencilMask === value) {
  6287. return;
  6288. }
  6289. this._stencilMask = value;
  6290. this._isStencilMaskDirty = true;
  6291. },
  6292. enumerable: true,
  6293. configurable: true
  6294. });
  6295. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  6296. get: function () {
  6297. return this._stencilTest;
  6298. },
  6299. set: function (value) {
  6300. if (this._stencilTest === value) {
  6301. return;
  6302. }
  6303. this._stencilTest = value;
  6304. this._isStencilTestDirty = true;
  6305. },
  6306. enumerable: true,
  6307. configurable: true
  6308. });
  6309. _StencilState.prototype.reset = function () {
  6310. this._stencilTest = false;
  6311. this._stencilMask = 0xFF;
  6312. this._stencilFunc = BABYLON.Engine.ALWAYS;
  6313. this._stencilFuncRef = 1;
  6314. this._stencilFuncMask = 0xFF;
  6315. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  6316. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  6317. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  6318. this._isStencilTestDirty = true;
  6319. this._isStencilMaskDirty = true;
  6320. this._isStencilFuncDirty = true;
  6321. this._isStencilOpDirty = true;
  6322. };
  6323. _StencilState.prototype.apply = function (gl) {
  6324. if (!this.isDirty) {
  6325. return;
  6326. }
  6327. // Stencil test
  6328. if (this._isStencilTestDirty) {
  6329. if (this.stencilTest) {
  6330. gl.enable(gl.STENCIL_TEST);
  6331. }
  6332. else {
  6333. gl.disable(gl.STENCIL_TEST);
  6334. }
  6335. this._isStencilTestDirty = false;
  6336. }
  6337. // Stencil mask
  6338. if (this._isStencilMaskDirty) {
  6339. gl.stencilMask(this.stencilMask);
  6340. this._isStencilMaskDirty = false;
  6341. }
  6342. // Stencil func
  6343. if (this._isStencilFuncDirty) {
  6344. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  6345. this._isStencilFuncDirty = false;
  6346. }
  6347. // Stencil op
  6348. if (this._isStencilOpDirty) {
  6349. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  6350. this._isStencilOpDirty = false;
  6351. }
  6352. };
  6353. return _StencilState;
  6354. }());
  6355. Internals._StencilState = _StencilState;
  6356. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6357. })(BABYLON || (BABYLON = {}));
  6358. //# sourceMappingURL=babylon.stencilState.js.map
  6359. var BABYLON;
  6360. (function (BABYLON) {
  6361. var compileShader = function (gl, source, type, defines) {
  6362. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  6363. gl.shaderSource(shader, (defines ? defines + "\n" : "") + source);
  6364. gl.compileShader(shader);
  6365. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  6366. throw new Error(gl.getShaderInfoLog(shader));
  6367. }
  6368. return shader;
  6369. };
  6370. var HALF_FLOAT_OES = 0x8D61;
  6371. var getWebGLTextureType = function (gl, type) {
  6372. if (type === Engine.TEXTURETYPE_FLOAT) {
  6373. return gl.FLOAT;
  6374. }
  6375. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  6376. // Add Half Float Constant.
  6377. return HALF_FLOAT_OES;
  6378. }
  6379. return gl.UNSIGNED_BYTE;
  6380. };
  6381. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  6382. var magFilter = gl.NEAREST;
  6383. var minFilter = gl.NEAREST;
  6384. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  6385. magFilter = gl.LINEAR;
  6386. if (generateMipMaps) {
  6387. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  6388. }
  6389. else {
  6390. minFilter = gl.LINEAR;
  6391. }
  6392. }
  6393. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  6394. magFilter = gl.LINEAR;
  6395. if (generateMipMaps) {
  6396. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  6397. }
  6398. else {
  6399. minFilter = gl.LINEAR;
  6400. }
  6401. }
  6402. else if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  6403. magFilter = gl.NEAREST;
  6404. if (generateMipMaps) {
  6405. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  6406. }
  6407. else {
  6408. minFilter = gl.NEAREST;
  6409. }
  6410. }
  6411. return {
  6412. min: minFilter,
  6413. mag: magFilter
  6414. };
  6415. };
  6416. var prepareWebGLTexture = function (texture, gl, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  6417. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  6418. var engine = scene.getEngine();
  6419. var potWidth = BABYLON.Tools.GetExponentOfTwo(width, engine.getCaps().maxTextureSize);
  6420. var potHeight = BABYLON.Tools.GetExponentOfTwo(height, engine.getCaps().maxTextureSize);
  6421. engine._bindTextureDirectly(gl.TEXTURE_2D, texture);
  6422. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  6423. texture._baseWidth = width;
  6424. texture._baseHeight = height;
  6425. texture._width = potWidth;
  6426. texture._height = potHeight;
  6427. texture.isReady = true;
  6428. processFunction(potWidth, potHeight);
  6429. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  6430. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  6431. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  6432. if (!noMipmap && !isCompressed) {
  6433. gl.generateMipmap(gl.TEXTURE_2D);
  6434. }
  6435. engine._bindTextureDirectly(gl.TEXTURE_2D, null);
  6436. engine.resetTextureCache();
  6437. scene._removePendingData(texture);
  6438. texture.onLoadedCallbacks.forEach(function (callback) {
  6439. callback();
  6440. });
  6441. texture.onLoadedCallbacks = [];
  6442. };
  6443. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  6444. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  6445. var img;
  6446. var onload = function () {
  6447. loadedImages[index] = img;
  6448. loadedImages._internalCount++;
  6449. scene._removePendingData(img);
  6450. if (loadedImages._internalCount === 6) {
  6451. onfinish(loadedImages);
  6452. }
  6453. };
  6454. var onerror = function () {
  6455. scene._removePendingData(img);
  6456. if (onErrorCallBack) {
  6457. onErrorCallBack();
  6458. }
  6459. };
  6460. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  6461. scene._addPendingData(img);
  6462. };
  6463. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  6464. if (onError === void 0) { onError = null; }
  6465. var loadedImages = [];
  6466. loadedImages._internalCount = 0;
  6467. for (var index = 0; index < 6; index++) {
  6468. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  6469. }
  6470. };
  6471. var InstancingAttributeInfo = (function () {
  6472. function InstancingAttributeInfo() {
  6473. }
  6474. return InstancingAttributeInfo;
  6475. }());
  6476. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  6477. var EngineCapabilities = (function () {
  6478. function EngineCapabilities() {
  6479. }
  6480. return EngineCapabilities;
  6481. }());
  6482. BABYLON.EngineCapabilities = EngineCapabilities;
  6483. /**
  6484. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  6485. */
  6486. var Engine = (function () {
  6487. /**
  6488. * @constructor
  6489. * @param {HTMLCanvasElement} canvas - the canvas to be used for rendering
  6490. * @param {boolean} [antialias] - enable antialias
  6491. * @param options - further options to be sent to the getContext function
  6492. */
  6493. function Engine(canvas, antialias, options, adaptToDeviceRatio) {
  6494. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  6495. var _this = this;
  6496. // Public members
  6497. this.isFullscreen = false;
  6498. this.isPointerLock = false;
  6499. this.cullBackFaces = true;
  6500. this.renderEvenInBackground = true;
  6501. // To enable/disable IDB support and avoid XHR on .manifest
  6502. this.enableOfflineSupport = true;
  6503. this.scenes = new Array();
  6504. this._windowIsBackground = false;
  6505. this._webGLVersion = "1.0";
  6506. this._badOS = false;
  6507. this._drawCalls = new BABYLON.PerfCounter();
  6508. this._renderingQueueLaunched = false;
  6509. this._activeRenderLoops = [];
  6510. // FPS
  6511. this.fpsRange = 60;
  6512. this.previousFramesDuration = [];
  6513. this.fps = 60;
  6514. this.deltaTime = 0;
  6515. // States
  6516. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  6517. this._stencilState = new BABYLON.Internals._StencilState();
  6518. this._alphaState = new BABYLON.Internals._AlphaState();
  6519. this._alphaMode = Engine.ALPHA_DISABLE;
  6520. // Cache
  6521. this._loadedTexturesCache = new Array();
  6522. this._maxTextureChannels = 16;
  6523. this._activeTexturesCache = new Array(this._maxTextureChannels);
  6524. this._compiledEffects = {};
  6525. this._vertexAttribArraysEnabled = [];
  6526. this._uintIndicesCurrentlySet = false;
  6527. this._currentBoundBuffer = new Array();
  6528. this._currentBufferPointers = [];
  6529. this._currentInstanceLocations = new Array();
  6530. this._currentInstanceBuffers = new Array();
  6531. // Hardware supported Compressed Textures
  6532. this._texturesSupported = new Array();
  6533. this._onVRFullScreenTriggered = function () {
  6534. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  6535. //get the old size before we change
  6536. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  6537. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  6538. //according to the WebVR specs, requestAnimationFrame should be triggered only once.
  6539. //But actually, no browser follow the specs...
  6540. //this._vrAnimationFrameHandler = this._vrDisplayEnabled.requestAnimationFrame(this._bindedRenderFunction);
  6541. //get the width and height, change the render size
  6542. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  6543. var width, height;
  6544. _this.setHardwareScalingLevel(1);
  6545. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  6546. }
  6547. else {
  6548. //When the specs are implemented, need to uncomment this.
  6549. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  6550. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  6551. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  6552. _this._vrDisplayEnabled = undefined;
  6553. }
  6554. };
  6555. this._renderingCanvas = canvas;
  6556. this._externalData = new BABYLON.StringDictionary();
  6557. options = options || {};
  6558. if (antialias != null) {
  6559. options.antialias = antialias;
  6560. }
  6561. if (options.preserveDrawingBuffer === undefined) {
  6562. options.preserveDrawingBuffer = false;
  6563. }
  6564. // Checks if some of the format renders first to allow the use of webgl inspector.
  6565. var renderToFullFloat = this._canRenderToFloatTexture();
  6566. var renderToHalfFloat = this._canRenderToHalfFloatTexture();
  6567. // GL
  6568. // try {
  6569. // this._gl = <WebGLRenderingContext>(canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  6570. // if (this._gl) {
  6571. // this._webGLVersion = "2.0";
  6572. // }
  6573. // } catch (e) {
  6574. // // Do nothing
  6575. // }
  6576. if (!this._gl) {
  6577. if (!canvas) {
  6578. throw new Error("The provided canvas is null or undefined.");
  6579. }
  6580. try {
  6581. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  6582. }
  6583. catch (e) {
  6584. throw new Error("WebGL not supported");
  6585. }
  6586. }
  6587. if (!this._gl) {
  6588. throw new Error("WebGL not supported");
  6589. }
  6590. this._onBlur = function () {
  6591. _this._windowIsBackground = true;
  6592. };
  6593. this._onFocus = function () {
  6594. _this._windowIsBackground = false;
  6595. };
  6596. window.addEventListener("blur", this._onBlur);
  6597. window.addEventListener("focus", this._onFocus);
  6598. // Viewport
  6599. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  6600. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  6601. this.resize();
  6602. // Caps
  6603. this._isStencilEnable = options.stencil;
  6604. this._caps = new EngineCapabilities();
  6605. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  6606. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  6607. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  6608. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  6609. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  6610. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  6611. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  6612. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  6613. // Infos
  6614. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  6615. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  6616. if (rendererInfo != null) {
  6617. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  6618. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  6619. }
  6620. if (!this._glVendor) {
  6621. this._glVendor = "Unknown vendor";
  6622. }
  6623. if (!this._glRenderer) {
  6624. this._glRenderer = "Unknown renderer";
  6625. }
  6626. // Extensions
  6627. this._caps.standardDerivatives = (this._gl.getExtension('OES_standard_derivatives') !== null);
  6628. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc');
  6629. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc');
  6630. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc'); // 2nd is what iOS reports
  6631. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1');
  6632. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // first is the final name, found hardware using 2nd
  6633. this._caps.textureFloat = (this._gl.getExtension('OES_texture_float') !== null);
  6634. 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');
  6635. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  6636. this._caps.instancedArrays = this._gl.getExtension('ANGLE_instanced_arrays');
  6637. this._caps.uintIndices = this._gl.getExtension('OES_element_index_uint') !== null;
  6638. this._caps.fragmentDepthSupported = this._gl.getExtension('EXT_frag_depth') !== null;
  6639. this._caps.highPrecisionShaderSupported = true;
  6640. this._caps.drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  6641. this._caps.textureFloatLinearFiltering = this._gl.getExtension('OES_texture_float_linear');
  6642. this._caps.textureLOD = this._gl.getExtension('EXT_shader_texture_lod');
  6643. this._caps.textureFloatRender = renderToFullFloat;
  6644. this._caps.textureHalfFloat = (this._gl.getExtension('OES_texture_half_float') !== null);
  6645. this._caps.textureHalfFloatLinearFiltering = this._gl.getExtension('OES_texture_half_float_linear');
  6646. this._caps.textureHalfFloatRender = renderToHalfFloat;
  6647. // Intelligently add supported commpressed formats in order to check for.
  6648. // Check for ASTC support first as it is most powerful and to be very cross platform.
  6649. // Next PVR & S3, which are probably superior to ETC1/2.
  6650. // Likely no hardware which supports both PVR & S3, so order matters little.
  6651. // ETC2 is newer and handles ETC1, so check for first.
  6652. if (this._caps.astc)
  6653. this.texturesSupported.push('.astc');
  6654. if (this._caps.s3tc)
  6655. this.texturesSupported.push('.dds');
  6656. if (this._caps.pvrtc)
  6657. this.texturesSupported.push('.pvr');
  6658. if (this._caps.etc2)
  6659. this.texturesSupported.push('.etc2');
  6660. if (this._caps.etc1)
  6661. this.texturesSupported.push('.etc1');
  6662. if (this._gl.getShaderPrecisionFormat) {
  6663. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  6664. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  6665. }
  6666. // Depth buffer
  6667. this.setDepthBuffer(true);
  6668. this.setDepthFunctionToLessOrEqual();
  6669. this.setDepthWrite(true);
  6670. // Fullscreen
  6671. this._onFullscreenChange = function () {
  6672. if (document.fullscreen !== undefined) {
  6673. _this.isFullscreen = document.fullscreen;
  6674. }
  6675. else if (document.mozFullScreen !== undefined) {
  6676. _this.isFullscreen = document.mozFullScreen;
  6677. }
  6678. else if (document.webkitIsFullScreen !== undefined) {
  6679. _this.isFullscreen = document.webkitIsFullScreen;
  6680. }
  6681. else if (document.msIsFullScreen !== undefined) {
  6682. _this.isFullscreen = document.msIsFullScreen;
  6683. }
  6684. // Pointer lock
  6685. if (_this.isFullscreen && _this._pointerLockRequested) {
  6686. canvas.requestPointerLock = canvas.requestPointerLock ||
  6687. canvas.msRequestPointerLock ||
  6688. canvas.mozRequestPointerLock ||
  6689. canvas.webkitRequestPointerLock;
  6690. if (canvas.requestPointerLock) {
  6691. canvas.requestPointerLock();
  6692. }
  6693. }
  6694. };
  6695. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  6696. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  6697. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  6698. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  6699. // Pointer lock
  6700. this._onPointerLockChange = function () {
  6701. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  6702. document.webkitPointerLockElement === canvas ||
  6703. document.msPointerLockElement === canvas ||
  6704. document.pointerLockElement === canvas);
  6705. };
  6706. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  6707. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  6708. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  6709. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  6710. if (BABYLON.AudioEngine && !Engine.audioEngine) {
  6711. Engine.audioEngine = new BABYLON.AudioEngine();
  6712. }
  6713. //default loading screen
  6714. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  6715. //Load WebVR Devices
  6716. if (options.autoEnableWebVR) {
  6717. this.initWebVR();
  6718. }
  6719. //Detect if we are running on a faulty buggy OS.
  6720. var regexp = /AppleWebKit.*10.[\d] Mobile/;
  6721. //ua sniffing is the tool of the devil.
  6722. this._badOS = regexp.test(navigator.userAgent);
  6723. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  6724. }
  6725. Object.defineProperty(Engine, "NEVER", {
  6726. get: function () {
  6727. return Engine._NEVER;
  6728. },
  6729. enumerable: true,
  6730. configurable: true
  6731. });
  6732. Object.defineProperty(Engine, "ALWAYS", {
  6733. get: function () {
  6734. return Engine._ALWAYS;
  6735. },
  6736. enumerable: true,
  6737. configurable: true
  6738. });
  6739. Object.defineProperty(Engine, "LESS", {
  6740. get: function () {
  6741. return Engine._LESS;
  6742. },
  6743. enumerable: true,
  6744. configurable: true
  6745. });
  6746. Object.defineProperty(Engine, "EQUAL", {
  6747. get: function () {
  6748. return Engine._EQUAL;
  6749. },
  6750. enumerable: true,
  6751. configurable: true
  6752. });
  6753. Object.defineProperty(Engine, "LEQUAL", {
  6754. get: function () {
  6755. return Engine._LEQUAL;
  6756. },
  6757. enumerable: true,
  6758. configurable: true
  6759. });
  6760. Object.defineProperty(Engine, "GREATER", {
  6761. get: function () {
  6762. return Engine._GREATER;
  6763. },
  6764. enumerable: true,
  6765. configurable: true
  6766. });
  6767. Object.defineProperty(Engine, "GEQUAL", {
  6768. get: function () {
  6769. return Engine._GEQUAL;
  6770. },
  6771. enumerable: true,
  6772. configurable: true
  6773. });
  6774. Object.defineProperty(Engine, "NOTEQUAL", {
  6775. get: function () {
  6776. return Engine._NOTEQUAL;
  6777. },
  6778. enumerable: true,
  6779. configurable: true
  6780. });
  6781. Object.defineProperty(Engine, "KEEP", {
  6782. get: function () {
  6783. return Engine._KEEP;
  6784. },
  6785. enumerable: true,
  6786. configurable: true
  6787. });
  6788. Object.defineProperty(Engine, "REPLACE", {
  6789. get: function () {
  6790. return Engine._REPLACE;
  6791. },
  6792. enumerable: true,
  6793. configurable: true
  6794. });
  6795. Object.defineProperty(Engine, "INCR", {
  6796. get: function () {
  6797. return Engine._INCR;
  6798. },
  6799. enumerable: true,
  6800. configurable: true
  6801. });
  6802. Object.defineProperty(Engine, "DECR", {
  6803. get: function () {
  6804. return Engine._DECR;
  6805. },
  6806. enumerable: true,
  6807. configurable: true
  6808. });
  6809. Object.defineProperty(Engine, "INVERT", {
  6810. get: function () {
  6811. return Engine._INVERT;
  6812. },
  6813. enumerable: true,
  6814. configurable: true
  6815. });
  6816. Object.defineProperty(Engine, "INCR_WRAP", {
  6817. get: function () {
  6818. return Engine._INCR_WRAP;
  6819. },
  6820. enumerable: true,
  6821. configurable: true
  6822. });
  6823. Object.defineProperty(Engine, "DECR_WRAP", {
  6824. get: function () {
  6825. return Engine._DECR_WRAP;
  6826. },
  6827. enumerable: true,
  6828. configurable: true
  6829. });
  6830. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  6831. get: function () {
  6832. return Engine._ALPHA_DISABLE;
  6833. },
  6834. enumerable: true,
  6835. configurable: true
  6836. });
  6837. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  6838. get: function () {
  6839. return Engine._ALPHA_ONEONE;
  6840. },
  6841. enumerable: true,
  6842. configurable: true
  6843. });
  6844. Object.defineProperty(Engine, "ALPHA_ADD", {
  6845. get: function () {
  6846. return Engine._ALPHA_ADD;
  6847. },
  6848. enumerable: true,
  6849. configurable: true
  6850. });
  6851. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  6852. get: function () {
  6853. return Engine._ALPHA_COMBINE;
  6854. },
  6855. enumerable: true,
  6856. configurable: true
  6857. });
  6858. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  6859. get: function () {
  6860. return Engine._ALPHA_SUBTRACT;
  6861. },
  6862. enumerable: true,
  6863. configurable: true
  6864. });
  6865. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  6866. get: function () {
  6867. return Engine._ALPHA_MULTIPLY;
  6868. },
  6869. enumerable: true,
  6870. configurable: true
  6871. });
  6872. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  6873. get: function () {
  6874. return Engine._ALPHA_MAXIMIZED;
  6875. },
  6876. enumerable: true,
  6877. configurable: true
  6878. });
  6879. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  6880. get: function () {
  6881. return Engine._ALPHA_PREMULTIPLIED;
  6882. },
  6883. enumerable: true,
  6884. configurable: true
  6885. });
  6886. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  6887. get: function () {
  6888. return Engine._DELAYLOADSTATE_NONE;
  6889. },
  6890. enumerable: true,
  6891. configurable: true
  6892. });
  6893. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  6894. get: function () {
  6895. return Engine._DELAYLOADSTATE_LOADED;
  6896. },
  6897. enumerable: true,
  6898. configurable: true
  6899. });
  6900. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  6901. get: function () {
  6902. return Engine._DELAYLOADSTATE_LOADING;
  6903. },
  6904. enumerable: true,
  6905. configurable: true
  6906. });
  6907. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  6908. get: function () {
  6909. return Engine._DELAYLOADSTATE_NOTLOADED;
  6910. },
  6911. enumerable: true,
  6912. configurable: true
  6913. });
  6914. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  6915. get: function () {
  6916. return Engine._TEXTUREFORMAT_ALPHA;
  6917. },
  6918. enumerable: true,
  6919. configurable: true
  6920. });
  6921. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  6922. get: function () {
  6923. return Engine._TEXTUREFORMAT_LUMINANCE;
  6924. },
  6925. enumerable: true,
  6926. configurable: true
  6927. });
  6928. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  6929. get: function () {
  6930. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  6931. },
  6932. enumerable: true,
  6933. configurable: true
  6934. });
  6935. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  6936. get: function () {
  6937. return Engine._TEXTUREFORMAT_RGB;
  6938. },
  6939. enumerable: true,
  6940. configurable: true
  6941. });
  6942. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  6943. get: function () {
  6944. return Engine._TEXTUREFORMAT_RGBA;
  6945. },
  6946. enumerable: true,
  6947. configurable: true
  6948. });
  6949. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  6950. get: function () {
  6951. return Engine._TEXTURETYPE_UNSIGNED_INT;
  6952. },
  6953. enumerable: true,
  6954. configurable: true
  6955. });
  6956. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  6957. get: function () {
  6958. return Engine._TEXTURETYPE_FLOAT;
  6959. },
  6960. enumerable: true,
  6961. configurable: true
  6962. });
  6963. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  6964. get: function () {
  6965. return Engine._TEXTURETYPE_HALF_FLOAT;
  6966. },
  6967. enumerable: true,
  6968. configurable: true
  6969. });
  6970. Object.defineProperty(Engine, "Version", {
  6971. get: function () {
  6972. return "2.6-alpha";
  6973. },
  6974. enumerable: true,
  6975. configurable: true
  6976. });
  6977. Object.defineProperty(Engine.prototype, "texturesSupported", {
  6978. get: function () {
  6979. return this._texturesSupported;
  6980. },
  6981. enumerable: true,
  6982. configurable: true
  6983. });
  6984. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  6985. get: function () {
  6986. return this._textureFormatInUse;
  6987. },
  6988. enumerable: true,
  6989. configurable: true
  6990. });
  6991. Object.defineProperty(Engine.prototype, "webGLVersion", {
  6992. get: function () {
  6993. return this._webGLVersion;
  6994. },
  6995. enumerable: true,
  6996. configurable: true
  6997. });
  6998. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  6999. /**
  7000. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  7001. */
  7002. get: function () {
  7003. return this._isStencilEnable;
  7004. },
  7005. enumerable: true,
  7006. configurable: true
  7007. });
  7008. Engine.prototype._prepareWorkingCanvas = function () {
  7009. if (this._workingCanvas) {
  7010. return;
  7011. }
  7012. this._workingCanvas = document.createElement("canvas");
  7013. this._workingContext = this._workingCanvas.getContext("2d");
  7014. };
  7015. Engine.prototype.resetTextureCache = function () {
  7016. for (var index = 0; index < this._maxTextureChannels; index++) {
  7017. this._activeTexturesCache[index] = null;
  7018. }
  7019. };
  7020. Engine.prototype.getGlInfo = function () {
  7021. return {
  7022. vendor: this._glVendor,
  7023. renderer: this._glRenderer,
  7024. version: this._glVersion
  7025. };
  7026. };
  7027. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  7028. if (useScreen === void 0) { useScreen = false; }
  7029. var viewport = camera.viewport;
  7030. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  7031. };
  7032. Engine.prototype.getRenderWidth = function (useScreen) {
  7033. if (useScreen === void 0) { useScreen = false; }
  7034. if (!useScreen && this._currentRenderTarget) {
  7035. return this._currentRenderTarget._width;
  7036. }
  7037. return this._renderingCanvas.width;
  7038. };
  7039. Engine.prototype.getRenderHeight = function (useScreen) {
  7040. if (useScreen === void 0) { useScreen = false; }
  7041. if (!useScreen && this._currentRenderTarget) {
  7042. return this._currentRenderTarget._height;
  7043. }
  7044. return this._renderingCanvas.height;
  7045. };
  7046. Engine.prototype.getRenderingCanvas = function () {
  7047. return this._renderingCanvas;
  7048. };
  7049. Engine.prototype.getRenderingCanvasClientRect = function () {
  7050. return this._renderingCanvas.getBoundingClientRect();
  7051. };
  7052. Engine.prototype.setHardwareScalingLevel = function (level) {
  7053. this._hardwareScalingLevel = level;
  7054. this.resize();
  7055. };
  7056. Engine.prototype.getHardwareScalingLevel = function () {
  7057. return this._hardwareScalingLevel;
  7058. };
  7059. Engine.prototype.getLoadedTexturesCache = function () {
  7060. return this._loadedTexturesCache;
  7061. };
  7062. Engine.prototype.getCaps = function () {
  7063. return this._caps;
  7064. };
  7065. Object.defineProperty(Engine.prototype, "drawCalls", {
  7066. get: function () {
  7067. return this._drawCalls.current;
  7068. },
  7069. enumerable: true,
  7070. configurable: true
  7071. });
  7072. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  7073. get: function () {
  7074. return this._drawCalls;
  7075. },
  7076. enumerable: true,
  7077. configurable: true
  7078. });
  7079. Engine.prototype.getDepthFunction = function () {
  7080. return this._depthCullingState.depthFunc;
  7081. };
  7082. Engine.prototype.setDepthFunction = function (depthFunc) {
  7083. this._depthCullingState.depthFunc = depthFunc;
  7084. };
  7085. Engine.prototype.setDepthFunctionToGreater = function () {
  7086. this._depthCullingState.depthFunc = this._gl.GREATER;
  7087. };
  7088. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  7089. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  7090. };
  7091. Engine.prototype.setDepthFunctionToLess = function () {
  7092. this._depthCullingState.depthFunc = this._gl.LESS;
  7093. };
  7094. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  7095. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  7096. };
  7097. Engine.prototype.getStencilBuffer = function () {
  7098. return this._stencilState.stencilTest;
  7099. };
  7100. Engine.prototype.setStencilBuffer = function (enable) {
  7101. this._stencilState.stencilTest = enable;
  7102. };
  7103. Engine.prototype.getStencilMask = function () {
  7104. return this._stencilState.stencilMask;
  7105. };
  7106. Engine.prototype.setStencilMask = function (mask) {
  7107. this._stencilState.stencilMask = mask;
  7108. };
  7109. Engine.prototype.getStencilFunction = function () {
  7110. return this._stencilState.stencilFunc;
  7111. };
  7112. Engine.prototype.getStencilFunctionReference = function () {
  7113. return this._stencilState.stencilFuncRef;
  7114. };
  7115. Engine.prototype.getStencilFunctionMask = function () {
  7116. return this._stencilState.stencilFuncMask;
  7117. };
  7118. Engine.prototype.setStencilFunction = function (stencilFunc) {
  7119. this._stencilState.stencilFunc = stencilFunc;
  7120. };
  7121. Engine.prototype.setStencilFunctionReference = function (reference) {
  7122. this._stencilState.stencilFuncRef = reference;
  7123. };
  7124. Engine.prototype.setStencilFunctionMask = function (mask) {
  7125. this._stencilState.stencilFuncMask = mask;
  7126. };
  7127. Engine.prototype.getStencilOperationFail = function () {
  7128. return this._stencilState.stencilOpStencilFail;
  7129. };
  7130. Engine.prototype.getStencilOperationDepthFail = function () {
  7131. return this._stencilState.stencilOpDepthFail;
  7132. };
  7133. Engine.prototype.getStencilOperationPass = function () {
  7134. return this._stencilState.stencilOpStencilDepthPass;
  7135. };
  7136. Engine.prototype.setStencilOperationFail = function (operation) {
  7137. this._stencilState.stencilOpStencilFail = operation;
  7138. };
  7139. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  7140. this._stencilState.stencilOpDepthFail = operation;
  7141. };
  7142. Engine.prototype.setStencilOperationPass = function (operation) {
  7143. this._stencilState.stencilOpStencilDepthPass = operation;
  7144. };
  7145. /**
  7146. * stop executing a render loop function and remove it from the execution array
  7147. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  7148. */
  7149. Engine.prototype.stopRenderLoop = function (renderFunction) {
  7150. if (!renderFunction) {
  7151. this._activeRenderLoops = [];
  7152. return;
  7153. }
  7154. var index = this._activeRenderLoops.indexOf(renderFunction);
  7155. if (index >= 0) {
  7156. this._activeRenderLoops.splice(index, 1);
  7157. }
  7158. };
  7159. Engine.prototype._renderLoop = function () {
  7160. var shouldRender = true;
  7161. if (!this.renderEvenInBackground && this._windowIsBackground) {
  7162. shouldRender = false;
  7163. }
  7164. if (shouldRender) {
  7165. // Start new frame
  7166. this.beginFrame();
  7167. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  7168. var renderFunction = this._activeRenderLoops[index];
  7169. renderFunction();
  7170. }
  7171. // Present
  7172. this.endFrame();
  7173. }
  7174. if (this._activeRenderLoops.length > 0) {
  7175. // Register new frame
  7176. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  7177. }
  7178. else {
  7179. this._renderingQueueLaunched = false;
  7180. }
  7181. };
  7182. /**
  7183. * Register and execute a render loop. The engine can have more than one render function.
  7184. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  7185. * @example
  7186. * engine.runRenderLoop(function () {
  7187. * scene.render()
  7188. * })
  7189. */
  7190. Engine.prototype.runRenderLoop = function (renderFunction) {
  7191. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  7192. return;
  7193. }
  7194. this._activeRenderLoops.push(renderFunction);
  7195. if (!this._renderingQueueLaunched) {
  7196. this._renderingQueueLaunched = true;
  7197. this._bindedRenderFunction = this._renderLoop.bind(this);
  7198. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  7199. }
  7200. };
  7201. /**
  7202. * Toggle full screen mode.
  7203. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  7204. * @param {any} options - an options object to be sent to the requestFullscreen function
  7205. */
  7206. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  7207. if (this.isFullscreen) {
  7208. BABYLON.Tools.ExitFullscreen();
  7209. }
  7210. else {
  7211. this._pointerLockRequested = requestPointerLock;
  7212. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  7213. }
  7214. };
  7215. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  7216. if (stencil === void 0) { stencil = false; }
  7217. this.applyStates();
  7218. var mode = 0;
  7219. if (backBuffer && color) {
  7220. this._gl.clearColor(color.r, color.g, color.b, color.a);
  7221. mode |= this._gl.COLOR_BUFFER_BIT;
  7222. }
  7223. if (depth) {
  7224. this._gl.clearDepth(1.0);
  7225. mode |= this._gl.DEPTH_BUFFER_BIT;
  7226. }
  7227. if (stencil) {
  7228. this._gl.clearStencil(0);
  7229. mode |= this._gl.STENCIL_BUFFER_BIT;
  7230. }
  7231. this._gl.clear(mode);
  7232. };
  7233. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  7234. var gl = this._gl;
  7235. // Save state
  7236. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  7237. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  7238. // Change state
  7239. gl.enable(gl.SCISSOR_TEST);
  7240. gl.scissor(x, y, width, height);
  7241. // Clear
  7242. this.clear(clearColor, true, true, true);
  7243. // Restore state
  7244. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  7245. if (curScissor === true) {
  7246. gl.enable(gl.SCISSOR_TEST);
  7247. }
  7248. else {
  7249. gl.disable(gl.SCISSOR_TEST);
  7250. }
  7251. };
  7252. /**
  7253. * Set the WebGL's viewport
  7254. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  7255. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  7256. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  7257. */
  7258. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  7259. var width = requiredWidth || (navigator.isCocoonJS ? window.innerWidth : this.getRenderWidth());
  7260. var height = requiredHeight || (navigator.isCocoonJS ? window.innerHeight : this.getRenderHeight());
  7261. var x = viewport.x || 0;
  7262. var y = viewport.y || 0;
  7263. this._cachedViewport = viewport;
  7264. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  7265. };
  7266. /**
  7267. * Directly set the WebGL Viewport
  7268. * The x, y, width & height are directly passed to the WebGL call
  7269. * @return the current viewport Object (if any) that is being replaced by this call. You can restore this viewport later on to go back to the original state.
  7270. */
  7271. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  7272. var currentViewport = this._cachedViewport;
  7273. this._cachedViewport = null;
  7274. this._gl.viewport(x, y, width, height);
  7275. return currentViewport;
  7276. };
  7277. Engine.prototype.beginFrame = function () {
  7278. this._measureFps();
  7279. };
  7280. Engine.prototype.endFrame = function () {
  7281. //force a flush in case we are using a bad OS.
  7282. if (this._badOS) {
  7283. this.flushFramebuffer();
  7284. }
  7285. //submit frame to the vr device, if enabled
  7286. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  7287. this._vrDisplayEnabled.submitFrame();
  7288. }
  7289. };
  7290. /**
  7291. * resize the view according to the canvas' size.
  7292. * @example
  7293. * window.addEventListener("resize", function () {
  7294. * engine.resize();
  7295. * });
  7296. */
  7297. Engine.prototype.resize = function () {
  7298. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  7299. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  7300. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  7301. };
  7302. /**
  7303. * force a specific size of the canvas
  7304. * @param {number} width - the new canvas' width
  7305. * @param {number} height - the new canvas' height
  7306. */
  7307. Engine.prototype.setSize = function (width, height) {
  7308. this._renderingCanvas.width = width;
  7309. this._renderingCanvas.height = height;
  7310. for (var index = 0; index < this.scenes.length; index++) {
  7311. var scene = this.scenes[index];
  7312. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  7313. var cam = scene.cameras[camIndex];
  7314. cam._currentRenderId = 0;
  7315. }
  7316. }
  7317. };
  7318. //WebVR functions
  7319. Engine.prototype.initWebVR = function () {
  7320. if (!this.vrDisplaysPromise) {
  7321. this._getVRDisplays();
  7322. }
  7323. };
  7324. Engine.prototype.enableVR = function (vrDevice) {
  7325. this._vrDisplayEnabled = vrDevice;
  7326. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  7327. };
  7328. Engine.prototype.disableVR = function () {
  7329. if (this._vrDisplayEnabled) {
  7330. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  7331. }
  7332. };
  7333. Engine.prototype._getVRDisplays = function () {
  7334. var _this = this;
  7335. var getWebVRDevices = function (devices) {
  7336. var size = devices.length;
  7337. var i = 0;
  7338. _this._vrDisplays = devices.filter(function (device) {
  7339. return devices[i] instanceof VRDisplay;
  7340. });
  7341. return _this._vrDisplays;
  7342. };
  7343. //using a key due to typescript
  7344. if (navigator.getVRDisplays) {
  7345. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  7346. }
  7347. };
  7348. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight) {
  7349. this._currentRenderTarget = texture;
  7350. this.bindUnboundFramebuffer(texture._framebuffer);
  7351. var gl = this._gl;
  7352. if (texture.isCube) {
  7353. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture, 0);
  7354. }
  7355. gl.viewport(0, 0, requiredWidth || texture._width, requiredHeight || texture._height);
  7356. this.wipeCaches();
  7357. };
  7358. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  7359. if (this._currentFramebuffer !== framebuffer) {
  7360. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  7361. this._currentFramebuffer = framebuffer;
  7362. }
  7363. };
  7364. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps) {
  7365. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  7366. this._currentRenderTarget = null;
  7367. if (texture.generateMipMaps && !disableGenerateMipMaps) {
  7368. var gl = this._gl;
  7369. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7370. gl.generateMipmap(gl.TEXTURE_2D);
  7371. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7372. }
  7373. this.bindUnboundFramebuffer(null);
  7374. };
  7375. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  7376. if (texture.generateMipMaps) {
  7377. var gl = this._gl;
  7378. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  7379. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  7380. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  7381. }
  7382. };
  7383. Engine.prototype.flushFramebuffer = function () {
  7384. this._gl.flush();
  7385. };
  7386. Engine.prototype.restoreDefaultFramebuffer = function () {
  7387. this._currentRenderTarget = null;
  7388. this.bindUnboundFramebuffer(null);
  7389. this.setViewport(this._cachedViewport);
  7390. this.wipeCaches();
  7391. };
  7392. // VBOs
  7393. Engine.prototype._resetVertexBufferBinding = function () {
  7394. this.bindArrayBuffer(null);
  7395. this._cachedVertexBuffers = null;
  7396. };
  7397. Engine.prototype.createVertexBuffer = function (vertices) {
  7398. var vbo = this._gl.createBuffer();
  7399. this.bindArrayBuffer(vbo);
  7400. if (vertices instanceof Float32Array) {
  7401. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  7402. }
  7403. else {
  7404. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  7405. }
  7406. this._resetVertexBufferBinding();
  7407. vbo.references = 1;
  7408. return vbo;
  7409. };
  7410. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  7411. var vbo = this._gl.createBuffer();
  7412. this.bindArrayBuffer(vbo);
  7413. if (vertices instanceof Float32Array) {
  7414. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  7415. }
  7416. else {
  7417. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  7418. }
  7419. this._resetVertexBufferBinding();
  7420. vbo.references = 1;
  7421. return vbo;
  7422. };
  7423. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  7424. this.bindArrayBuffer(vertexBuffer);
  7425. if (offset === undefined) {
  7426. offset = 0;
  7427. }
  7428. if (count === undefined) {
  7429. if (vertices instanceof Float32Array) {
  7430. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  7431. }
  7432. else {
  7433. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  7434. }
  7435. }
  7436. else {
  7437. if (vertices instanceof Float32Array) {
  7438. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  7439. }
  7440. else {
  7441. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  7442. }
  7443. }
  7444. this._resetVertexBufferBinding();
  7445. };
  7446. Engine.prototype._resetIndexBufferBinding = function () {
  7447. this.bindIndexBuffer(null);
  7448. this._cachedIndexBuffer = null;
  7449. };
  7450. Engine.prototype.createIndexBuffer = function (indices) {
  7451. var vbo = this._gl.createBuffer();
  7452. this.bindIndexBuffer(vbo);
  7453. // Check for 32 bits indices
  7454. var arrayBuffer;
  7455. var need32Bits = false;
  7456. if (this._caps.uintIndices) {
  7457. for (var index = 0; index < indices.length; index++) {
  7458. if (indices[index] > 65535) {
  7459. need32Bits = true;
  7460. break;
  7461. }
  7462. }
  7463. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  7464. }
  7465. else {
  7466. arrayBuffer = new Uint16Array(indices);
  7467. }
  7468. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  7469. this._resetIndexBufferBinding();
  7470. vbo.references = 1;
  7471. vbo.is32Bits = need32Bits;
  7472. return vbo;
  7473. };
  7474. Engine.prototype.bindArrayBuffer = function (buffer) {
  7475. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  7476. };
  7477. Engine.prototype.bindIndexBuffer = function (buffer) {
  7478. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  7479. };
  7480. Engine.prototype.bindBuffer = function (buffer, target) {
  7481. if (this._currentBoundBuffer[target] !== buffer) {
  7482. this._gl.bindBuffer(target, buffer);
  7483. this._currentBoundBuffer[target] = buffer;
  7484. }
  7485. };
  7486. Engine.prototype.updateArrayBuffer = function (data) {
  7487. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7488. };
  7489. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  7490. var pointer = this._currentBufferPointers[indx];
  7491. var changed = false;
  7492. if (!pointer) {
  7493. changed = true;
  7494. this._currentBufferPointers[indx] = { indx: indx, size: size, type: type, normalized: normalized, stride: stride, offset: offset, buffer: buffer };
  7495. }
  7496. else {
  7497. if (pointer.buffer !== buffer) {
  7498. pointer.buffer = buffer;
  7499. changed = true;
  7500. }
  7501. if (pointer.size !== size) {
  7502. pointer.size = size;
  7503. changed = true;
  7504. }
  7505. if (pointer.type !== type) {
  7506. pointer.type = type;
  7507. changed = true;
  7508. }
  7509. if (pointer.normalized !== normalized) {
  7510. pointer.normalized = normalized;
  7511. changed = true;
  7512. }
  7513. if (pointer.stride !== stride) {
  7514. pointer.stride = stride;
  7515. changed = true;
  7516. }
  7517. if (pointer.offset !== offset) {
  7518. pointer.offset = offset;
  7519. changed = true;
  7520. }
  7521. }
  7522. if (changed) {
  7523. this.bindArrayBuffer(buffer);
  7524. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  7525. }
  7526. };
  7527. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  7528. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  7529. this._cachedVertexBuffers = vertexBuffer;
  7530. this._cachedEffectForVertexBuffers = effect;
  7531. var attributesCount = effect.getAttributesCount();
  7532. this.unbindAllAttributes();
  7533. var offset = 0;
  7534. for (var index = 0; index < attributesCount; index++) {
  7535. if (index < vertexDeclaration.length) {
  7536. var order = effect.getAttributeLocation(index);
  7537. if (order >= 0) {
  7538. this._gl.enableVertexAttribArray(order);
  7539. this._vertexAttribArraysEnabled[order] = true;
  7540. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  7541. }
  7542. offset += vertexDeclaration[index] * 4;
  7543. }
  7544. }
  7545. }
  7546. if (this._cachedIndexBuffer !== indexBuffer) {
  7547. this._cachedIndexBuffer = indexBuffer;
  7548. this.bindIndexBuffer(indexBuffer);
  7549. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7550. }
  7551. };
  7552. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  7553. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  7554. this._cachedVertexBuffers = vertexBuffers;
  7555. this._cachedEffectForVertexBuffers = effect;
  7556. var attributes = effect.getAttributesNames();
  7557. this.unbindAllAttributes();
  7558. for (var index = 0; index < attributes.length; index++) {
  7559. var order = effect.getAttributeLocation(index);
  7560. if (order >= 0) {
  7561. var vertexBuffer = vertexBuffers[attributes[index]];
  7562. if (!vertexBuffer) {
  7563. continue;
  7564. }
  7565. this._gl.enableVertexAttribArray(order);
  7566. this._vertexAttribArraysEnabled[order] = true;
  7567. var buffer = vertexBuffer.getBuffer();
  7568. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  7569. if (vertexBuffer.getIsInstanced()) {
  7570. this._caps.instancedArrays.vertexAttribDivisorANGLE(order, 1);
  7571. this._currentInstanceLocations.push(order);
  7572. this._currentInstanceBuffers.push(buffer);
  7573. }
  7574. }
  7575. }
  7576. }
  7577. if (indexBuffer != null && this._cachedIndexBuffer !== indexBuffer) {
  7578. this._cachedIndexBuffer = indexBuffer;
  7579. this.bindIndexBuffer(indexBuffer);
  7580. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  7581. }
  7582. };
  7583. Engine.prototype.unbindInstanceAttributes = function () {
  7584. var boundBuffer;
  7585. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  7586. var instancesBuffer = this._currentInstanceBuffers[i];
  7587. if (boundBuffer != instancesBuffer) {
  7588. boundBuffer = instancesBuffer;
  7589. this.bindArrayBuffer(instancesBuffer);
  7590. }
  7591. var offsetLocation = this._currentInstanceLocations[i];
  7592. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 0);
  7593. }
  7594. this._currentInstanceBuffers.length = 0;
  7595. this._currentInstanceLocations.length = 0;
  7596. };
  7597. Engine.prototype._releaseBuffer = function (buffer) {
  7598. buffer.references--;
  7599. if (buffer.references === 0) {
  7600. this._gl.deleteBuffer(buffer);
  7601. return true;
  7602. }
  7603. return false;
  7604. };
  7605. Engine.prototype.createInstancesBuffer = function (capacity) {
  7606. var buffer = this._gl.createBuffer();
  7607. buffer.capacity = capacity;
  7608. this.bindArrayBuffer(buffer);
  7609. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  7610. return buffer;
  7611. };
  7612. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  7613. this._gl.deleteBuffer(buffer);
  7614. };
  7615. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  7616. this.bindArrayBuffer(instancesBuffer);
  7617. if (data) {
  7618. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  7619. }
  7620. if (offsetLocations[0].index !== undefined) {
  7621. var stride = 0;
  7622. for (var i = 0; i < offsetLocations.length; i++) {
  7623. var ai = offsetLocations[i];
  7624. stride += ai.attributeSize * 4;
  7625. }
  7626. for (var i = 0; i < offsetLocations.length; i++) {
  7627. var ai = offsetLocations[i];
  7628. if (!this._vertexAttribArraysEnabled[ai.index]) {
  7629. this._gl.enableVertexAttribArray(ai.index);
  7630. this._vertexAttribArraysEnabled[ai.index] = true;
  7631. }
  7632. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  7633. this._caps.instancedArrays.vertexAttribDivisorANGLE(ai.index, 1);
  7634. this._currentInstanceLocations.push(ai.index);
  7635. this._currentInstanceBuffers.push(instancesBuffer);
  7636. }
  7637. }
  7638. else {
  7639. for (var index = 0; index < 4; index++) {
  7640. var offsetLocation = offsetLocations[index];
  7641. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  7642. this._gl.enableVertexAttribArray(offsetLocation);
  7643. this._vertexAttribArraysEnabled[offsetLocation] = true;
  7644. }
  7645. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  7646. this._caps.instancedArrays.vertexAttribDivisorANGLE(offsetLocation, 1);
  7647. this._currentInstanceLocations.push(offsetLocation);
  7648. this._currentInstanceBuffers.push(instancesBuffer);
  7649. }
  7650. }
  7651. };
  7652. Engine.prototype.applyStates = function () {
  7653. this._depthCullingState.apply(this._gl);
  7654. this._stencilState.apply(this._gl);
  7655. this._alphaState.apply(this._gl);
  7656. };
  7657. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  7658. // Apply states
  7659. this.applyStates();
  7660. this._drawCalls.addCount(1, false);
  7661. // Render
  7662. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  7663. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  7664. if (instancesCount) {
  7665. this._caps.instancedArrays.drawElementsInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  7666. return;
  7667. }
  7668. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  7669. };
  7670. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  7671. // Apply states
  7672. this.applyStates();
  7673. this._drawCalls.addCount(1, false);
  7674. if (instancesCount) {
  7675. this._caps.instancedArrays.drawArraysInstancedANGLE(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  7676. return;
  7677. }
  7678. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  7679. };
  7680. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  7681. // Apply states
  7682. this.applyStates();
  7683. this._drawCalls.addCount(1, false);
  7684. if (instancesCount) {
  7685. this._caps.instancedArrays.drawArraysInstancedANGLE(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  7686. return;
  7687. }
  7688. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  7689. };
  7690. // Shaders
  7691. Engine.prototype._releaseEffect = function (effect) {
  7692. if (this._compiledEffects[effect._key]) {
  7693. delete this._compiledEffects[effect._key];
  7694. if (effect.getProgram()) {
  7695. this._gl.deleteProgram(effect.getProgram());
  7696. }
  7697. }
  7698. };
  7699. Engine.prototype.createEffect = function (baseName, attributesNames, uniformsNames, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  7700. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  7701. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  7702. var name = vertex + "+" + fragment + "@" + defines;
  7703. if (this._compiledEffects[name]) {
  7704. return this._compiledEffects[name];
  7705. }
  7706. var effect = new BABYLON.Effect(baseName, attributesNames, uniformsNames, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  7707. effect._key = name;
  7708. this._compiledEffects[name] = effect;
  7709. return effect;
  7710. };
  7711. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  7712. if (uniformsNames === void 0) { uniformsNames = []; }
  7713. if (samplers === void 0) { samplers = []; }
  7714. if (defines === void 0) { defines = ""; }
  7715. return this.createEffect({
  7716. vertex: "particles",
  7717. fragmentElement: fragmentName
  7718. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  7719. };
  7720. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  7721. context = context || this._gl;
  7722. var vertexShader = compileShader(context, vertexCode, "vertex", defines);
  7723. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines);
  7724. var shaderProgram = context.createProgram();
  7725. context.attachShader(shaderProgram, vertexShader);
  7726. context.attachShader(shaderProgram, fragmentShader);
  7727. context.linkProgram(shaderProgram);
  7728. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  7729. if (!linked) {
  7730. var error = context.getProgramInfoLog(shaderProgram);
  7731. if (error) {
  7732. throw new Error(error);
  7733. }
  7734. }
  7735. context.deleteShader(vertexShader);
  7736. context.deleteShader(fragmentShader);
  7737. return shaderProgram;
  7738. };
  7739. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  7740. var results = [];
  7741. for (var index = 0; index < uniformsNames.length; index++) {
  7742. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  7743. }
  7744. return results;
  7745. };
  7746. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  7747. var results = [];
  7748. for (var index = 0; index < attributesNames.length; index++) {
  7749. try {
  7750. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  7751. }
  7752. catch (e) {
  7753. results.push(-1);
  7754. }
  7755. }
  7756. return results;
  7757. };
  7758. Engine.prototype.enableEffect = function (effect) {
  7759. //if (!effect || !effect.getAttributesCount() || this._currentEffect === effect) {
  7760. // if (effect && effect.onBind) {
  7761. // effect.onBind(effect);
  7762. // }
  7763. // return;
  7764. //}
  7765. // Use program
  7766. this.setProgram(effect.getProgram());
  7767. this._currentEffect = effect;
  7768. if (effect.onBind) {
  7769. effect.onBind(effect);
  7770. }
  7771. };
  7772. Engine.prototype.setIntArray = function (uniform, array) {
  7773. if (!uniform)
  7774. return;
  7775. this._gl.uniform1iv(uniform, array);
  7776. };
  7777. Engine.prototype.setIntArray2 = function (uniform, array) {
  7778. if (!uniform || array.length % 2 !== 0)
  7779. return;
  7780. this._gl.uniform2iv(uniform, array);
  7781. };
  7782. Engine.prototype.setIntArray3 = function (uniform, array) {
  7783. if (!uniform || array.length % 3 !== 0)
  7784. return;
  7785. this._gl.uniform3iv(uniform, array);
  7786. };
  7787. Engine.prototype.setIntArray4 = function (uniform, array) {
  7788. if (!uniform || array.length % 4 !== 0)
  7789. return;
  7790. this._gl.uniform4iv(uniform, array);
  7791. };
  7792. Engine.prototype.setFloatArray = function (uniform, array) {
  7793. if (!uniform)
  7794. return;
  7795. this._gl.uniform1fv(uniform, array);
  7796. };
  7797. Engine.prototype.setFloatArray2 = function (uniform, array) {
  7798. if (!uniform || array.length % 2 !== 0)
  7799. return;
  7800. this._gl.uniform2fv(uniform, array);
  7801. };
  7802. Engine.prototype.setFloatArray3 = function (uniform, array) {
  7803. if (!uniform || array.length % 3 !== 0)
  7804. return;
  7805. this._gl.uniform3fv(uniform, array);
  7806. };
  7807. Engine.prototype.setFloatArray4 = function (uniform, array) {
  7808. if (!uniform || array.length % 4 !== 0)
  7809. return;
  7810. this._gl.uniform4fv(uniform, array);
  7811. };
  7812. Engine.prototype.setArray = function (uniform, array) {
  7813. if (!uniform)
  7814. return;
  7815. this._gl.uniform1fv(uniform, array);
  7816. };
  7817. Engine.prototype.setArray2 = function (uniform, array) {
  7818. if (!uniform || array.length % 2 !== 0)
  7819. return;
  7820. this._gl.uniform2fv(uniform, array);
  7821. };
  7822. Engine.prototype.setArray3 = function (uniform, array) {
  7823. if (!uniform || array.length % 3 !== 0)
  7824. return;
  7825. this._gl.uniform3fv(uniform, array);
  7826. };
  7827. Engine.prototype.setArray4 = function (uniform, array) {
  7828. if (!uniform || array.length % 4 !== 0)
  7829. return;
  7830. this._gl.uniform4fv(uniform, array);
  7831. };
  7832. Engine.prototype.setMatrices = function (uniform, matrices) {
  7833. if (!uniform)
  7834. return;
  7835. this._gl.uniformMatrix4fv(uniform, false, matrices);
  7836. };
  7837. Engine.prototype.setMatrix = function (uniform, matrix) {
  7838. if (!uniform)
  7839. return;
  7840. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  7841. };
  7842. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  7843. if (!uniform)
  7844. return;
  7845. this._gl.uniformMatrix3fv(uniform, false, matrix);
  7846. };
  7847. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  7848. if (!uniform)
  7849. return;
  7850. this._gl.uniformMatrix2fv(uniform, false, matrix);
  7851. };
  7852. Engine.prototype.setFloat = function (uniform, value) {
  7853. if (!uniform)
  7854. return;
  7855. this._gl.uniform1f(uniform, value);
  7856. };
  7857. Engine.prototype.setFloat2 = function (uniform, x, y) {
  7858. if (!uniform)
  7859. return;
  7860. this._gl.uniform2f(uniform, x, y);
  7861. };
  7862. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  7863. if (!uniform)
  7864. return;
  7865. this._gl.uniform3f(uniform, x, y, z);
  7866. };
  7867. Engine.prototype.setBool = function (uniform, bool) {
  7868. if (!uniform)
  7869. return;
  7870. this._gl.uniform1i(uniform, bool);
  7871. };
  7872. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  7873. if (!uniform)
  7874. return;
  7875. this._gl.uniform4f(uniform, x, y, z, w);
  7876. };
  7877. Engine.prototype.setColor3 = function (uniform, color3) {
  7878. if (!uniform)
  7879. return;
  7880. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  7881. };
  7882. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  7883. if (!uniform)
  7884. return;
  7885. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  7886. };
  7887. // States
  7888. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  7889. if (zOffset === void 0) { zOffset = 0; }
  7890. if (reverseSide === void 0) { reverseSide = false; }
  7891. // Culling
  7892. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  7893. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  7894. var cullFace = this.cullBackFaces ? showSide : hideSide;
  7895. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  7896. if (culling) {
  7897. this._depthCullingState.cullFace = cullFace;
  7898. this._depthCullingState.cull = true;
  7899. }
  7900. else {
  7901. this._depthCullingState.cull = false;
  7902. }
  7903. }
  7904. // Z offset
  7905. this._depthCullingState.zOffset = zOffset;
  7906. };
  7907. Engine.prototype.setDepthBuffer = function (enable) {
  7908. this._depthCullingState.depthTest = enable;
  7909. };
  7910. Engine.prototype.getDepthWrite = function () {
  7911. return this._depthCullingState.depthMask;
  7912. };
  7913. Engine.prototype.setDepthWrite = function (enable) {
  7914. this._depthCullingState.depthMask = enable;
  7915. };
  7916. Engine.prototype.setColorWrite = function (enable) {
  7917. this._gl.colorMask(enable, enable, enable, enable);
  7918. };
  7919. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  7920. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  7921. if (this._alphaMode === mode) {
  7922. return;
  7923. }
  7924. switch (mode) {
  7925. case Engine.ALPHA_DISABLE:
  7926. this._alphaState.alphaBlend = false;
  7927. break;
  7928. case Engine.ALPHA_PREMULTIPLIED:
  7929. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  7930. this._alphaState.alphaBlend = true;
  7931. break;
  7932. case Engine.ALPHA_COMBINE:
  7933. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  7934. this._alphaState.alphaBlend = true;
  7935. break;
  7936. case Engine.ALPHA_ONEONE:
  7937. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7938. this._alphaState.alphaBlend = true;
  7939. break;
  7940. case Engine.ALPHA_ADD:
  7941. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  7942. this._alphaState.alphaBlend = true;
  7943. break;
  7944. case Engine.ALPHA_SUBTRACT:
  7945. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7946. this._alphaState.alphaBlend = true;
  7947. break;
  7948. case Engine.ALPHA_MULTIPLY:
  7949. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  7950. this._alphaState.alphaBlend = true;
  7951. break;
  7952. case Engine.ALPHA_MAXIMIZED:
  7953. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  7954. this._alphaState.alphaBlend = true;
  7955. break;
  7956. }
  7957. if (!noDepthWriteChange) {
  7958. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  7959. }
  7960. this._alphaMode = mode;
  7961. };
  7962. Engine.prototype.getAlphaMode = function () {
  7963. return this._alphaMode;
  7964. };
  7965. Engine.prototype.setAlphaTesting = function (enable) {
  7966. this._alphaTest = enable;
  7967. };
  7968. Engine.prototype.getAlphaTesting = function () {
  7969. return this._alphaTest;
  7970. };
  7971. // Textures
  7972. Engine.prototype.wipeCaches = function () {
  7973. this.resetTextureCache();
  7974. this._currentEffect = null;
  7975. this._stencilState.reset();
  7976. this._depthCullingState.reset();
  7977. this.setDepthFunctionToLessOrEqual();
  7978. this._alphaState.reset();
  7979. this._cachedVertexBuffers = null;
  7980. this._cachedIndexBuffer = null;
  7981. this._cachedEffectForVertexBuffers = null;
  7982. };
  7983. Engine.prototype.setSamplingMode = function (texture, samplingMode) {
  7984. var gl = this._gl;
  7985. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  7986. var magFilter = gl.NEAREST;
  7987. var minFilter = gl.NEAREST;
  7988. if (samplingMode === BABYLON.Texture.BILINEAR_SAMPLINGMODE) {
  7989. magFilter = gl.LINEAR;
  7990. minFilter = gl.LINEAR;
  7991. }
  7992. else if (samplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE) {
  7993. magFilter = gl.LINEAR;
  7994. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7995. }
  7996. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, magFilter);
  7997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, minFilter);
  7998. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  7999. texture.samplingMode = samplingMode;
  8000. };
  8001. /**
  8002. * Set the compressed texture format to use, based on the formats you have,
  8003. * the formats supported by the hardware / browser, and those currently implemented
  8004. * in BJS.
  8005. *
  8006. * Note: The result of this call is not taken into account texture is base64 or when
  8007. * using a database / manifest.
  8008. *
  8009. * @param {Array<string>} formatsAvailable - Extension names including dot. Case
  8010. * and order do not matter.
  8011. * @returns The extension selected.
  8012. */
  8013. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  8014. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  8015. // code to allow the formats to be added as they can be developed / hw tested
  8016. if (this._texturesSupported[i] === '.astc')
  8017. continue;
  8018. if (this._texturesSupported[i] === '.pvr')
  8019. continue;
  8020. if (this._texturesSupported[i] === '.etc1')
  8021. continue;
  8022. if (this._texturesSupported[i] === '.etc2')
  8023. continue;
  8024. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  8025. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  8026. return this._textureFormatInUse = this._texturesSupported[i];
  8027. }
  8028. }
  8029. }
  8030. // actively set format to nothing, to allow this to be called more than once
  8031. // and possibly fail the 2nd time
  8032. return this._textureFormatInUse = null;
  8033. };
  8034. Engine.prototype.createTexture = function (url, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer) {
  8035. var _this = this;
  8036. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  8037. if (onLoad === void 0) { onLoad = null; }
  8038. if (onError === void 0) { onError = null; }
  8039. if (buffer === void 0) { buffer = null; }
  8040. var texture = this._gl.createTexture();
  8041. var extension;
  8042. var fromData = false;
  8043. if (url.substr(0, 5) === "data:") {
  8044. fromData = true;
  8045. }
  8046. if (!fromData) {
  8047. var lastDot = url.lastIndexOf('.');
  8048. extension = url.substring(lastDot).toLowerCase();
  8049. if (this._textureFormatInUse && !fromData && !scene.database) {
  8050. extension = this._textureFormatInUse;
  8051. url = url.substring(0, lastDot) + this._textureFormatInUse;
  8052. }
  8053. }
  8054. else {
  8055. var oldUrl = url;
  8056. fromData = oldUrl.split(':');
  8057. url = oldUrl;
  8058. extension = fromData[1].substr(fromData[1].length - 4, 4).toLowerCase();
  8059. }
  8060. var isDDS = (extension === ".dds");
  8061. var isTGA = (extension === ".tga");
  8062. scene._addPendingData(texture);
  8063. texture.url = url;
  8064. texture.noMipmap = noMipmap;
  8065. texture.references = 1;
  8066. texture.samplingMode = samplingMode;
  8067. texture.onLoadedCallbacks = [onLoad];
  8068. this._loadedTexturesCache.push(texture);
  8069. var onerror = function () {
  8070. scene._removePendingData(texture);
  8071. if (onError) {
  8072. onError();
  8073. }
  8074. };
  8075. var callback;
  8076. if (isTGA) {
  8077. callback = function (arrayBuffer) {
  8078. var data = new Uint8Array(arrayBuffer);
  8079. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  8080. prepareWebGLTexture(texture, _this._gl, scene, header.width, header.height, invertY, noMipmap, false, function () {
  8081. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  8082. }, samplingMode);
  8083. };
  8084. if (!(fromData instanceof Array))
  8085. BABYLON.Tools.LoadFile(url, function (arrayBuffer) {
  8086. callback(arrayBuffer);
  8087. }, null, scene.database, true, onerror);
  8088. else
  8089. callback(buffer);
  8090. }
  8091. else if (isDDS) {
  8092. callback = function (data) {
  8093. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8094. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  8095. prepareWebGLTexture(texture, _this._gl, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  8096. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 1);
  8097. }, samplingMode);
  8098. };
  8099. if (!(fromData instanceof Array))
  8100. BABYLON.Tools.LoadFile(url, function (data) {
  8101. callback(data);
  8102. }, null, scene.database, true, onerror);
  8103. else
  8104. callback(buffer);
  8105. }
  8106. else {
  8107. var onload = function (img) {
  8108. prepareWebGLTexture(texture, _this._gl, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight) {
  8109. var isPot = (img.width === potWidth && img.height === potHeight);
  8110. if (!isPot) {
  8111. _this._prepareWorkingCanvas();
  8112. _this._workingCanvas.width = potWidth;
  8113. _this._workingCanvas.height = potHeight;
  8114. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8115. _this._workingContext.imageSmoothingEnabled = false;
  8116. _this._workingContext.mozImageSmoothingEnabled = false;
  8117. _this._workingContext.oImageSmoothingEnabled = false;
  8118. _this._workingContext.webkitImageSmoothingEnabled = false;
  8119. _this._workingContext.msImageSmoothingEnabled = false;
  8120. }
  8121. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  8122. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8123. _this._workingContext.imageSmoothingEnabled = true;
  8124. _this._workingContext.mozImageSmoothingEnabled = true;
  8125. _this._workingContext.oImageSmoothingEnabled = true;
  8126. _this._workingContext.webkitImageSmoothingEnabled = true;
  8127. _this._workingContext.msImageSmoothingEnabled = true;
  8128. }
  8129. }
  8130. _this._gl.texImage2D(_this._gl.TEXTURE_2D, 0, _this._gl.RGBA, _this._gl.RGBA, _this._gl.UNSIGNED_BYTE, isPot ? img : _this._workingCanvas);
  8131. }, samplingMode);
  8132. };
  8133. if (!(fromData instanceof Array))
  8134. BABYLON.Tools.LoadImage(url, onload, onerror, scene.database);
  8135. else
  8136. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene.database);
  8137. }
  8138. return texture;
  8139. };
  8140. Engine.prototype._getInternalFormat = function (format) {
  8141. var internalFormat = this._gl.RGBA;
  8142. switch (format) {
  8143. case Engine.TEXTUREFORMAT_ALPHA:
  8144. internalFormat = this._gl.ALPHA;
  8145. break;
  8146. case Engine.TEXTUREFORMAT_LUMINANCE:
  8147. internalFormat = this._gl.LUMINANCE;
  8148. break;
  8149. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  8150. internalFormat = this._gl.LUMINANCE_ALPHA;
  8151. break;
  8152. case Engine.TEXTUREFORMAT_RGB:
  8153. internalFormat = this._gl.RGB;
  8154. break;
  8155. case Engine.TEXTUREFORMAT_RGBA:
  8156. internalFormat = this._gl.RGBA;
  8157. break;
  8158. }
  8159. return internalFormat;
  8160. };
  8161. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  8162. if (compression === void 0) { compression = null; }
  8163. var internalFormat = this._getInternalFormat(format);
  8164. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8165. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  8166. if (texture._width % 4 !== 0) {
  8167. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  8168. }
  8169. if (compression) {
  8170. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture._width, texture._height, 0, data);
  8171. }
  8172. else {
  8173. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture._width, texture._height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  8174. }
  8175. if (texture.generateMipMaps) {
  8176. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8177. }
  8178. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8179. this.resetTextureCache();
  8180. texture.isReady = true;
  8181. };
  8182. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  8183. if (compression === void 0) { compression = null; }
  8184. var texture = this._gl.createTexture();
  8185. texture._baseWidth = width;
  8186. texture._baseHeight = height;
  8187. texture._width = width;
  8188. texture._height = height;
  8189. texture.references = 1;
  8190. this.updateRawTexture(texture, data, format, invertY, compression);
  8191. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8192. // Filters
  8193. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  8194. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8195. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8196. if (generateMipMaps) {
  8197. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8198. }
  8199. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8200. texture.samplingMode = samplingMode;
  8201. this._loadedTexturesCache.push(texture);
  8202. return texture;
  8203. };
  8204. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  8205. var texture = this._gl.createTexture();
  8206. texture._baseWidth = width;
  8207. texture._baseHeight = height;
  8208. if (generateMipMaps) {
  8209. width = BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize);
  8210. height = BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize);
  8211. }
  8212. this.resetTextureCache();
  8213. texture._width = width;
  8214. texture._height = height;
  8215. texture.isReady = false;
  8216. texture.generateMipMaps = generateMipMaps;
  8217. texture.references = 1;
  8218. texture.samplingMode = samplingMode;
  8219. this.updateTextureSamplingMode(samplingMode, texture);
  8220. this._loadedTexturesCache.push(texture);
  8221. return texture;
  8222. };
  8223. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  8224. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  8225. if (texture.isCube) {
  8226. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  8227. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8228. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8229. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8230. }
  8231. else {
  8232. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8233. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  8234. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  8235. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8236. }
  8237. };
  8238. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha) {
  8239. if (premulAlpha === void 0) { premulAlpha = false; }
  8240. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8241. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  8242. if (premulAlpha) {
  8243. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  8244. }
  8245. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, canvas);
  8246. if (texture.generateMipMaps) {
  8247. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8248. }
  8249. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8250. if (premulAlpha) {
  8251. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  8252. }
  8253. this.resetTextureCache();
  8254. texture.isReady = true;
  8255. };
  8256. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  8257. if (texture._isDisabled) {
  8258. return;
  8259. }
  8260. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8261. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  8262. try {
  8263. // Testing video texture support
  8264. if (this._videoTextureSupported === undefined) {
  8265. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8266. if (this._gl.getError() !== 0) {
  8267. this._videoTextureSupported = false;
  8268. }
  8269. else {
  8270. this._videoTextureSupported = true;
  8271. }
  8272. }
  8273. // Copy video through the current working canvas if video texture is not supported
  8274. if (!this._videoTextureSupported) {
  8275. if (!texture._workingCanvas) {
  8276. texture._workingCanvas = document.createElement("canvas");
  8277. texture._workingContext = texture._workingCanvas.getContext("2d");
  8278. texture._workingCanvas.width = texture._width;
  8279. texture._workingCanvas.height = texture._height;
  8280. }
  8281. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture._width, texture._height);
  8282. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  8283. }
  8284. else {
  8285. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  8286. }
  8287. if (texture.generateMipMaps) {
  8288. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8289. }
  8290. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8291. this.resetTextureCache();
  8292. texture.isReady = true;
  8293. }
  8294. catch (ex) {
  8295. // Something unexpected
  8296. // Let's disable the texture
  8297. texture._isDisabled = true;
  8298. }
  8299. };
  8300. Engine.prototype.createRenderTargetTexture = function (size, options) {
  8301. // old version had a "generateMipMaps" arg instead of options.
  8302. // if options.generateMipMaps is undefined, consider that options itself if the generateMipmaps value
  8303. // in the same way, generateDepthBuffer is defaulted to true
  8304. var generateMipMaps = false;
  8305. var generateDepthBuffer = true;
  8306. var generateStencilBuffer = false;
  8307. var type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8308. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8309. if (options !== undefined) {
  8310. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8311. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8312. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8313. type = options.type === undefined ? type : options.type;
  8314. if (options.samplingMode !== undefined) {
  8315. samplingMode = options.samplingMode;
  8316. }
  8317. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  8318. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  8319. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8320. }
  8321. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  8322. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  8323. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  8324. }
  8325. }
  8326. var gl = this._gl;
  8327. var texture = gl.createTexture();
  8328. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8329. var width = size.width || size;
  8330. var height = size.height || size;
  8331. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8332. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  8333. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  8334. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  8335. }
  8336. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  8337. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  8338. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8339. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8340. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, getWebGLTextureType(gl, type), null);
  8341. var depthStencilBuffer;
  8342. // Create the depth/stencil buffer
  8343. if (generateStencilBuffer) {
  8344. depthStencilBuffer = gl.createRenderbuffer();
  8345. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8346. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  8347. }
  8348. else if (generateDepthBuffer) {
  8349. depthStencilBuffer = gl.createRenderbuffer();
  8350. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8351. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  8352. }
  8353. // Create the framebuffer
  8354. var framebuffer = gl.createFramebuffer();
  8355. this.bindUnboundFramebuffer(framebuffer);
  8356. // Manage attachments
  8357. if (generateStencilBuffer) {
  8358. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8359. }
  8360. else if (generateDepthBuffer) {
  8361. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8362. }
  8363. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  8364. if (generateMipMaps) {
  8365. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  8366. }
  8367. // Unbind
  8368. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8369. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8370. this.bindUnboundFramebuffer(null);
  8371. texture._framebuffer = framebuffer;
  8372. if (generateDepthBuffer) {
  8373. texture._depthBuffer = depthStencilBuffer;
  8374. }
  8375. texture._baseWidth = width;
  8376. texture._baseHeight = height;
  8377. texture._width = width;
  8378. texture._height = height;
  8379. texture.isReady = true;
  8380. texture.generateMipMaps = generateMipMaps;
  8381. texture.references = 1;
  8382. texture.samplingMode = samplingMode;
  8383. texture.type = type;
  8384. this.resetTextureCache();
  8385. this._loadedTexturesCache.push(texture);
  8386. return texture;
  8387. };
  8388. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  8389. var gl = this._gl;
  8390. var texture = gl.createTexture();
  8391. var generateMipMaps = true;
  8392. var generateDepthBuffer = true;
  8393. var generateStencilBuffer = false;
  8394. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  8395. if (options !== undefined) {
  8396. generateMipMaps = options.generateMipMaps === undefined ? options : options.generateMipMaps;
  8397. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  8398. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  8399. if (options.samplingMode !== undefined) {
  8400. samplingMode = options.samplingMode;
  8401. }
  8402. }
  8403. texture.isCube = true;
  8404. texture.references = 1;
  8405. texture.generateMipMaps = generateMipMaps;
  8406. texture.references = 1;
  8407. texture.samplingMode = samplingMode;
  8408. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  8409. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8410. for (var face = 0; face < 6; face++) {
  8411. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  8412. }
  8413. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  8414. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  8415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8417. // Create the depth buffer
  8418. var depthStencilBuffer;
  8419. // Create the depth/stencil buffer
  8420. if (generateStencilBuffer) {
  8421. depthStencilBuffer = gl.createRenderbuffer();
  8422. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8423. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, size, size);
  8424. }
  8425. else if (generateDepthBuffer) {
  8426. depthStencilBuffer = gl.createRenderbuffer();
  8427. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  8428. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, size, size);
  8429. }
  8430. // Create the framebuffer
  8431. var framebuffer = gl.createFramebuffer();
  8432. this.bindUnboundFramebuffer(framebuffer);
  8433. // Manage attachments
  8434. if (generateStencilBuffer) {
  8435. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8436. }
  8437. else if (generateDepthBuffer) {
  8438. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  8439. }
  8440. // Mipmaps
  8441. if (texture.generateMipMaps) {
  8442. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8443. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8444. }
  8445. // Unbind
  8446. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8447. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  8448. this.bindUnboundFramebuffer(null);
  8449. texture._framebuffer = framebuffer;
  8450. if (generateDepthBuffer) {
  8451. texture._depthBuffer = depthStencilBuffer;
  8452. }
  8453. texture._width = size;
  8454. texture._height = size;
  8455. texture.isReady = true;
  8456. this.resetTextureCache();
  8457. this._loadedTexturesCache.push(texture);
  8458. return texture;
  8459. };
  8460. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError) {
  8461. var _this = this;
  8462. if (onLoad === void 0) { onLoad = null; }
  8463. if (onError === void 0) { onError = null; }
  8464. var gl = this._gl;
  8465. var texture = gl.createTexture();
  8466. texture.isCube = true;
  8467. texture.url = rootUrl;
  8468. texture.references = 1;
  8469. texture.onLoadedCallbacks = [];
  8470. var extension = rootUrl.substr(rootUrl.length - 4, 4).toLowerCase();
  8471. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  8472. if (isDDS) {
  8473. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  8474. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  8475. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  8476. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8477. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  8478. BABYLON.Internals.DDSTools.UploadDDSLevels(_this._gl, _this.getCaps().s3tc, data, info, loadMipmap, 6);
  8479. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  8480. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8481. }
  8482. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8483. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  8484. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8485. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8486. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8487. _this.resetTextureCache();
  8488. texture._width = info.width;
  8489. texture._height = info.height;
  8490. texture.isReady = true;
  8491. }, null, null, true, onError);
  8492. }
  8493. else {
  8494. cascadeLoad(rootUrl, scene, function (imgs) {
  8495. var width = BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize);
  8496. var height = width;
  8497. _this._prepareWorkingCanvas();
  8498. _this._workingCanvas.width = width;
  8499. _this._workingCanvas.height = height;
  8500. var faces = [
  8501. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8502. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8503. ];
  8504. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8505. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8506. for (var index = 0; index < faces.length; index++) {
  8507. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  8508. gl.texImage2D(faces[index], 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, _this._workingCanvas);
  8509. }
  8510. if (!noMipmap) {
  8511. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8512. }
  8513. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8514. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8515. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8516. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8517. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8518. _this.resetTextureCache();
  8519. texture._width = width;
  8520. texture._height = height;
  8521. texture.isReady = true;
  8522. texture.onLoadedCallbacks.forEach(function (callback) {
  8523. callback();
  8524. });
  8525. if (onLoad) {
  8526. onLoad();
  8527. }
  8528. }, files, onError);
  8529. }
  8530. this._loadedTexturesCache.push(texture);
  8531. return texture;
  8532. };
  8533. Engine.prototype.updateTextureSize = function (texture, width, height) {
  8534. texture._width = width;
  8535. texture._height = height;
  8536. texture._size = width * height;
  8537. texture._baseWidth = width;
  8538. texture._baseHeight = height;
  8539. };
  8540. Engine.prototype.createRawCubeTexture = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator) {
  8541. var _this = this;
  8542. var gl = this._gl;
  8543. var texture = gl.createTexture();
  8544. scene._addPendingData(texture);
  8545. texture.isCube = true;
  8546. texture.references = 1;
  8547. texture.url = url;
  8548. var internalFormat = this._getInternalFormat(format);
  8549. var textureType = gl.UNSIGNED_BYTE;
  8550. if (type === Engine.TEXTURETYPE_FLOAT) {
  8551. textureType = gl.FLOAT;
  8552. }
  8553. var width = size;
  8554. var height = width;
  8555. var isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8556. texture._width = width;
  8557. texture._height = height;
  8558. var onerror = function () {
  8559. scene._removePendingData(texture);
  8560. };
  8561. var internalCallback = function (data) {
  8562. var rgbeDataArrays = callback(data);
  8563. var facesIndex = [
  8564. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  8565. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  8566. ];
  8567. width = texture._width;
  8568. height = texture._height;
  8569. isPot = (BABYLON.Tools.IsExponentOfTwo(width) && BABYLON.Tools.IsExponentOfTwo(height));
  8570. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8571. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  8572. if (!noMipmap && isPot) {
  8573. if (mipmmapGenerator) {
  8574. var arrayTemp = [];
  8575. // Data are known to be in +X +Y +Z -X -Y -Z
  8576. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  8577. arrayTemp.push(rgbeDataArrays[0]); // +X
  8578. arrayTemp.push(rgbeDataArrays[3]); // -X
  8579. arrayTemp.push(rgbeDataArrays[1]); // +Y
  8580. arrayTemp.push(rgbeDataArrays[4]); // -Y
  8581. arrayTemp.push(rgbeDataArrays[2]); // +Z
  8582. arrayTemp.push(rgbeDataArrays[5]); // -Z
  8583. var mipData = mipmmapGenerator(arrayTemp);
  8584. for (var level = 0; level < mipData.length; level++) {
  8585. var mipSize = width >> level;
  8586. // mipData is order in +X -X +Y -Y +Z -Z
  8587. gl.texImage2D(facesIndex[0], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][0]);
  8588. gl.texImage2D(facesIndex[1], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][2]);
  8589. gl.texImage2D(facesIndex[2], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][4]);
  8590. gl.texImage2D(facesIndex[3], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][1]);
  8591. gl.texImage2D(facesIndex[4], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][3]);
  8592. gl.texImage2D(facesIndex[5], level, internalFormat, mipSize, mipSize, 0, internalFormat, textureType, mipData[level][5]);
  8593. }
  8594. }
  8595. else {
  8596. // Data are known to be in +X +Y +Z -X -Y -Z
  8597. for (var index = 0; index < facesIndex.length; index++) {
  8598. var faceData = rgbeDataArrays[index];
  8599. gl.texImage2D(facesIndex[index], 0, internalFormat, width, height, 0, internalFormat, textureType, faceData);
  8600. }
  8601. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8602. // Workaround firefox bug fix https://bugzilla.mozilla.org/show_bug.cgi?id=1221822
  8603. // By following the webgl standard changes from Revision 7, 2014/11/24
  8604. // Firefox Removed the support for RGB32F, since it is not natively supported on all platforms where WebGL is implemented.
  8605. if (textureType === gl.FLOAT && internalFormat === gl.RGB && gl.getError() === 1282) {
  8606. BABYLON.Tools.Log("RGB32F not renderable on Firefox, trying fallback to RGBA32F.");
  8607. // Data are known to be in +X +Y +Z -X -Y -Z
  8608. for (var index = 0; index < facesIndex.length; index++) {
  8609. var faceData = rgbeDataArrays[index];
  8610. // Create a new RGBA Face.
  8611. var newFaceData = new Float32Array(width * height * 4);
  8612. for (var x = 0; x < width; x++) {
  8613. for (var y = 0; y < height; y++) {
  8614. var index_1 = (y * width + x) * 3;
  8615. var newIndex = (y * width + x) * 4;
  8616. // Map Old Value to new value.
  8617. newFaceData[newIndex + 0] = faceData[index_1 + 0];
  8618. newFaceData[newIndex + 1] = faceData[index_1 + 1];
  8619. newFaceData[newIndex + 2] = faceData[index_1 + 2];
  8620. // Add fully opaque alpha channel.
  8621. newFaceData[newIndex + 3] = 1;
  8622. }
  8623. }
  8624. // Reupload the face.
  8625. gl.texImage2D(facesIndex[index], 0, gl.RGBA, width, height, 0, gl.RGBA, textureType, newFaceData);
  8626. }
  8627. // Try to generate mipmap again.
  8628. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8629. }
  8630. }
  8631. }
  8632. else {
  8633. noMipmap = true;
  8634. }
  8635. if (textureType === gl.FLOAT && !_this._caps.textureFloatLinearFiltering) {
  8636. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8637. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8638. }
  8639. else if (textureType === HALF_FLOAT_OES && !_this._caps.textureHalfFloatLinearFiltering) {
  8640. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  8641. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  8642. }
  8643. else {
  8644. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  8645. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  8646. }
  8647. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  8648. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  8649. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8650. texture.isReady = true;
  8651. _this.resetTextureCache();
  8652. scene._removePendingData(texture);
  8653. };
  8654. BABYLON.Tools.LoadFile(url, function (data) {
  8655. internalCallback(data);
  8656. }, onerror, scene.database, true);
  8657. return texture;
  8658. };
  8659. ;
  8660. Engine.prototype._releaseTexture = function (texture) {
  8661. var gl = this._gl;
  8662. if (texture._framebuffer) {
  8663. gl.deleteFramebuffer(texture._framebuffer);
  8664. }
  8665. if (texture._depthBuffer) {
  8666. gl.deleteRenderbuffer(texture._depthBuffer);
  8667. }
  8668. gl.deleteTexture(texture);
  8669. // Unbind channels
  8670. this.unbindAllTextures();
  8671. var index = this._loadedTexturesCache.indexOf(texture);
  8672. if (index !== -1) {
  8673. this._loadedTexturesCache.splice(index, 1);
  8674. }
  8675. };
  8676. Engine.prototype.setProgram = function (program) {
  8677. if (this._currentProgram !== program) {
  8678. this._gl.useProgram(program);
  8679. this._currentProgram = program;
  8680. }
  8681. };
  8682. Engine.prototype.bindSamplers = function (effect) {
  8683. this.setProgram(effect.getProgram());
  8684. var samplers = effect.getSamplers();
  8685. for (var index = 0; index < samplers.length; index++) {
  8686. var uniform = effect.getUniform(samplers[index]);
  8687. this._gl.uniform1i(uniform, index);
  8688. }
  8689. this._currentEffect = null;
  8690. };
  8691. Engine.prototype.activateTexture = function (texture) {
  8692. if (this._activeTexture !== texture) {
  8693. this._gl.activeTexture(texture);
  8694. this._activeTexture = texture;
  8695. }
  8696. };
  8697. Engine.prototype._bindTextureDirectly = function (target, texture) {
  8698. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  8699. this._gl.bindTexture(target, texture);
  8700. this._activeTexturesCache[this._activeTexture] = texture;
  8701. }
  8702. };
  8703. Engine.prototype._bindTexture = function (channel, texture) {
  8704. if (channel < 0) {
  8705. return;
  8706. }
  8707. this.activateTexture(this._gl.TEXTURE0 + channel);
  8708. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  8709. };
  8710. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  8711. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  8712. };
  8713. Engine.prototype.unbindAllTextures = function () {
  8714. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  8715. this.activateTexture(this._gl["TEXTURE" + channel]);
  8716. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8717. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8718. }
  8719. };
  8720. Engine.prototype.setTexture = function (channel, uniform, texture) {
  8721. if (channel < 0) {
  8722. return;
  8723. }
  8724. this._gl.uniform1i(uniform, channel);
  8725. this._setTexture(channel, texture);
  8726. };
  8727. Engine.prototype._setTexture = function (channel, texture) {
  8728. // Not ready?
  8729. if (!texture || !texture.isReady()) {
  8730. if (this._activeTexturesCache[channel] != null) {
  8731. this.activateTexture(this._gl["TEXTURE" + channel]);
  8732. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  8733. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  8734. }
  8735. return;
  8736. }
  8737. // Video
  8738. var alreadyActivated = false;
  8739. if (texture instanceof BABYLON.VideoTexture) {
  8740. this.activateTexture(this._gl["TEXTURE" + channel]);
  8741. alreadyActivated = true;
  8742. texture.update();
  8743. }
  8744. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  8745. texture.delayLoad();
  8746. return;
  8747. }
  8748. var internalTexture = texture.getInternalTexture();
  8749. if (this._activeTexturesCache[channel] === internalTexture) {
  8750. return;
  8751. }
  8752. if (!alreadyActivated) {
  8753. this.activateTexture(this._gl["TEXTURE" + channel]);
  8754. }
  8755. if (internalTexture.isCube) {
  8756. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  8757. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  8758. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  8759. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  8760. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  8761. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  8762. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  8763. }
  8764. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  8765. }
  8766. else {
  8767. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  8768. if (internalTexture._cachedWrapU !== texture.wrapU) {
  8769. internalTexture._cachedWrapU = texture.wrapU;
  8770. switch (texture.wrapU) {
  8771. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8772. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  8773. break;
  8774. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8775. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  8776. break;
  8777. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8778. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  8779. break;
  8780. }
  8781. }
  8782. if (internalTexture._cachedWrapV !== texture.wrapV) {
  8783. internalTexture._cachedWrapV = texture.wrapV;
  8784. switch (texture.wrapV) {
  8785. case BABYLON.Texture.WRAP_ADDRESSMODE:
  8786. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  8787. break;
  8788. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  8789. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  8790. break;
  8791. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  8792. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  8793. break;
  8794. }
  8795. }
  8796. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  8797. }
  8798. };
  8799. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  8800. if (channel < 0) {
  8801. return;
  8802. }
  8803. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  8804. this._textureUnits = new Int32Array(textures.length);
  8805. }
  8806. for (var i = 0; i < textures.length; i++) {
  8807. this._textureUnits[i] = channel + i;
  8808. }
  8809. this._gl.uniform1iv(uniform, this._textureUnits);
  8810. for (var index = 0; index < textures.length; index++) {
  8811. this._setTexture(channel + index, textures[index]);
  8812. }
  8813. };
  8814. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  8815. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  8816. var value = texture.anisotropicFilteringLevel;
  8817. if (texture.getInternalTexture().samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  8818. value = 1;
  8819. }
  8820. if (anisotropicFilterExtension && texture._cachedAnisotropicFilteringLevel !== value) {
  8821. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  8822. texture._cachedAnisotropicFilteringLevel = value;
  8823. }
  8824. };
  8825. Engine.prototype.readPixels = function (x, y, width, height) {
  8826. var data = new Uint8Array(height * width * 4);
  8827. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  8828. return data;
  8829. };
  8830. /**
  8831. * Add an externaly attached data from its key.
  8832. * This method call will fail and return false, if such key already exists.
  8833. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  8834. * @param key the unique key that identifies the data
  8835. * @param data the data object to associate to the key for this Engine instance
  8836. * @return true if no such key were already present and the data was added successfully, false otherwise
  8837. */
  8838. Engine.prototype.addExternalData = function (key, data) {
  8839. return this._externalData.add(key, data);
  8840. };
  8841. /**
  8842. * Get an externaly attached data from its key
  8843. * @param key the unique key that identifies the data
  8844. * @return the associated data, if present (can be null), or undefined if not present
  8845. */
  8846. Engine.prototype.getExternalData = function (key) {
  8847. return this._externalData.get(key);
  8848. };
  8849. /**
  8850. * Get an externaly attached data from its key, create it using a factory if it's not already present
  8851. * @param key the unique key that identifies the data
  8852. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  8853. * @return the associated data, can be null if the factory returned null.
  8854. */
  8855. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  8856. return this._externalData.getOrAddWithFactory(key, factory);
  8857. };
  8858. /**
  8859. * Remove an externaly attached data from the Engine instance
  8860. * @param key the unique key that identifies the data
  8861. * @return true if the data was successfully removed, false if it doesn't exist
  8862. */
  8863. Engine.prototype.removeExternalData = function (key) {
  8864. return this._externalData.remove(key);
  8865. };
  8866. Engine.prototype.releaseInternalTexture = function (texture) {
  8867. if (!texture) {
  8868. return;
  8869. }
  8870. texture.references--;
  8871. // Final reference ?
  8872. if (texture.references === 0) {
  8873. var texturesCache = this.getLoadedTexturesCache();
  8874. var index = texturesCache.indexOf(texture);
  8875. if (index > -1) {
  8876. texturesCache.splice(index, 1);
  8877. }
  8878. this._releaseTexture(texture);
  8879. }
  8880. };
  8881. Engine.prototype.unbindAllAttributes = function () {
  8882. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  8883. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  8884. continue;
  8885. }
  8886. if (this._vertexAttribArraysEnabled[i]) {
  8887. this._gl.disableVertexAttribArray(i);
  8888. this._vertexAttribArraysEnabled[i] = false;
  8889. }
  8890. }
  8891. };
  8892. // Dispose
  8893. Engine.prototype.dispose = function () {
  8894. this.hideLoadingUI();
  8895. this.stopRenderLoop();
  8896. // Release scenes
  8897. while (this.scenes.length) {
  8898. this.scenes[0].dispose();
  8899. }
  8900. // Release audio engine
  8901. Engine.audioEngine.dispose();
  8902. // Release effects
  8903. for (var name in this._compiledEffects) {
  8904. this._gl.deleteProgram(this._compiledEffects[name]._program);
  8905. }
  8906. // Unbind
  8907. this.unbindAllAttributes();
  8908. this._gl = null;
  8909. //WebVR
  8910. this.disableVR();
  8911. // Events
  8912. window.removeEventListener("blur", this._onBlur);
  8913. window.removeEventListener("focus", this._onFocus);
  8914. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  8915. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  8916. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  8917. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  8918. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  8919. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  8920. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  8921. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  8922. };
  8923. // Loading screen
  8924. Engine.prototype.displayLoadingUI = function () {
  8925. this._loadingScreen.displayLoadingUI();
  8926. };
  8927. Engine.prototype.hideLoadingUI = function () {
  8928. this._loadingScreen.hideLoadingUI();
  8929. };
  8930. Object.defineProperty(Engine.prototype, "loadingScreen", {
  8931. get: function () {
  8932. return this._loadingScreen;
  8933. },
  8934. set: function (loadingScreen) {
  8935. this._loadingScreen = loadingScreen;
  8936. },
  8937. enumerable: true,
  8938. configurable: true
  8939. });
  8940. Object.defineProperty(Engine.prototype, "loadingUIText", {
  8941. set: function (text) {
  8942. this._loadingScreen.loadingUIText = text;
  8943. },
  8944. enumerable: true,
  8945. configurable: true
  8946. });
  8947. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  8948. set: function (color) {
  8949. this._loadingScreen.loadingUIBackgroundColor = color;
  8950. },
  8951. enumerable: true,
  8952. configurable: true
  8953. });
  8954. Engine.prototype.attachContextLostEvent = function (callback) {
  8955. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  8956. };
  8957. Engine.prototype.attachContextRestoredEvent = function (callback) {
  8958. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  8959. };
  8960. Engine.prototype.getVertexShaderSource = function (program) {
  8961. var shaders = this._gl.getAttachedShaders(program);
  8962. return this._gl.getShaderSource(shaders[0]);
  8963. };
  8964. Engine.prototype.getFragmentShaderSource = function (program) {
  8965. var shaders = this._gl.getAttachedShaders(program);
  8966. return this._gl.getShaderSource(shaders[1]);
  8967. };
  8968. // FPS
  8969. Engine.prototype.getFps = function () {
  8970. return this.fps;
  8971. };
  8972. Engine.prototype.getDeltaTime = function () {
  8973. return this.deltaTime;
  8974. };
  8975. Engine.prototype._measureFps = function () {
  8976. this.previousFramesDuration.push(BABYLON.Tools.Now);
  8977. var length = this.previousFramesDuration.length;
  8978. if (length >= 2) {
  8979. this.deltaTime = this.previousFramesDuration[length - 1] - this.previousFramesDuration[length - 2];
  8980. }
  8981. if (length >= this.fpsRange) {
  8982. if (length > this.fpsRange) {
  8983. this.previousFramesDuration.splice(0, 1);
  8984. length = this.previousFramesDuration.length;
  8985. }
  8986. var sum = 0;
  8987. for (var id = 0; id < length - 1; id++) {
  8988. sum += this.previousFramesDuration[id + 1] - this.previousFramesDuration[id];
  8989. }
  8990. this.fps = 1000.0 / (sum / (length - 1));
  8991. }
  8992. };
  8993. Engine.prototype._canRenderToFloatTexture = function () {
  8994. try {
  8995. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_FLOAT, 'OES_texture_float');
  8996. }
  8997. catch (e) {
  8998. return false;
  8999. }
  9000. };
  9001. Engine.prototype._canRenderToHalfFloatTexture = function () {
  9002. try {
  9003. return this._canRenderToTextureOfType(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT, 'OES_texture_half_float');
  9004. }
  9005. catch (e) {
  9006. return false;
  9007. }
  9008. };
  9009. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  9010. Engine.prototype._canRenderToTextureOfType = function (format, extension) {
  9011. var tempcanvas = document.createElement("canvas");
  9012. tempcanvas.height = 16;
  9013. tempcanvas.width = 16;
  9014. var gl = (tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl"));
  9015. // extension.
  9016. var ext = gl.getExtension(extension);
  9017. if (!ext) {
  9018. return false;
  9019. }
  9020. // setup GLSL program
  9021. var vertexCode = "attribute vec4 a_position;\n void main() {\n gl_Position = a_position;\n }";
  9022. var fragmentCode = "precision mediump float;\n uniform vec4 u_color;\n uniform sampler2D u_texture;\n\n void main() {\n gl_FragColor = texture2D(u_texture, vec2(0.5, 0.5)) * u_color;\n }";
  9023. var program = this.createShaderProgram(vertexCode, fragmentCode, null, gl);
  9024. gl.useProgram(program);
  9025. // look up where the vertex data needs to go.
  9026. var positionLocation = gl.getAttribLocation(program, "a_position");
  9027. var colorLoc = gl.getUniformLocation(program, "u_color");
  9028. // provide texture coordinates for the rectangle.
  9029. var positionBuffer = gl.createBuffer();
  9030. gl.bindBuffer(gl.ARRAY_BUFFER, positionBuffer);
  9031. gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([
  9032. -1.0, -1.0,
  9033. 1.0, -1.0,
  9034. -1.0, 1.0,
  9035. -1.0, 1.0,
  9036. 1.0, -1.0,
  9037. 1.0, 1.0
  9038. ]), gl.STATIC_DRAW);
  9039. gl.enableVertexAttribArray(positionLocation);
  9040. gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, 0, 0);
  9041. var whiteTex = gl.createTexture();
  9042. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9043. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, new Uint8Array([255, 255, 255, 255]));
  9044. var tex = gl.createTexture();
  9045. gl.bindTexture(gl.TEXTURE_2D, tex);
  9046. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, getWebGLTextureType(gl, format), null);
  9047. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  9048. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  9049. var fb = gl.createFramebuffer();
  9050. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  9051. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
  9052. var cleanup = function () {
  9053. gl.deleteProgram(program);
  9054. gl.disableVertexAttribArray(positionLocation);
  9055. gl.deleteBuffer(positionBuffer);
  9056. gl.deleteFramebuffer(fb);
  9057. gl.deleteTexture(whiteTex);
  9058. gl.deleteTexture(tex);
  9059. };
  9060. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  9061. if (status !== gl.FRAMEBUFFER_COMPLETE) {
  9062. BABYLON.Tools.Log("GL Support: can **NOT** render to " + format + " texture");
  9063. cleanup();
  9064. return false;
  9065. }
  9066. // Draw the rectangle.
  9067. gl.bindTexture(gl.TEXTURE_2D, whiteTex);
  9068. gl.uniform4fv(colorLoc, [0, 10, 20, 1]);
  9069. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9070. gl.bindTexture(gl.TEXTURE_2D, tex);
  9071. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  9072. gl.clearColor(1, 0, 0, 1);
  9073. gl.clear(gl.COLOR_BUFFER_BIT);
  9074. gl.uniform4fv(colorLoc, [0, 1 / 10, 1 / 20, 1]);
  9075. gl.drawArrays(gl.TRIANGLES, 0, 6);
  9076. var pixel = new Uint8Array(4);
  9077. gl.readPixels(0, 0, 1, 1, gl.RGBA, gl.UNSIGNED_BYTE, pixel);
  9078. if (pixel[0] !== 0 ||
  9079. pixel[1] < 248 ||
  9080. pixel[2] < 248 ||
  9081. pixel[3] < 254) {
  9082. BABYLON.Tools.Log("GL Support: Was not able to actually render to " + format + " texture");
  9083. cleanup();
  9084. return false;
  9085. }
  9086. // Succesfully rendered to "format" texture.
  9087. cleanup();
  9088. return true;
  9089. };
  9090. // Statics
  9091. Engine.isSupported = function () {
  9092. try {
  9093. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  9094. if (navigator.isCocoonJS) {
  9095. return true;
  9096. }
  9097. var tempcanvas = document.createElement("canvas");
  9098. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  9099. return gl != null && !!window.WebGLRenderingContext;
  9100. }
  9101. catch (e) {
  9102. return false;
  9103. }
  9104. };
  9105. return Engine;
  9106. }());
  9107. // Const statics
  9108. Engine._ALPHA_DISABLE = 0;
  9109. Engine._ALPHA_ADD = 1;
  9110. Engine._ALPHA_COMBINE = 2;
  9111. Engine._ALPHA_SUBTRACT = 3;
  9112. Engine._ALPHA_MULTIPLY = 4;
  9113. Engine._ALPHA_MAXIMIZED = 5;
  9114. Engine._ALPHA_ONEONE = 6;
  9115. Engine._ALPHA_PREMULTIPLIED = 7;
  9116. Engine._DELAYLOADSTATE_NONE = 0;
  9117. Engine._DELAYLOADSTATE_LOADED = 1;
  9118. Engine._DELAYLOADSTATE_LOADING = 2;
  9119. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  9120. Engine._TEXTUREFORMAT_ALPHA = 0;
  9121. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  9122. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  9123. Engine._TEXTUREFORMAT_RGB = 4;
  9124. Engine._TEXTUREFORMAT_RGBA = 5;
  9125. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  9126. Engine._TEXTURETYPE_FLOAT = 1;
  9127. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  9128. // Depht or Stencil test Constants.
  9129. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  9130. Engine._ALWAYS = 0x0207; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will always pass. i.e. Pixels will be drawn in the order they are drawn.
  9131. Engine._LESS = 0x0201; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value.
  9132. Engine._EQUAL = 0x0202; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value.
  9133. Engine._LEQUAL = 0x0203; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than or equal to the stored value.
  9134. Engine._GREATER = 0x0204; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value.
  9135. Engine._GEQUAL = 0x0206; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than or equal to the stored value.
  9136. Engine._NOTEQUAL = 0x0205; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is not equal to the stored value.
  9137. // Stencil Actions Constants.
  9138. Engine._KEEP = 0x1E00;
  9139. Engine._REPLACE = 0x1E01;
  9140. Engine._INCR = 0x1E02;
  9141. Engine._DECR = 0x1E03;
  9142. Engine._INVERT = 0x150A;
  9143. Engine._INCR_WRAP = 0x8507;
  9144. Engine._DECR_WRAP = 0x8508;
  9145. // Updatable statics so stick with vars here
  9146. Engine.CollisionsEpsilon = 0.001;
  9147. Engine.CodeRepository = "src/";
  9148. Engine.ShadersRepository = "src/Shaders/";
  9149. BABYLON.Engine = Engine;
  9150. })(BABYLON || (BABYLON = {}));
  9151. //# sourceMappingURL=babylon.engine.js.map
  9152. var BABYLON;
  9153. (function (BABYLON) {
  9154. /**
  9155. * Node is the basic class for all scene objects (Mesh, Light Camera).
  9156. */
  9157. var Node = (function () {
  9158. /**
  9159. * @constructor
  9160. * @param {string} name - the name and id to be given to this node
  9161. * @param {BABYLON.Scene} the scene this node will be added to
  9162. */
  9163. function Node(name, scene) {
  9164. this.state = "";
  9165. this.metadata = null;
  9166. this.doNotSerialize = false;
  9167. this.animations = new Array();
  9168. this._ranges = {};
  9169. this._childrenFlag = -1;
  9170. this._isEnabled = true;
  9171. this._isReady = true;
  9172. this._currentRenderId = -1;
  9173. this._parentRenderId = -1;
  9174. /**
  9175. * An event triggered when the mesh is disposed.
  9176. * @type {BABYLON.Observable}
  9177. */
  9178. this.onDisposeObservable = new BABYLON.Observable();
  9179. this.name = name;
  9180. this.id = name;
  9181. this._scene = scene;
  9182. this._initCache();
  9183. }
  9184. Object.defineProperty(Node.prototype, "parent", {
  9185. get: function () {
  9186. return this._parentNode;
  9187. },
  9188. set: function (parent) {
  9189. if (this._parentNode === parent) {
  9190. return;
  9191. }
  9192. if (this._parentNode) {
  9193. var index = this._parentNode._children.indexOf(this);
  9194. if (index !== -1) {
  9195. this._parentNode._children.splice(index, 1);
  9196. }
  9197. }
  9198. this._parentNode = parent;
  9199. if (this._parentNode) {
  9200. if (!this._parentNode._children) {
  9201. this._parentNode._children = new Array();
  9202. }
  9203. this._parentNode._children.push(this);
  9204. }
  9205. },
  9206. enumerable: true,
  9207. configurable: true
  9208. });
  9209. Node.prototype.getClassName = function () {
  9210. return "Node";
  9211. };
  9212. Object.defineProperty(Node.prototype, "onDispose", {
  9213. set: function (callback) {
  9214. if (this._onDisposeObserver) {
  9215. this.onDisposeObservable.remove(this._onDisposeObserver);
  9216. }
  9217. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  9218. },
  9219. enumerable: true,
  9220. configurable: true
  9221. });
  9222. Node.prototype.getScene = function () {
  9223. return this._scene;
  9224. };
  9225. Node.prototype.getEngine = function () {
  9226. return this._scene.getEngine();
  9227. };
  9228. // override it in derived class
  9229. Node.prototype.getWorldMatrix = function () {
  9230. return BABYLON.Matrix.Identity();
  9231. };
  9232. // override it in derived class if you add new variables to the cache
  9233. // and call the parent class method
  9234. Node.prototype._initCache = function () {
  9235. this._cache = {};
  9236. this._cache.parent = undefined;
  9237. };
  9238. Node.prototype.updateCache = function (force) {
  9239. if (!force && this.isSynchronized())
  9240. return;
  9241. this._cache.parent = this.parent;
  9242. this._updateCache();
  9243. };
  9244. // override it in derived class if you add new variables to the cache
  9245. // and call the parent class method if !ignoreParentClass
  9246. Node.prototype._updateCache = function (ignoreParentClass) {
  9247. };
  9248. // override it in derived class if you add new variables to the cache
  9249. Node.prototype._isSynchronized = function () {
  9250. return true;
  9251. };
  9252. Node.prototype._markSyncedWithParent = function () {
  9253. this._parentRenderId = this.parent._currentRenderId;
  9254. };
  9255. Node.prototype.isSynchronizedWithParent = function () {
  9256. if (!this.parent) {
  9257. return true;
  9258. }
  9259. if (this._parentRenderId !== this.parent._currentRenderId) {
  9260. return false;
  9261. }
  9262. return this.parent.isSynchronized();
  9263. };
  9264. Node.prototype.isSynchronized = function (updateCache) {
  9265. var check = this.hasNewParent();
  9266. check = check || !this.isSynchronizedWithParent();
  9267. check = check || !this._isSynchronized();
  9268. if (updateCache)
  9269. this.updateCache(true);
  9270. return !check;
  9271. };
  9272. Node.prototype.hasNewParent = function (update) {
  9273. if (this._cache.parent === this.parent)
  9274. return false;
  9275. if (update)
  9276. this._cache.parent = this.parent;
  9277. return true;
  9278. };
  9279. /**
  9280. * Is this node ready to be used/rendered
  9281. * @return {boolean} is it ready
  9282. */
  9283. Node.prototype.isReady = function () {
  9284. return this._isReady;
  9285. };
  9286. /**
  9287. * Is this node enabled.
  9288. * If the node has a parent and is enabled, the parent will be inspected as well.
  9289. * @return {boolean} whether this node (and its parent) is enabled.
  9290. * @see setEnabled
  9291. */
  9292. Node.prototype.isEnabled = function () {
  9293. if (!this._isEnabled) {
  9294. return false;
  9295. }
  9296. if (this.parent) {
  9297. return this.parent.isEnabled();
  9298. }
  9299. return true;
  9300. };
  9301. /**
  9302. * Set the enabled state of this node.
  9303. * @param {boolean} value - the new enabled state
  9304. * @see isEnabled
  9305. */
  9306. Node.prototype.setEnabled = function (value) {
  9307. this._isEnabled = value;
  9308. };
  9309. /**
  9310. * Is this node a descendant of the given node.
  9311. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  9312. * @param {BABYLON.Node} ancestor - The parent node to inspect
  9313. * @see parent
  9314. */
  9315. Node.prototype.isDescendantOf = function (ancestor) {
  9316. if (this.parent) {
  9317. if (this.parent === ancestor) {
  9318. return true;
  9319. }
  9320. return this.parent.isDescendantOf(ancestor);
  9321. }
  9322. return false;
  9323. };
  9324. /**
  9325. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  9326. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  9327. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  9328. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  9329. */
  9330. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  9331. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  9332. if (!this._children) {
  9333. return;
  9334. }
  9335. for (var index = 0; index < this._children.length; index++) {
  9336. var item = this._children[index];
  9337. if (!predicate || predicate(item)) {
  9338. results.push(item);
  9339. }
  9340. if (!directDescendantsOnly) {
  9341. item._getDescendants(results, false, predicate);
  9342. }
  9343. }
  9344. };
  9345. /**
  9346. * Will return all nodes that have this node as ascendant.
  9347. * @param {boolean} directDescendantsOnly if true only direct descendants of 'this' will be considered, if false direct and also indirect (children of children, an so on in a recursive manner) descendants of 'this' will be considered.
  9348. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  9349. * @return {BABYLON.Node[]} all children nodes of all types.
  9350. */
  9351. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  9352. var results = [];
  9353. this._getDescendants(results, directDescendantsOnly, predicate);
  9354. return results;
  9355. };
  9356. /**
  9357. * @param predicate: an optional predicate that will be called on every evaluated children, the predicate must return true for a given child to be part of the result, otherwise it will be ignored.
  9358. * @Deprecated, legacy support.
  9359. * use getDecendants instead.
  9360. */
  9361. Node.prototype.getChildren = function (predicate) {
  9362. return this.getDescendants(true, predicate);
  9363. };
  9364. /**
  9365. * Get all child-meshes of this node.
  9366. */
  9367. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  9368. var results = [];
  9369. this._getDescendants(results, directDecendantsOnly, function (node) {
  9370. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  9371. });
  9372. return results;
  9373. };
  9374. Node.prototype._setReady = function (state) {
  9375. if (state === this._isReady) {
  9376. return;
  9377. }
  9378. if (!state) {
  9379. this._isReady = false;
  9380. return;
  9381. }
  9382. this._isReady = true;
  9383. if (this.onReady) {
  9384. this.onReady(this);
  9385. }
  9386. };
  9387. Node.prototype.getAnimationByName = function (name) {
  9388. for (var i = 0; i < this.animations.length; i++) {
  9389. var animation = this.animations[i];
  9390. if (animation.name === name) {
  9391. return animation;
  9392. }
  9393. }
  9394. return null;
  9395. };
  9396. Node.prototype.createAnimationRange = function (name, from, to) {
  9397. // check name not already in use
  9398. if (!this._ranges[name]) {
  9399. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  9400. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9401. if (this.animations[i]) {
  9402. this.animations[i].createRange(name, from, to);
  9403. }
  9404. }
  9405. }
  9406. };
  9407. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  9408. if (deleteFrames === void 0) { deleteFrames = true; }
  9409. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  9410. if (this.animations[i]) {
  9411. this.animations[i].deleteRange(name, deleteFrames);
  9412. }
  9413. }
  9414. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  9415. };
  9416. Node.prototype.getAnimationRange = function (name) {
  9417. return this._ranges[name];
  9418. };
  9419. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  9420. var range = this.getAnimationRange(name);
  9421. if (!range) {
  9422. return null;
  9423. }
  9424. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  9425. };
  9426. Node.prototype.serializeAnimationRanges = function () {
  9427. var serializationRanges = [];
  9428. for (var name in this._ranges) {
  9429. var range = {};
  9430. range.name = name;
  9431. range.from = this._ranges[name].from;
  9432. range.to = this._ranges[name].to;
  9433. serializationRanges.push(range);
  9434. }
  9435. return serializationRanges;
  9436. };
  9437. Node.prototype.dispose = function () {
  9438. this.parent = null;
  9439. // Callback
  9440. this.onDisposeObservable.notifyObservers(this);
  9441. this.onDisposeObservable.clear();
  9442. };
  9443. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  9444. if (parsedNode.ranges) {
  9445. for (var index = 0; index < parsedNode.ranges.length; index++) {
  9446. var data = parsedNode.ranges[index];
  9447. node.createAnimationRange(data.name, data.from, data.to);
  9448. }
  9449. }
  9450. };
  9451. return Node;
  9452. }());
  9453. __decorate([
  9454. BABYLON.serialize()
  9455. ], Node.prototype, "name", void 0);
  9456. __decorate([
  9457. BABYLON.serialize()
  9458. ], Node.prototype, "id", void 0);
  9459. __decorate([
  9460. BABYLON.serialize()
  9461. ], Node.prototype, "uniqueId", void 0);
  9462. __decorate([
  9463. BABYLON.serialize()
  9464. ], Node.prototype, "state", void 0);
  9465. __decorate([
  9466. BABYLON.serialize()
  9467. ], Node.prototype, "metadata", void 0);
  9468. BABYLON.Node = Node;
  9469. })(BABYLON || (BABYLON = {}));
  9470. //# sourceMappingURL=babylon.node.js.map
  9471. var BABYLON;
  9472. (function (BABYLON) {
  9473. var FilesInput = (function () {
  9474. /// Register to core BabylonJS object: engine, scene, rendering canvas, callback function when the scene will be loaded,
  9475. /// loading progress callback and optionnal addionnal logic to call in the rendering loop
  9476. function FilesInput(p_engine, p_scene, p_canvas, p_sceneLoadedCallback, p_progressCallback, p_additionnalRenderLoopLogicCallback, p_textureLoadingCallback, p_startingProcessingFilesCallback) {
  9477. this._engine = p_engine;
  9478. this._canvas = p_canvas;
  9479. this._currentScene = p_scene;
  9480. this._sceneLoadedCallback = p_sceneLoadedCallback;
  9481. this._progressCallback = p_progressCallback;
  9482. this._additionnalRenderLoopLogicCallback = p_additionnalRenderLoopLogicCallback;
  9483. this._textureLoadingCallback = p_textureLoadingCallback;
  9484. this._startingProcessingFilesCallback = p_startingProcessingFilesCallback;
  9485. }
  9486. FilesInput.prototype.monitorElementForDragNDrop = function (p_elementToMonitor) {
  9487. var _this = this;
  9488. if (p_elementToMonitor) {
  9489. this._elementToMonitor = p_elementToMonitor;
  9490. this._elementToMonitor.addEventListener("dragenter", function (e) { _this.drag(e); }, false);
  9491. this._elementToMonitor.addEventListener("dragover", function (e) { _this.drag(e); }, false);
  9492. this._elementToMonitor.addEventListener("drop", function (e) { _this.drop(e); }, false);
  9493. }
  9494. };
  9495. FilesInput.prototype.renderFunction = function () {
  9496. if (this._additionnalRenderLoopLogicCallback) {
  9497. this._additionnalRenderLoopLogicCallback();
  9498. }
  9499. if (this._currentScene) {
  9500. if (this._textureLoadingCallback) {
  9501. var remaining = this._currentScene.getWaitingItemsCount();
  9502. if (remaining > 0) {
  9503. this._textureLoadingCallback(remaining);
  9504. }
  9505. }
  9506. this._currentScene.render();
  9507. }
  9508. };
  9509. FilesInput.prototype.drag = function (e) {
  9510. e.stopPropagation();
  9511. e.preventDefault();
  9512. };
  9513. FilesInput.prototype.drop = function (eventDrop) {
  9514. eventDrop.stopPropagation();
  9515. eventDrop.preventDefault();
  9516. this.loadFiles(eventDrop);
  9517. };
  9518. FilesInput.prototype.loadFiles = function (event) {
  9519. if (this._startingProcessingFilesCallback)
  9520. this._startingProcessingFilesCallback();
  9521. // Handling data transfer via drag'n'drop
  9522. if (event && event.dataTransfer && event.dataTransfer.files) {
  9523. this._filesToLoad = event.dataTransfer.files;
  9524. }
  9525. // Handling files from input files
  9526. if (event && event.target && event.target.files) {
  9527. this._filesToLoad = event.target.files;
  9528. }
  9529. if (this._filesToLoad && this._filesToLoad.length > 0) {
  9530. for (var i = 0; i < this._filesToLoad.length; i++) {
  9531. switch (this._filesToLoad[i].type) {
  9532. case "image/jpeg":
  9533. case "image/png":
  9534. case "image/bmp":
  9535. FilesInput.FilesTextures[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9536. break;
  9537. case "image/targa":
  9538. case "image/vnd.ms-dds":
  9539. case "audio/wav":
  9540. case "audio/x-wav":
  9541. case "audio/mp3":
  9542. case "audio/mpeg":
  9543. case "audio/mpeg3":
  9544. case "audio/x-mpeg-3":
  9545. case "audio/ogg":
  9546. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9547. break;
  9548. default:
  9549. if (this._filesToLoad[i].name.indexOf(".mtl") !== -1) {
  9550. FilesInput.FilesToLoad[this._filesToLoad[i].name.toLowerCase()] = this._filesToLoad[i];
  9551. }
  9552. else if ((this._filesToLoad[i].name.indexOf(".babylon") !== -1 ||
  9553. this._filesToLoad[i].name.indexOf(".stl") !== -1 ||
  9554. this._filesToLoad[i].name.indexOf(".obj") !== -1)
  9555. && this._filesToLoad[i].name.indexOf(".manifest") === -1
  9556. && this._filesToLoad[i].name.indexOf(".incremental") === -1 && this._filesToLoad[i].name.indexOf(".babylonmeshdata") === -1
  9557. && this._filesToLoad[i].name.indexOf(".babylongeometrydata") === -1 && this._filesToLoad[i].name.indexOf(".babylonbinarymeshdata") === -1 &&
  9558. this._filesToLoad[i].name.indexOf(".binary.babylon") === -1) {
  9559. this._sceneFileToLoad = this._filesToLoad[i];
  9560. }
  9561. break;
  9562. }
  9563. }
  9564. this.reload();
  9565. }
  9566. };
  9567. FilesInput.prototype.reload = function () {
  9568. var _this = this;
  9569. var that = this;
  9570. // If a ".babylon" file has been provided
  9571. if (this._sceneFileToLoad) {
  9572. if (this._currentScene) {
  9573. if (BABYLON.Tools.errorsCount > 0) {
  9574. BABYLON.Tools.ClearLogCache();
  9575. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  9576. }
  9577. this._engine.stopRenderLoop();
  9578. this._currentScene.dispose();
  9579. }
  9580. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  9581. that._currentScene = newScene;
  9582. // Wait for textures and shaders to be ready
  9583. that._currentScene.executeWhenReady(function () {
  9584. // Attach camera to canvas inputs
  9585. if (!that._currentScene.activeCamera || that._currentScene.lights.length === 0) {
  9586. that._currentScene.createDefaultCameraOrLight();
  9587. }
  9588. that._currentScene.activeCamera.attachControl(that._canvas);
  9589. if (that._sceneLoadedCallback) {
  9590. that._sceneLoadedCallback(_this._sceneFileToLoad, that._currentScene);
  9591. }
  9592. that._engine.runRenderLoop(function () { that.renderFunction(); });
  9593. });
  9594. }, function (progress) {
  9595. if (_this._progressCallback) {
  9596. _this._progressCallback(progress);
  9597. }
  9598. });
  9599. }
  9600. else {
  9601. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  9602. }
  9603. };
  9604. return FilesInput;
  9605. }());
  9606. FilesInput.FilesTextures = new Array();
  9607. FilesInput.FilesToLoad = new Array();
  9608. BABYLON.FilesInput = FilesInput;
  9609. })(BABYLON || (BABYLON = {}));
  9610. //# sourceMappingURL=babylon.filesInput.js.map
  9611. var BABYLON;
  9612. (function (BABYLON) {
  9613. var IntersectionInfo = (function () {
  9614. function IntersectionInfo(bu, bv, distance) {
  9615. this.bu = bu;
  9616. this.bv = bv;
  9617. this.distance = distance;
  9618. this.faceId = 0;
  9619. this.subMeshId = 0;
  9620. }
  9621. return IntersectionInfo;
  9622. }());
  9623. BABYLON.IntersectionInfo = IntersectionInfo;
  9624. var PickingInfo = (function () {
  9625. function PickingInfo() {
  9626. this.hit = false;
  9627. this.distance = 0;
  9628. this.pickedPoint = null;
  9629. this.pickedMesh = null;
  9630. this.bu = 0;
  9631. this.bv = 0;
  9632. this.faceId = -1;
  9633. this.subMeshId = 0;
  9634. this.pickedSprite = null;
  9635. }
  9636. // Methods
  9637. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  9638. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  9639. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  9640. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  9641. return null;
  9642. }
  9643. var indices = this.pickedMesh.getIndices();
  9644. var result;
  9645. if (useVerticesNormals) {
  9646. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  9647. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  9648. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  9649. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  9650. normal0 = normal0.scale(this.bu);
  9651. normal1 = normal1.scale(this.bv);
  9652. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  9653. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  9654. }
  9655. else {
  9656. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  9657. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  9658. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  9659. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  9660. var p1p2 = vertex1.subtract(vertex2);
  9661. var p3p2 = vertex3.subtract(vertex2);
  9662. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  9663. }
  9664. if (useWorldCoordinates) {
  9665. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  9666. }
  9667. return BABYLON.Vector3.Normalize(result);
  9668. };
  9669. PickingInfo.prototype.getTextureCoordinates = function () {
  9670. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  9671. return null;
  9672. }
  9673. var indices = this.pickedMesh.getIndices();
  9674. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  9675. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  9676. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  9677. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  9678. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  9679. uv1 = uv1.scale(this.bu);
  9680. uv2 = uv2.scale(this.bv);
  9681. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  9682. };
  9683. return PickingInfo;
  9684. }());
  9685. BABYLON.PickingInfo = PickingInfo;
  9686. })(BABYLON || (BABYLON = {}));
  9687. //# sourceMappingURL=babylon.pickingInfo.js.map
  9688. var BABYLON;
  9689. (function (BABYLON) {
  9690. var BoundingSphere = (function () {
  9691. function BoundingSphere(minimum, maximum) {
  9692. this.minimum = minimum;
  9693. this.maximum = maximum;
  9694. this._tempRadiusVector = BABYLON.Vector3.Zero();
  9695. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  9696. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  9697. this.radius = distance * 0.5;
  9698. this.centerWorld = BABYLON.Vector3.Zero();
  9699. this._update(BABYLON.Matrix.Identity());
  9700. }
  9701. // Methods
  9702. BoundingSphere.prototype._update = function (world) {
  9703. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  9704. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  9705. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  9706. };
  9707. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  9708. for (var i = 0; i < 6; i++) {
  9709. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  9710. return false;
  9711. }
  9712. return true;
  9713. };
  9714. BoundingSphere.prototype.intersectsPoint = function (point) {
  9715. var x = this.centerWorld.x - point.x;
  9716. var y = this.centerWorld.y - point.y;
  9717. var z = this.centerWorld.z - point.z;
  9718. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9719. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  9720. return false;
  9721. return true;
  9722. };
  9723. // Statics
  9724. BoundingSphere.Intersects = function (sphere0, sphere1) {
  9725. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  9726. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  9727. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  9728. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  9729. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  9730. return false;
  9731. return true;
  9732. };
  9733. return BoundingSphere;
  9734. }());
  9735. BABYLON.BoundingSphere = BoundingSphere;
  9736. })(BABYLON || (BABYLON = {}));
  9737. //# sourceMappingURL=babylon.boundingSphere.js.map
  9738. var BABYLON;
  9739. (function (BABYLON) {
  9740. var BoundingBox = (function () {
  9741. function BoundingBox(minimum, maximum) {
  9742. this.minimum = minimum;
  9743. this.maximum = maximum;
  9744. this.vectors = new Array();
  9745. this.vectorsWorld = new Array();
  9746. // Bounding vectors
  9747. this.vectors.push(this.minimum.clone());
  9748. this.vectors.push(this.maximum.clone());
  9749. this.vectors.push(this.minimum.clone());
  9750. this.vectors[2].x = this.maximum.x;
  9751. this.vectors.push(this.minimum.clone());
  9752. this.vectors[3].y = this.maximum.y;
  9753. this.vectors.push(this.minimum.clone());
  9754. this.vectors[4].z = this.maximum.z;
  9755. this.vectors.push(this.maximum.clone());
  9756. this.vectors[5].z = this.minimum.z;
  9757. this.vectors.push(this.maximum.clone());
  9758. this.vectors[6].x = this.minimum.x;
  9759. this.vectors.push(this.maximum.clone());
  9760. this.vectors[7].y = this.minimum.y;
  9761. // OBB
  9762. this.center = this.maximum.add(this.minimum).scale(0.5);
  9763. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  9764. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  9765. // World
  9766. for (var index = 0; index < this.vectors.length; index++) {
  9767. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  9768. }
  9769. this.minimumWorld = BABYLON.Vector3.Zero();
  9770. this.maximumWorld = BABYLON.Vector3.Zero();
  9771. this._update(BABYLON.Matrix.Identity());
  9772. }
  9773. // Methods
  9774. BoundingBox.prototype.getWorldMatrix = function () {
  9775. return this._worldMatrix;
  9776. };
  9777. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  9778. this._worldMatrix.copyFrom(matrix);
  9779. return this;
  9780. };
  9781. BoundingBox.prototype._update = function (world) {
  9782. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  9783. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  9784. for (var index = 0; index < this.vectors.length; index++) {
  9785. var v = this.vectorsWorld[index];
  9786. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  9787. if (v.x < this.minimumWorld.x)
  9788. this.minimumWorld.x = v.x;
  9789. if (v.y < this.minimumWorld.y)
  9790. this.minimumWorld.y = v.y;
  9791. if (v.z < this.minimumWorld.z)
  9792. this.minimumWorld.z = v.z;
  9793. if (v.x > this.maximumWorld.x)
  9794. this.maximumWorld.x = v.x;
  9795. if (v.y > this.maximumWorld.y)
  9796. this.maximumWorld.y = v.y;
  9797. if (v.z > this.maximumWorld.z)
  9798. this.maximumWorld.z = v.z;
  9799. }
  9800. // OBB
  9801. this.maximumWorld.addToRef(this.minimumWorld, this.center);
  9802. this.center.scaleInPlace(0.5);
  9803. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  9804. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  9805. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  9806. this._worldMatrix = world;
  9807. };
  9808. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  9809. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  9810. };
  9811. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9812. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  9813. };
  9814. BoundingBox.prototype.intersectsPoint = function (point) {
  9815. var delta = -BABYLON.Epsilon;
  9816. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  9817. return false;
  9818. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  9819. return false;
  9820. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  9821. return false;
  9822. return true;
  9823. };
  9824. BoundingBox.prototype.intersectsSphere = function (sphere) {
  9825. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  9826. };
  9827. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  9828. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  9829. return false;
  9830. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  9831. return false;
  9832. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  9833. return false;
  9834. return true;
  9835. };
  9836. // Statics
  9837. BoundingBox.Intersects = function (box0, box1) {
  9838. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  9839. return false;
  9840. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  9841. return false;
  9842. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  9843. return false;
  9844. return true;
  9845. };
  9846. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  9847. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  9848. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  9849. return (num <= (sphereRadius * sphereRadius));
  9850. };
  9851. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  9852. for (var p = 0; p < 6; p++) {
  9853. for (var i = 0; i < 8; i++) {
  9854. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9855. return false;
  9856. }
  9857. }
  9858. }
  9859. return true;
  9860. };
  9861. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  9862. for (var p = 0; p < 6; p++) {
  9863. var inCount = 8;
  9864. for (var i = 0; i < 8; i++) {
  9865. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  9866. --inCount;
  9867. }
  9868. else {
  9869. break;
  9870. }
  9871. }
  9872. if (inCount === 0)
  9873. return false;
  9874. }
  9875. return true;
  9876. };
  9877. return BoundingBox;
  9878. }());
  9879. BABYLON.BoundingBox = BoundingBox;
  9880. })(BABYLON || (BABYLON = {}));
  9881. //# sourceMappingURL=babylon.boundingBox.js.map
  9882. var BABYLON;
  9883. (function (BABYLON) {
  9884. var computeBoxExtents = function (axis, box) {
  9885. var p = BABYLON.Vector3.Dot(box.center, axis);
  9886. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  9887. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  9888. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  9889. var r = r0 + r1 + r2;
  9890. return {
  9891. min: p - r,
  9892. max: p + r
  9893. };
  9894. };
  9895. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  9896. var axisOverlap = function (axis, box0, box1) {
  9897. var result0 = computeBoxExtents(axis, box0);
  9898. var result1 = computeBoxExtents(axis, box1);
  9899. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  9900. };
  9901. var BoundingInfo = (function () {
  9902. function BoundingInfo(minimum, maximum) {
  9903. this.minimum = minimum;
  9904. this.maximum = maximum;
  9905. this._isLocked = false;
  9906. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  9907. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  9908. }
  9909. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  9910. get: function () {
  9911. return this._isLocked;
  9912. },
  9913. set: function (value) {
  9914. this._isLocked = value;
  9915. },
  9916. enumerable: true,
  9917. configurable: true
  9918. });
  9919. // Methods
  9920. BoundingInfo.prototype.update = function (world) {
  9921. if (this._isLocked) {
  9922. return;
  9923. }
  9924. this.boundingBox._update(world);
  9925. this.boundingSphere._update(world);
  9926. };
  9927. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  9928. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  9929. return false;
  9930. return this.boundingBox.isInFrustum(frustumPlanes);
  9931. };
  9932. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  9933. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  9934. };
  9935. BoundingInfo.prototype._checkCollision = function (collider) {
  9936. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  9937. };
  9938. BoundingInfo.prototype.intersectsPoint = function (point) {
  9939. if (!this.boundingSphere.centerWorld) {
  9940. return false;
  9941. }
  9942. if (!this.boundingSphere.intersectsPoint(point)) {
  9943. return false;
  9944. }
  9945. if (!this.boundingBox.intersectsPoint(point)) {
  9946. return false;
  9947. }
  9948. return true;
  9949. };
  9950. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  9951. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  9952. return false;
  9953. }
  9954. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  9955. return false;
  9956. }
  9957. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  9958. return false;
  9959. }
  9960. if (!precise) {
  9961. return true;
  9962. }
  9963. var box0 = this.boundingBox;
  9964. var box1 = boundingInfo.boundingBox;
  9965. if (!axisOverlap(box0.directions[0], box0, box1))
  9966. return false;
  9967. if (!axisOverlap(box0.directions[1], box0, box1))
  9968. return false;
  9969. if (!axisOverlap(box0.directions[2], box0, box1))
  9970. return false;
  9971. if (!axisOverlap(box1.directions[0], box0, box1))
  9972. return false;
  9973. if (!axisOverlap(box1.directions[1], box0, box1))
  9974. return false;
  9975. if (!axisOverlap(box1.directions[2], box0, box1))
  9976. return false;
  9977. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  9978. return false;
  9979. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  9980. return false;
  9981. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  9982. return false;
  9983. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  9984. return false;
  9985. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  9986. return false;
  9987. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  9988. return false;
  9989. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  9990. return false;
  9991. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  9992. return false;
  9993. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  9994. return false;
  9995. return true;
  9996. };
  9997. return BoundingInfo;
  9998. }());
  9999. BABYLON.BoundingInfo = BoundingInfo;
  10000. })(BABYLON || (BABYLON = {}));
  10001. //# sourceMappingURL=babylon.boundingInfo.js.map
  10002. var BABYLON;
  10003. (function (BABYLON) {
  10004. var Ray = (function () {
  10005. function Ray(origin, direction, length) {
  10006. if (length === void 0) { length = Number.MAX_VALUE; }
  10007. this.origin = origin;
  10008. this.direction = direction;
  10009. this.length = length;
  10010. this._show = false;
  10011. }
  10012. // Methods
  10013. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  10014. var d = 0.0;
  10015. var maxValue = Number.MAX_VALUE;
  10016. var inv;
  10017. var min;
  10018. var max;
  10019. var temp;
  10020. if (Math.abs(this.direction.x) < 0.0000001) {
  10021. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  10022. return false;
  10023. }
  10024. }
  10025. else {
  10026. inv = 1.0 / this.direction.x;
  10027. min = (minimum.x - this.origin.x) * inv;
  10028. max = (maximum.x - this.origin.x) * inv;
  10029. if (max === -Infinity) {
  10030. max = Infinity;
  10031. }
  10032. if (min > max) {
  10033. temp = min;
  10034. min = max;
  10035. max = temp;
  10036. }
  10037. d = Math.max(min, d);
  10038. maxValue = Math.min(max, maxValue);
  10039. if (d > maxValue) {
  10040. return false;
  10041. }
  10042. }
  10043. if (Math.abs(this.direction.y) < 0.0000001) {
  10044. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  10045. return false;
  10046. }
  10047. }
  10048. else {
  10049. inv = 1.0 / this.direction.y;
  10050. min = (minimum.y - this.origin.y) * inv;
  10051. max = (maximum.y - this.origin.y) * inv;
  10052. if (max === -Infinity) {
  10053. max = Infinity;
  10054. }
  10055. if (min > max) {
  10056. temp = min;
  10057. min = max;
  10058. max = temp;
  10059. }
  10060. d = Math.max(min, d);
  10061. maxValue = Math.min(max, maxValue);
  10062. if (d > maxValue) {
  10063. return false;
  10064. }
  10065. }
  10066. if (Math.abs(this.direction.z) < 0.0000001) {
  10067. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  10068. return false;
  10069. }
  10070. }
  10071. else {
  10072. inv = 1.0 / this.direction.z;
  10073. min = (minimum.z - this.origin.z) * inv;
  10074. max = (maximum.z - this.origin.z) * inv;
  10075. if (max === -Infinity) {
  10076. max = Infinity;
  10077. }
  10078. if (min > max) {
  10079. temp = min;
  10080. min = max;
  10081. max = temp;
  10082. }
  10083. d = Math.max(min, d);
  10084. maxValue = Math.min(max, maxValue);
  10085. if (d > maxValue) {
  10086. return false;
  10087. }
  10088. }
  10089. return true;
  10090. };
  10091. Ray.prototype.intersectsBox = function (box) {
  10092. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  10093. };
  10094. Ray.prototype.intersectsSphere = function (sphere) {
  10095. var x = sphere.center.x - this.origin.x;
  10096. var y = sphere.center.y - this.origin.y;
  10097. var z = sphere.center.z - this.origin.z;
  10098. var pyth = (x * x) + (y * y) + (z * z);
  10099. var rr = sphere.radius * sphere.radius;
  10100. if (pyth <= rr) {
  10101. return true;
  10102. }
  10103. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  10104. if (dot < 0.0) {
  10105. return false;
  10106. }
  10107. var temp = pyth - (dot * dot);
  10108. return temp <= rr;
  10109. };
  10110. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  10111. if (!this._edge1) {
  10112. this._edge1 = BABYLON.Vector3.Zero();
  10113. this._edge2 = BABYLON.Vector3.Zero();
  10114. this._pvec = BABYLON.Vector3.Zero();
  10115. this._tvec = BABYLON.Vector3.Zero();
  10116. this._qvec = BABYLON.Vector3.Zero();
  10117. }
  10118. vertex1.subtractToRef(vertex0, this._edge1);
  10119. vertex2.subtractToRef(vertex0, this._edge2);
  10120. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  10121. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  10122. if (det === 0) {
  10123. return null;
  10124. }
  10125. var invdet = 1 / det;
  10126. this.origin.subtractToRef(vertex0, this._tvec);
  10127. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  10128. if (bu < 0 || bu > 1.0) {
  10129. return null;
  10130. }
  10131. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  10132. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  10133. if (bv < 0 || bu + bv > 1.0) {
  10134. return null;
  10135. }
  10136. //check if the distance is longer than the predefined length.
  10137. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  10138. if (distance > this.length) {
  10139. return null;
  10140. }
  10141. return new BABYLON.IntersectionInfo(bu, bv, distance);
  10142. };
  10143. Ray.prototype.intersectsPlane = function (plane) {
  10144. var distance;
  10145. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  10146. if (Math.abs(result1) < 9.99999997475243E-07) {
  10147. return null;
  10148. }
  10149. else {
  10150. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  10151. distance = (-plane.d - result2) / result1;
  10152. if (distance < 0.0) {
  10153. if (distance < -9.99999997475243E-07) {
  10154. return null;
  10155. }
  10156. else {
  10157. return 0;
  10158. }
  10159. }
  10160. return distance;
  10161. }
  10162. };
  10163. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  10164. var tm = BABYLON.Tmp.Matrix[0];
  10165. mesh.getWorldMatrix().invertToRef(tm);
  10166. if (this._tmpRay) {
  10167. Ray.TransformToRef(this, tm, this._tmpRay);
  10168. }
  10169. else {
  10170. this._tmpRay = Ray.Transform(this, tm);
  10171. }
  10172. return mesh.intersects(this._tmpRay, fastCheck);
  10173. };
  10174. Ray.prototype.show = function (scene, color) {
  10175. if (!this._show) {
  10176. this._renderFunction = this._render.bind(this);
  10177. this._show = true;
  10178. this._scene = scene;
  10179. this._renderPoints = [this.origin, this.origin.add(this.direction.scale(this.length))];
  10180. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  10181. this._scene.registerBeforeRender(this._renderFunction);
  10182. }
  10183. if (color) {
  10184. this._renderLine.color.copyFrom(color);
  10185. }
  10186. };
  10187. Ray.prototype.hide = function () {
  10188. if (this._show) {
  10189. this._show = false;
  10190. this._scene.unregisterBeforeRender(this._renderFunction);
  10191. }
  10192. if (this._renderLine) {
  10193. this._renderLine.dispose();
  10194. this._renderLine = null;
  10195. this._renderPoints = null;
  10196. }
  10197. };
  10198. Ray.prototype._render = function () {
  10199. var point = this._renderPoints[1];
  10200. point.copyFrom(this.direction);
  10201. point.scaleInPlace(this.length);
  10202. point.addInPlace(this.origin);
  10203. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  10204. };
  10205. /**
  10206. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  10207. * @param sega the first point of the segment to test the intersection against
  10208. * @param segb the second point of the segment to test the intersection against
  10209. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  10210. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  10211. */
  10212. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  10213. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  10214. var u = segb.subtract(sega);
  10215. var v = rsegb.subtract(this.origin);
  10216. var w = sega.subtract(this.origin);
  10217. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  10218. var b = BABYLON.Vector3.Dot(u, v);
  10219. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  10220. var d = BABYLON.Vector3.Dot(u, w);
  10221. var e = BABYLON.Vector3.Dot(v, w);
  10222. var D = a * c - b * b; // always >= 0
  10223. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  10224. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  10225. // compute the line parameters of the two closest points
  10226. if (D < Ray.smallnum) {
  10227. sN = 0.0; // force using point P0 on segment S1
  10228. sD = 1.0; // to prevent possible division by 0.0 later
  10229. tN = e;
  10230. tD = c;
  10231. }
  10232. else {
  10233. sN = (b * e - c * d);
  10234. tN = (a * e - b * d);
  10235. if (sN < 0.0) {
  10236. sN = 0.0;
  10237. tN = e;
  10238. tD = c;
  10239. }
  10240. else if (sN > sD) {
  10241. sN = sD;
  10242. tN = e + b;
  10243. tD = c;
  10244. }
  10245. }
  10246. if (tN < 0.0) {
  10247. tN = 0.0;
  10248. // recompute sc for this edge
  10249. if (-d < 0.0) {
  10250. sN = 0.0;
  10251. }
  10252. else if (-d > a)
  10253. sN = sD;
  10254. else {
  10255. sN = -d;
  10256. sD = a;
  10257. }
  10258. }
  10259. else if (tN > tD) {
  10260. tN = tD;
  10261. // recompute sc for this edge
  10262. if ((-d + b) < 0.0) {
  10263. sN = 0;
  10264. }
  10265. else if ((-d + b) > a) {
  10266. sN = sD;
  10267. }
  10268. else {
  10269. sN = (-d + b);
  10270. sD = a;
  10271. }
  10272. }
  10273. // finally do the division to get sc and tc
  10274. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  10275. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  10276. // get the difference of the two closest points
  10277. var qtc = v.multiplyByFloats(tc, tc, tc);
  10278. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  10279. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  10280. if (isIntersected) {
  10281. return qtc.length();
  10282. }
  10283. return -1;
  10284. };
  10285. // Statics
  10286. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  10287. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  10288. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  10289. var direction = end.subtract(start);
  10290. direction.normalize();
  10291. return new Ray(start, direction);
  10292. };
  10293. /**
  10294. * 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
  10295. * transformed to the given world matrix.
  10296. * @param origin The origin point
  10297. * @param end The end point
  10298. * @param world a matrix to transform the ray to. Default is the identity matrix.
  10299. */
  10300. Ray.CreateNewFromTo = function (origin, end, world) {
  10301. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  10302. var direction = end.subtract(origin);
  10303. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  10304. direction.normalize();
  10305. return Ray.Transform(new Ray(origin, direction, length), world);
  10306. };
  10307. Ray.Transform = function (ray, matrix) {
  10308. var newOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, matrix);
  10309. var newDirection = BABYLON.Vector3.TransformNormal(ray.direction, matrix);
  10310. newDirection.normalize();
  10311. return new Ray(newOrigin, newDirection, ray.length);
  10312. };
  10313. Ray.TransformToRef = function (ray, matrix, result) {
  10314. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  10315. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  10316. ray.direction.normalize();
  10317. };
  10318. return Ray;
  10319. }());
  10320. Ray.smallnum = 0.00000001;
  10321. Ray.rayl = 10e8;
  10322. BABYLON.Ray = Ray;
  10323. })(BABYLON || (BABYLON = {}));
  10324. //# sourceMappingURL=babylon.ray.js.map
  10325. var BABYLON;
  10326. (function (BABYLON) {
  10327. var AbstractMesh = (function (_super) {
  10328. __extends(AbstractMesh, _super);
  10329. // Constructor
  10330. function AbstractMesh(name, scene) {
  10331. var _this = _super.call(this, name, scene) || this;
  10332. // Events
  10333. /**
  10334. * An event triggered when this mesh collides with another one
  10335. * @type {BABYLON.Observable}
  10336. */
  10337. _this.onCollideObservable = new BABYLON.Observable();
  10338. /**
  10339. * An event triggered when the collision's position changes
  10340. * @type {BABYLON.Observable}
  10341. */
  10342. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  10343. /**
  10344. * An event triggered after the world matrix is updated
  10345. * @type {BABYLON.Observable}
  10346. */
  10347. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  10348. // Properties
  10349. _this.definedFacingForward = true; // orientation for POV movement & rotation
  10350. _this.position = new BABYLON.Vector3(0, 0, 0);
  10351. _this._rotation = new BABYLON.Vector3(0, 0, 0);
  10352. _this._scaling = new BABYLON.Vector3(1, 1, 1);
  10353. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  10354. _this.visibility = 1.0;
  10355. _this.alphaIndex = Number.MAX_VALUE;
  10356. _this.infiniteDistance = false;
  10357. _this.isVisible = true;
  10358. _this.isPickable = true;
  10359. _this.showBoundingBox = false;
  10360. _this.showSubMeshesBoundingBox = false;
  10361. _this.isBlocker = false;
  10362. _this.renderingGroupId = 0;
  10363. _this.receiveShadows = false;
  10364. _this.renderOutline = false;
  10365. _this.outlineColor = BABYLON.Color3.Red();
  10366. _this.outlineWidth = 0.02;
  10367. _this.renderOverlay = false;
  10368. _this.overlayColor = BABYLON.Color3.Red();
  10369. _this.overlayAlpha = 0.5;
  10370. _this.hasVertexAlpha = false;
  10371. _this.useVertexColors = true;
  10372. _this.applyFog = true;
  10373. _this.computeBonesUsingShaders = true;
  10374. _this.scalingDeterminant = 1;
  10375. _this.numBoneInfluencers = 4;
  10376. _this.useOctreeForRenderingSelection = true;
  10377. _this.useOctreeForPicking = true;
  10378. _this.useOctreeForCollisions = true;
  10379. _this.layerMask = 0x0FFFFFFF;
  10380. _this.alwaysSelectAsActiveMesh = false;
  10381. // Collisions
  10382. _this._checkCollisions = false;
  10383. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  10384. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  10385. _this._collider = new BABYLON.Collider();
  10386. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10387. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10388. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  10389. // Edges
  10390. _this.edgesWidth = 1;
  10391. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  10392. // Cache
  10393. _this._localWorld = BABYLON.Matrix.Zero();
  10394. _this._worldMatrix = BABYLON.Matrix.Zero();
  10395. _this._rotateYByPI = BABYLON.Matrix.RotationY(Math.PI);
  10396. _this._absolutePosition = BABYLON.Vector3.Zero();
  10397. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  10398. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  10399. _this._isDirty = false;
  10400. _this._pivotMatrix = BABYLON.Matrix.Identity();
  10401. _this._isDisposed = false;
  10402. _this._renderId = 0;
  10403. _this._intersectionsInProgress = new Array();
  10404. _this._isWorldMatrixFrozen = false;
  10405. _this._unIndexed = false;
  10406. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  10407. if (collidedMesh === void 0) { collidedMesh = null; }
  10408. //TODO move this to the collision coordinator!
  10409. if (_this.getScene().workerCollisions)
  10410. newPosition.multiplyInPlace(_this._collider.radius);
  10411. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  10412. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  10413. _this.position.addInPlace(_this._diffPositionForCollisions);
  10414. }
  10415. if (collidedMesh) {
  10416. _this.onCollideObservable.notifyObservers(collidedMesh);
  10417. }
  10418. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  10419. };
  10420. scene.addMesh(_this);
  10421. return _this;
  10422. }
  10423. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  10424. get: function () {
  10425. return AbstractMesh._BILLBOARDMODE_NONE;
  10426. },
  10427. enumerable: true,
  10428. configurable: true
  10429. });
  10430. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  10431. get: function () {
  10432. return AbstractMesh._BILLBOARDMODE_X;
  10433. },
  10434. enumerable: true,
  10435. configurable: true
  10436. });
  10437. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  10438. get: function () {
  10439. return AbstractMesh._BILLBOARDMODE_Y;
  10440. },
  10441. enumerable: true,
  10442. configurable: true
  10443. });
  10444. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  10445. get: function () {
  10446. return AbstractMesh._BILLBOARDMODE_Z;
  10447. },
  10448. enumerable: true,
  10449. configurable: true
  10450. });
  10451. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  10452. get: function () {
  10453. return AbstractMesh._BILLBOARDMODE_ALL;
  10454. },
  10455. enumerable: true,
  10456. configurable: true
  10457. });
  10458. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  10459. set: function (callback) {
  10460. if (this._onCollideObserver) {
  10461. this.onCollideObservable.remove(this._onCollideObserver);
  10462. }
  10463. this._onCollideObserver = this.onCollideObservable.add(callback);
  10464. },
  10465. enumerable: true,
  10466. configurable: true
  10467. });
  10468. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  10469. set: function (callback) {
  10470. if (this._onCollisionPositionChangeObserver) {
  10471. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  10472. }
  10473. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  10474. },
  10475. enumerable: true,
  10476. configurable: true
  10477. });
  10478. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  10479. get: function () {
  10480. return this._skeleton;
  10481. },
  10482. set: function (value) {
  10483. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  10484. this._skeleton._unregisterMeshWithPoseMatrix(this);
  10485. }
  10486. if (value && value.needInitialSkinMatrix) {
  10487. value._registerMeshWithPoseMatrix(this);
  10488. }
  10489. this._skeleton = value;
  10490. if (!this._skeleton) {
  10491. this._bonesTransformMatrices = null;
  10492. }
  10493. },
  10494. enumerable: true,
  10495. configurable: true
  10496. });
  10497. AbstractMesh.prototype.getClassName = function () {
  10498. return "AbstractMesh";
  10499. };
  10500. /**
  10501. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  10502. */
  10503. AbstractMesh.prototype.toString = function (fullDetails) {
  10504. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  10505. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  10506. if (this._skeleton) {
  10507. ret += ", skeleton: " + this._skeleton.name;
  10508. }
  10509. if (fullDetails) {
  10510. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  10511. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  10512. }
  10513. return ret;
  10514. };
  10515. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  10516. /**
  10517. * Getting the rotation object.
  10518. * If rotation quaternion is set, this vector will (almost always) be the Zero vector!
  10519. */
  10520. get: function () {
  10521. return this._rotation;
  10522. },
  10523. set: function (newRotation) {
  10524. this._rotation = newRotation;
  10525. },
  10526. enumerable: true,
  10527. configurable: true
  10528. });
  10529. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  10530. get: function () {
  10531. return this._scaling;
  10532. },
  10533. set: function (newScaling) {
  10534. this._scaling = newScaling;
  10535. if (this.physicsImpostor) {
  10536. this.physicsImpostor.forceUpdate();
  10537. }
  10538. },
  10539. enumerable: true,
  10540. configurable: true
  10541. });
  10542. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  10543. get: function () {
  10544. return this._rotationQuaternion;
  10545. },
  10546. set: function (quaternion) {
  10547. this._rotationQuaternion = quaternion;
  10548. //reset the rotation vector.
  10549. if (quaternion && this.rotation.length()) {
  10550. this.rotation.copyFromFloats(0, 0, 0);
  10551. }
  10552. },
  10553. enumerable: true,
  10554. configurable: true
  10555. });
  10556. // Methods
  10557. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  10558. this._poseMatrix.copyFrom(matrix);
  10559. };
  10560. AbstractMesh.prototype.getPoseMatrix = function () {
  10561. return this._poseMatrix;
  10562. };
  10563. AbstractMesh.prototype.disableEdgesRendering = function () {
  10564. if (this._edgesRenderer !== undefined) {
  10565. this._edgesRenderer.dispose();
  10566. this._edgesRenderer = undefined;
  10567. }
  10568. };
  10569. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  10570. if (epsilon === void 0) { epsilon = 0.95; }
  10571. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  10572. this.disableEdgesRendering();
  10573. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  10574. };
  10575. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  10576. get: function () {
  10577. return false;
  10578. },
  10579. enumerable: true,
  10580. configurable: true
  10581. });
  10582. AbstractMesh.prototype.getLOD = function (camera) {
  10583. return this;
  10584. };
  10585. AbstractMesh.prototype.getTotalVertices = function () {
  10586. return 0;
  10587. };
  10588. AbstractMesh.prototype.getIndices = function () {
  10589. return null;
  10590. };
  10591. AbstractMesh.prototype.getVerticesData = function (kind) {
  10592. return null;
  10593. };
  10594. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  10595. return false;
  10596. };
  10597. AbstractMesh.prototype.getBoundingInfo = function () {
  10598. if (this._masterMesh) {
  10599. return this._masterMesh.getBoundingInfo();
  10600. }
  10601. if (!this._boundingInfo) {
  10602. this._updateBoundingInfo();
  10603. }
  10604. return this._boundingInfo;
  10605. };
  10606. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  10607. this._boundingInfo = boundingInfo;
  10608. };
  10609. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  10610. get: function () {
  10611. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  10612. },
  10613. enumerable: true,
  10614. configurable: true
  10615. });
  10616. AbstractMesh.prototype._preActivate = function () {
  10617. };
  10618. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  10619. };
  10620. AbstractMesh.prototype._activate = function (renderId) {
  10621. this._renderId = renderId;
  10622. };
  10623. AbstractMesh.prototype.getWorldMatrix = function () {
  10624. if (this._masterMesh) {
  10625. return this._masterMesh.getWorldMatrix();
  10626. }
  10627. if (this._currentRenderId !== this.getScene().getRenderId()) {
  10628. this.computeWorldMatrix();
  10629. }
  10630. return this._worldMatrix;
  10631. };
  10632. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  10633. get: function () {
  10634. return this._worldMatrix;
  10635. },
  10636. enumerable: true,
  10637. configurable: true
  10638. });
  10639. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  10640. get: function () {
  10641. return this._absolutePosition;
  10642. },
  10643. enumerable: true,
  10644. configurable: true
  10645. });
  10646. AbstractMesh.prototype.freezeWorldMatrix = function () {
  10647. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  10648. this.computeWorldMatrix(true);
  10649. this._isWorldMatrixFrozen = true;
  10650. };
  10651. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  10652. this._isWorldMatrixFrozen = false;
  10653. this.computeWorldMatrix(true);
  10654. };
  10655. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  10656. get: function () {
  10657. return this._isWorldMatrixFrozen;
  10658. },
  10659. enumerable: true,
  10660. configurable: true
  10661. });
  10662. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  10663. axis.normalize();
  10664. if (!this.rotationQuaternion) {
  10665. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10666. this.rotation = BABYLON.Vector3.Zero();
  10667. }
  10668. var rotationQuaternion;
  10669. if (!space || space === BABYLON.Space.LOCAL) {
  10670. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10671. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  10672. }
  10673. else {
  10674. if (this.parent) {
  10675. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10676. invertParentWorldMatrix.invert();
  10677. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  10678. }
  10679. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  10680. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  10681. }
  10682. };
  10683. AbstractMesh.prototype.translate = function (axis, distance, space) {
  10684. var displacementVector = axis.scale(distance);
  10685. if (!space || space === BABYLON.Space.LOCAL) {
  10686. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  10687. this.setPositionWithLocalVector(tempV3);
  10688. }
  10689. else {
  10690. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  10691. }
  10692. };
  10693. AbstractMesh.prototype.getAbsolutePosition = function () {
  10694. this.computeWorldMatrix();
  10695. return this._absolutePosition;
  10696. };
  10697. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  10698. if (!absolutePosition) {
  10699. return;
  10700. }
  10701. var absolutePositionX;
  10702. var absolutePositionY;
  10703. var absolutePositionZ;
  10704. if (absolutePosition.x === undefined) {
  10705. if (arguments.length < 3) {
  10706. return;
  10707. }
  10708. absolutePositionX = arguments[0];
  10709. absolutePositionY = arguments[1];
  10710. absolutePositionZ = arguments[2];
  10711. }
  10712. else {
  10713. absolutePositionX = absolutePosition.x;
  10714. absolutePositionY = absolutePosition.y;
  10715. absolutePositionZ = absolutePosition.z;
  10716. }
  10717. if (this.parent) {
  10718. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  10719. invertParentWorldMatrix.invert();
  10720. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  10721. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  10722. }
  10723. else {
  10724. this.position.x = absolutePositionX;
  10725. this.position.y = absolutePositionY;
  10726. this.position.z = absolutePositionZ;
  10727. }
  10728. };
  10729. // ================================== Point of View Movement =================================
  10730. /**
  10731. * Perform relative position change from the point of view of behind the front of the mesh.
  10732. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10733. * Supports definition of mesh facing forward or backward.
  10734. * @param {number} amountRight
  10735. * @param {number} amountUp
  10736. * @param {number} amountForward
  10737. */
  10738. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  10739. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  10740. };
  10741. /**
  10742. * Calculate relative position change from the point of view of behind the front of the mesh.
  10743. * This is performed taking into account the meshes current rotation, so you do not have to care.
  10744. * Supports definition of mesh facing forward or backward.
  10745. * @param {number} amountRight
  10746. * @param {number} amountUp
  10747. * @param {number} amountForward
  10748. */
  10749. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  10750. var rotMatrix = new BABYLON.Matrix();
  10751. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  10752. rotQuaternion.toRotationMatrix(rotMatrix);
  10753. var translationDelta = BABYLON.Vector3.Zero();
  10754. var defForwardMult = this.definedFacingForward ? -1 : 1;
  10755. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  10756. return translationDelta;
  10757. };
  10758. // ================================== Point of View Rotation =================================
  10759. /**
  10760. * Perform relative rotation change from the point of view of behind the front of the mesh.
  10761. * Supports definition of mesh facing forward or backward.
  10762. * @param {number} flipBack
  10763. * @param {number} twirlClockwise
  10764. * @param {number} tiltRight
  10765. */
  10766. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10767. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  10768. };
  10769. /**
  10770. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  10771. * Supports definition of mesh facing forward or backward.
  10772. * @param {number} flipBack
  10773. * @param {number} twirlClockwise
  10774. * @param {number} tiltRight
  10775. */
  10776. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  10777. var defForwardMult = this.definedFacingForward ? 1 : -1;
  10778. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  10779. };
  10780. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  10781. this._pivotMatrix = matrix;
  10782. this._cache.pivotMatrixUpdated = true;
  10783. };
  10784. AbstractMesh.prototype.getPivotMatrix = function () {
  10785. return this._pivotMatrix;
  10786. };
  10787. AbstractMesh.prototype._isSynchronized = function () {
  10788. if (this._isDirty) {
  10789. return false;
  10790. }
  10791. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  10792. return false;
  10793. if (this._cache.pivotMatrixUpdated) {
  10794. return false;
  10795. }
  10796. if (this.infiniteDistance) {
  10797. return false;
  10798. }
  10799. if (!this._cache.position.equals(this.position))
  10800. return false;
  10801. if (this.rotationQuaternion) {
  10802. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  10803. return false;
  10804. }
  10805. if (!this._cache.rotation.equals(this.rotation))
  10806. return false;
  10807. if (!this._cache.scaling.equals(this.scaling))
  10808. return false;
  10809. return true;
  10810. };
  10811. AbstractMesh.prototype._initCache = function () {
  10812. _super.prototype._initCache.call(this);
  10813. this._cache.localMatrixUpdated = false;
  10814. this._cache.position = BABYLON.Vector3.Zero();
  10815. this._cache.scaling = BABYLON.Vector3.Zero();
  10816. this._cache.rotation = BABYLON.Vector3.Zero();
  10817. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  10818. this._cache.billboardMode = -1;
  10819. };
  10820. AbstractMesh.prototype.markAsDirty = function (property) {
  10821. if (property === "rotation") {
  10822. this.rotationQuaternion = null;
  10823. }
  10824. this._currentRenderId = Number.MAX_VALUE;
  10825. this._isDirty = true;
  10826. };
  10827. AbstractMesh.prototype._updateBoundingInfo = function () {
  10828. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  10829. this._boundingInfo.update(this.worldMatrixFromCache);
  10830. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  10831. };
  10832. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  10833. if (!this.subMeshes) {
  10834. return;
  10835. }
  10836. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  10837. var subMesh = this.subMeshes[subIndex];
  10838. if (!subMesh.IsGlobal) {
  10839. subMesh.updateBoundingInfo(matrix);
  10840. }
  10841. }
  10842. };
  10843. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  10844. if (this._isWorldMatrixFrozen) {
  10845. return this._worldMatrix;
  10846. }
  10847. if (!force && (this._currentRenderId === this.getScene().getRenderId() || this.isSynchronized(true))) {
  10848. this._currentRenderId = this.getScene().getRenderId();
  10849. return this._worldMatrix;
  10850. }
  10851. this._cache.position.copyFrom(this.position);
  10852. this._cache.scaling.copyFrom(this.scaling);
  10853. this._cache.pivotMatrixUpdated = false;
  10854. this._cache.billboardMode = this.billboardMode;
  10855. this._currentRenderId = this.getScene().getRenderId();
  10856. this._isDirty = false;
  10857. // Scaling
  10858. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  10859. // Rotation
  10860. //rotate, if quaternion is set and rotation was used
  10861. if (this.rotationQuaternion) {
  10862. var len = this.rotation.length();
  10863. if (len) {
  10864. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  10865. this.rotation.copyFromFloats(0, 0, 0);
  10866. }
  10867. }
  10868. if (this.rotationQuaternion) {
  10869. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  10870. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  10871. }
  10872. else {
  10873. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  10874. this._cache.rotation.copyFrom(this.rotation);
  10875. }
  10876. // Translation
  10877. if (this.infiniteDistance && !this.parent) {
  10878. var camera = this.getScene().activeCamera;
  10879. if (camera) {
  10880. var cameraWorldMatrix = camera.getWorldMatrix();
  10881. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  10882. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  10883. }
  10884. }
  10885. else {
  10886. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  10887. }
  10888. // Composing transformations
  10889. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  10890. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  10891. // Billboarding
  10892. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  10893. BABYLON.Tmp.Vector3[0].copyFrom(this.position);
  10894. var localPosition = BABYLON.Tmp.Vector3[0];
  10895. if (this.parent && this.parent.getWorldMatrix) {
  10896. this._markSyncedWithParent();
  10897. var parentMatrix;
  10898. if (this._meshToBoneReferal) {
  10899. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10900. parentMatrix = BABYLON.Tmp.Matrix[6];
  10901. }
  10902. else {
  10903. parentMatrix = this.parent.getWorldMatrix();
  10904. }
  10905. BABYLON.Vector3.TransformNormalToRef(localPosition, parentMatrix, BABYLON.Tmp.Vector3[1]);
  10906. localPosition = BABYLON.Tmp.Vector3[1];
  10907. }
  10908. var zero = this.getScene().activeCamera.globalPosition.clone();
  10909. if (this.parent && this.parent.position) {
  10910. localPosition.addInPlace(this.parent.position);
  10911. BABYLON.Matrix.TranslationToRef(localPosition.x, localPosition.y, localPosition.z, BABYLON.Tmp.Matrix[2]);
  10912. }
  10913. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  10914. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_X)
  10915. zero.x = localPosition.x + BABYLON.Epsilon;
  10916. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Y)
  10917. zero.y = localPosition.y + BABYLON.Epsilon;
  10918. if (this.billboardMode & AbstractMesh.BILLBOARDMODE_Z)
  10919. zero.z = localPosition.z + BABYLON.Epsilon;
  10920. }
  10921. BABYLON.Matrix.LookAtLHToRef(localPosition, zero, BABYLON.Vector3.Up(), BABYLON.Tmp.Matrix[3]);
  10922. BABYLON.Tmp.Matrix[3].m[12] = BABYLON.Tmp.Matrix[3].m[13] = BABYLON.Tmp.Matrix[3].m[14] = 0;
  10923. BABYLON.Tmp.Matrix[3].invert();
  10924. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[3], this._localWorld);
  10925. this._rotateYByPI.multiplyToRef(this._localWorld, BABYLON.Tmp.Matrix[5]);
  10926. }
  10927. // Local world
  10928. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  10929. // Parent
  10930. if (this.parent && this.parent.getWorldMatrix && this.billboardMode === AbstractMesh.BILLBOARDMODE_NONE) {
  10931. this._markSyncedWithParent();
  10932. if (this._meshToBoneReferal) {
  10933. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  10934. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  10935. }
  10936. else {
  10937. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  10938. }
  10939. }
  10940. else {
  10941. this._worldMatrix.copyFrom(this._localWorld);
  10942. }
  10943. // Bounding info
  10944. this._updateBoundingInfo();
  10945. // Absolute position
  10946. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  10947. // Callbacks
  10948. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  10949. if (!this._poseMatrix) {
  10950. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  10951. }
  10952. return this._worldMatrix;
  10953. };
  10954. /**
  10955. * If you'd like to be callbacked after the mesh position, rotation or scaling has been updated
  10956. * @param func: callback function to add
  10957. */
  10958. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  10959. this.onAfterWorldMatrixUpdateObservable.add(func);
  10960. };
  10961. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  10962. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  10963. };
  10964. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  10965. this.computeWorldMatrix();
  10966. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  10967. };
  10968. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  10969. this.computeWorldMatrix();
  10970. var invLocalWorldMatrix = this._localWorld.clone();
  10971. invLocalWorldMatrix.invert();
  10972. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  10973. };
  10974. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  10975. this.computeWorldMatrix(true);
  10976. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  10977. };
  10978. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  10979. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  10980. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  10981. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  10982. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  10983. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  10984. /// <returns>Mesh oriented towards targetMesh</returns>
  10985. if (yawCor === void 0) { yawCor = 0; }
  10986. if (pitchCor === void 0) { pitchCor = 0; }
  10987. if (rollCor === void 0) { rollCor = 0; }
  10988. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  10989. var dv = AbstractMesh._lookAtVectorCache;
  10990. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  10991. targetPoint.subtractToRef(pos, dv);
  10992. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  10993. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  10994. var pitch = Math.atan2(dv.y, len);
  10995. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  10996. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  10997. };
  10998. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  10999. this._meshToBoneReferal = affectedMesh;
  11000. this.parent = bone;
  11001. if (bone.getWorldMatrix().determinant() < 0) {
  11002. this.scalingDeterminant *= -1;
  11003. }
  11004. };
  11005. AbstractMesh.prototype.detachFromBone = function () {
  11006. if (this.parent.getWorldMatrix().determinant() < 0) {
  11007. this.scalingDeterminant *= -1;
  11008. }
  11009. this._meshToBoneReferal = null;
  11010. this.parent = null;
  11011. };
  11012. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  11013. return this._boundingInfo.isInFrustum(frustumPlanes);
  11014. };
  11015. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11016. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  11017. ;
  11018. };
  11019. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  11020. if (!this._boundingInfo || !mesh._boundingInfo) {
  11021. return false;
  11022. }
  11023. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  11024. };
  11025. AbstractMesh.prototype.intersectsPoint = function (point) {
  11026. if (!this._boundingInfo) {
  11027. return false;
  11028. }
  11029. return this._boundingInfo.intersectsPoint(point);
  11030. };
  11031. // Physics
  11032. /**
  11033. * @Deprecated. Use new PhysicsImpostor instead.
  11034. * */
  11035. AbstractMesh.prototype.setPhysicsState = function (impostor, options) {
  11036. //legacy support
  11037. if (impostor.impostor) {
  11038. options = impostor;
  11039. impostor = impostor.impostor;
  11040. }
  11041. this.physicsImpostor = new BABYLON.PhysicsImpostor(this, impostor, options, this.getScene());
  11042. return this.physicsImpostor.physicsBody;
  11043. };
  11044. AbstractMesh.prototype.getPhysicsImpostor = function () {
  11045. return this.physicsImpostor;
  11046. };
  11047. /**
  11048. * @Deprecated. Use getPhysicsImpostor().getParam("mass");
  11049. */
  11050. AbstractMesh.prototype.getPhysicsMass = function () {
  11051. return this.physicsImpostor.getParam("mass");
  11052. };
  11053. /**
  11054. * @Deprecated. Use getPhysicsImpostor().getParam("friction");
  11055. */
  11056. AbstractMesh.prototype.getPhysicsFriction = function () {
  11057. return this.physicsImpostor.getParam("friction");
  11058. };
  11059. /**
  11060. * @Deprecated. Use getPhysicsImpostor().getParam("restitution");
  11061. */
  11062. AbstractMesh.prototype.getPhysicsRestitution = function () {
  11063. return this.physicsImpostor.getParam("restitution");
  11064. };
  11065. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  11066. if (!camera) {
  11067. camera = this.getScene().activeCamera;
  11068. }
  11069. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  11070. };
  11071. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  11072. if (!camera) {
  11073. camera = this.getScene().activeCamera;
  11074. }
  11075. return this.absolutePosition.subtract(camera.position).length();
  11076. };
  11077. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  11078. if (!this.physicsImpostor) {
  11079. return;
  11080. }
  11081. this.physicsImpostor.applyImpulse(force, contactPoint);
  11082. };
  11083. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  11084. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  11085. return;
  11086. }
  11087. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  11088. mainPivot: pivot1,
  11089. connectedPivot: pivot2,
  11090. nativeParams: options
  11091. });
  11092. };
  11093. /**
  11094. * @Deprecated
  11095. */
  11096. AbstractMesh.prototype.updatePhysicsBodyPosition = function () {
  11097. BABYLON.Tools.Warn("updatePhysicsBodyPosition() is deprecated, please use updatePhysicsBody()");
  11098. this.updatePhysicsBody();
  11099. };
  11100. /**
  11101. * @Deprecated
  11102. * Calling this function is not needed anymore.
  11103. * The physics engine takes care of transofmration automatically.
  11104. */
  11105. AbstractMesh.prototype.updatePhysicsBody = function () {
  11106. //Unneeded
  11107. };
  11108. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  11109. // Collisions
  11110. get: function () {
  11111. return this._checkCollisions;
  11112. },
  11113. set: function (collisionEnabled) {
  11114. this._checkCollisions = collisionEnabled;
  11115. if (this.getScene().workerCollisions) {
  11116. this.getScene().collisionCoordinator.onMeshUpdated(this);
  11117. }
  11118. },
  11119. enumerable: true,
  11120. configurable: true
  11121. });
  11122. AbstractMesh.prototype.moveWithCollisions = function (velocity) {
  11123. var globalPosition = this.getAbsolutePosition();
  11124. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  11125. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  11126. this._collider.radius = this.ellipsoid;
  11127. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, velocity, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  11128. };
  11129. // Submeshes octree
  11130. /**
  11131. * This function will create an octree to help select the right submeshes for rendering, picking and collisions
  11132. * Please note that you must have a decent number of submeshes to get performance improvements when using octree
  11133. */
  11134. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  11135. if (maxCapacity === void 0) { maxCapacity = 64; }
  11136. if (maxDepth === void 0) { maxDepth = 2; }
  11137. if (!this._submeshesOctree) {
  11138. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  11139. }
  11140. this.computeWorldMatrix(true);
  11141. // Update octree
  11142. var bbox = this.getBoundingInfo().boundingBox;
  11143. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  11144. return this._submeshesOctree;
  11145. };
  11146. // Collisions
  11147. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  11148. this._generatePointsArray();
  11149. // Transformation
  11150. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  11151. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  11152. subMesh._lastColliderWorldVertices = [];
  11153. subMesh._trianglePlanes = [];
  11154. var start = subMesh.verticesStart;
  11155. var end = (subMesh.verticesStart + subMesh.verticesCount);
  11156. for (var i = start; i < end; i++) {
  11157. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  11158. }
  11159. }
  11160. // Collide
  11161. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  11162. if (collider.collisionFound) {
  11163. collider.collidedMesh = this;
  11164. }
  11165. };
  11166. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  11167. var subMeshes;
  11168. var len;
  11169. // Octrees
  11170. if (this._submeshesOctree && this.useOctreeForCollisions) {
  11171. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  11172. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  11173. len = intersections.length;
  11174. subMeshes = intersections.data;
  11175. }
  11176. else {
  11177. subMeshes = this.subMeshes;
  11178. len = subMeshes.length;
  11179. }
  11180. for (var index = 0; index < len; index++) {
  11181. var subMesh = subMeshes[index];
  11182. // Bounding test
  11183. if (len > 1 && !subMesh._checkCollision(collider))
  11184. continue;
  11185. this._collideForSubMesh(subMesh, transformMatrix, collider);
  11186. }
  11187. };
  11188. AbstractMesh.prototype._checkCollision = function (collider) {
  11189. // Bounding box test
  11190. if (!this._boundingInfo._checkCollision(collider))
  11191. return;
  11192. // Transformation matrix
  11193. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  11194. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  11195. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  11196. };
  11197. // Picking
  11198. AbstractMesh.prototype._generatePointsArray = function () {
  11199. return false;
  11200. };
  11201. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  11202. var pickingInfo = new BABYLON.PickingInfo();
  11203. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  11204. return pickingInfo;
  11205. }
  11206. if (!this._generatePointsArray()) {
  11207. return pickingInfo;
  11208. }
  11209. var intersectInfo = null;
  11210. // Octrees
  11211. var subMeshes;
  11212. var len;
  11213. if (this._submeshesOctree && this.useOctreeForPicking) {
  11214. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  11215. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  11216. len = intersections.length;
  11217. subMeshes = intersections.data;
  11218. }
  11219. else {
  11220. subMeshes = this.subMeshes;
  11221. len = subMeshes.length;
  11222. }
  11223. for (var index = 0; index < len; index++) {
  11224. var subMesh = subMeshes[index];
  11225. // Bounding test
  11226. if (len > 1 && !subMesh.canIntersects(ray))
  11227. continue;
  11228. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  11229. if (currentIntersectInfo) {
  11230. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  11231. intersectInfo = currentIntersectInfo;
  11232. intersectInfo.subMeshId = index;
  11233. if (fastCheck) {
  11234. break;
  11235. }
  11236. }
  11237. }
  11238. }
  11239. if (intersectInfo) {
  11240. // Get picked point
  11241. var world = this.getWorldMatrix();
  11242. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  11243. var direction = ray.direction.clone();
  11244. direction = direction.scale(intersectInfo.distance);
  11245. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  11246. var pickedPoint = worldOrigin.add(worldDirection);
  11247. // Return result
  11248. pickingInfo.hit = true;
  11249. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  11250. pickingInfo.pickedPoint = pickedPoint;
  11251. pickingInfo.pickedMesh = this;
  11252. pickingInfo.bu = intersectInfo.bu;
  11253. pickingInfo.bv = intersectInfo.bv;
  11254. pickingInfo.faceId = intersectInfo.faceId;
  11255. pickingInfo.subMeshId = intersectInfo.subMeshId;
  11256. return pickingInfo;
  11257. }
  11258. return pickingInfo;
  11259. };
  11260. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  11261. return null;
  11262. };
  11263. AbstractMesh.prototype.releaseSubMeshes = function () {
  11264. if (this.subMeshes) {
  11265. while (this.subMeshes.length) {
  11266. this.subMeshes[0].dispose();
  11267. }
  11268. }
  11269. else {
  11270. this.subMeshes = new Array();
  11271. }
  11272. };
  11273. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  11274. var _this = this;
  11275. var index;
  11276. // Action manager
  11277. if (this.actionManager) {
  11278. this.actionManager.dispose();
  11279. this.actionManager = null;
  11280. }
  11281. // Skeleton
  11282. this.skeleton = null;
  11283. // Animations
  11284. this.getScene().stopAnimation(this);
  11285. // Physics
  11286. if (this.physicsImpostor) {
  11287. this.physicsImpostor.dispose();
  11288. }
  11289. // Intersections in progress
  11290. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  11291. var other = this._intersectionsInProgress[index];
  11292. var pos = other._intersectionsInProgress.indexOf(this);
  11293. other._intersectionsInProgress.splice(pos, 1);
  11294. }
  11295. this._intersectionsInProgress = [];
  11296. // Lights
  11297. var lights = this.getScene().lights;
  11298. lights.forEach(function (light) {
  11299. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  11300. if (meshIndex !== -1) {
  11301. light.includedOnlyMeshes.splice(meshIndex, 1);
  11302. }
  11303. meshIndex = light.excludedMeshes.indexOf(_this);
  11304. if (meshIndex !== -1) {
  11305. light.excludedMeshes.splice(meshIndex, 1);
  11306. }
  11307. // Shadow generators
  11308. var generator = light.getShadowGenerator();
  11309. if (generator) {
  11310. meshIndex = generator.getShadowMap().renderList.indexOf(_this);
  11311. if (meshIndex !== -1) {
  11312. generator.getShadowMap().renderList.splice(meshIndex, 1);
  11313. }
  11314. }
  11315. });
  11316. // Edges
  11317. if (this._edgesRenderer) {
  11318. this._edgesRenderer.dispose();
  11319. this._edgesRenderer = null;
  11320. }
  11321. // SubMeshes
  11322. this.releaseSubMeshes();
  11323. // Engine
  11324. this.getScene().getEngine().unbindAllAttributes();
  11325. this.getScene().getEngine().wipeCaches();
  11326. // Remove from scene
  11327. this.getScene().removeMesh(this);
  11328. if (!doNotRecurse) {
  11329. // Particles
  11330. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  11331. if (this.getScene().particleSystems[index].emitter === this) {
  11332. this.getScene().particleSystems[index].dispose();
  11333. index--;
  11334. }
  11335. }
  11336. // Children
  11337. var objects = this.getDescendants(true);
  11338. for (index = 0; index < objects.length; index++) {
  11339. objects[index].dispose();
  11340. }
  11341. }
  11342. else {
  11343. var childMeshes = this.getChildMeshes(true);
  11344. for (index = 0; index < childMeshes.length; index++) {
  11345. var child = childMeshes[index];
  11346. child.parent = null;
  11347. child.computeWorldMatrix(true);
  11348. }
  11349. }
  11350. this.onAfterWorldMatrixUpdateObservable.clear();
  11351. this.onCollideObservable.clear();
  11352. this.onCollisionPositionChangeObservable.clear();
  11353. this._isDisposed = true;
  11354. _super.prototype.dispose.call(this);
  11355. };
  11356. AbstractMesh.prototype.getDirection = function (localAxis) {
  11357. var result = BABYLON.Vector3.Zero();
  11358. this.getDirectionToRef(localAxis, result);
  11359. return result;
  11360. };
  11361. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  11362. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  11363. };
  11364. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  11365. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  11366. if (this.getScene().getRenderId() == 0) {
  11367. this.computeWorldMatrix(true);
  11368. }
  11369. var wm = this.getWorldMatrix();
  11370. if (space == BABYLON.Space.WORLD) {
  11371. var tmat = BABYLON.Tmp.Matrix[0];
  11372. wm.invertToRef(tmat);
  11373. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  11374. }
  11375. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  11376. this._pivotMatrix.m[12] = -point.x;
  11377. this._pivotMatrix.m[13] = -point.y;
  11378. this._pivotMatrix.m[14] = -point.z;
  11379. this._cache.pivotMatrixUpdated = true;
  11380. };
  11381. AbstractMesh.prototype.getPivotPoint = function () {
  11382. var point = BABYLON.Vector3.Zero();
  11383. this.getPivotPointToRef(point);
  11384. return point;
  11385. };
  11386. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  11387. result.x = -this._pivotMatrix.m[12];
  11388. result.y = -this._pivotMatrix.m[13];
  11389. result.z = -this._pivotMatrix.m[14];
  11390. };
  11391. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  11392. var point = BABYLON.Vector3.Zero();
  11393. this.getAbsolutePivotPointToRef(point);
  11394. return point;
  11395. };
  11396. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  11397. result.x = this._pivotMatrix.m[12];
  11398. result.y = this._pivotMatrix.m[13];
  11399. result.z = this._pivotMatrix.m[14];
  11400. this.getPivotPointToRef(result);
  11401. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  11402. };
  11403. return AbstractMesh;
  11404. }(BABYLON.Node));
  11405. // Statics
  11406. AbstractMesh._BILLBOARDMODE_NONE = 0;
  11407. AbstractMesh._BILLBOARDMODE_X = 1;
  11408. AbstractMesh._BILLBOARDMODE_Y = 2;
  11409. AbstractMesh._BILLBOARDMODE_Z = 4;
  11410. AbstractMesh._BILLBOARDMODE_ALL = 7;
  11411. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  11412. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  11413. BABYLON.AbstractMesh = AbstractMesh;
  11414. })(BABYLON || (BABYLON = {}));
  11415. //# sourceMappingURL=babylon.abstractMesh.js.map
  11416. var BABYLON;
  11417. (function (BABYLON) {
  11418. var Light = (function (_super) {
  11419. __extends(Light, _super);
  11420. function Light(name, scene) {
  11421. var _this = _super.call(this, name, scene) || this;
  11422. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  11423. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  11424. _this.intensity = 1.0;
  11425. _this.range = Number.MAX_VALUE;
  11426. _this.includeOnlyWithLayerMask = 0;
  11427. _this.includedOnlyMeshes = new Array();
  11428. _this.excludedMeshes = new Array();
  11429. _this.excludeWithLayerMask = 0;
  11430. _this.lightmapMode = 0;
  11431. // PBR Properties.
  11432. _this.radius = 0.00001;
  11433. _this._excludedMeshesIds = new Array();
  11434. _this._includedOnlyMeshesIds = new Array();
  11435. scene.addLight(_this);
  11436. return _this;
  11437. }
  11438. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  11439. /**
  11440. * If every light affecting the material is in this lightmapMode,
  11441. * material.lightmapTexture adds or multiplies
  11442. * (depends on material.useLightmapAsShadowmap)
  11443. * after every other light calculations.
  11444. */
  11445. get: function () {
  11446. return Light._LIGHTMAP_DEFAULT;
  11447. },
  11448. enumerable: true,
  11449. configurable: true
  11450. });
  11451. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  11452. /**
  11453. * material.lightmapTexture as only diffuse lighting from this light
  11454. * adds pnly specular lighting from this light
  11455. * adds dynamic shadows
  11456. */
  11457. get: function () {
  11458. return Light._LIGHTMAP_SPECULAR;
  11459. },
  11460. enumerable: true,
  11461. configurable: true
  11462. });
  11463. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  11464. /**
  11465. * material.lightmapTexture as only lighting
  11466. * no light calculation from this light
  11467. * only adds dynamic shadows from this light
  11468. */
  11469. get: function () {
  11470. return Light._LIGHTMAP_SHADOWSONLY;
  11471. },
  11472. enumerable: true,
  11473. configurable: true
  11474. });
  11475. Light.prototype.getClassName = function () {
  11476. return "Light";
  11477. };
  11478. /**
  11479. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  11480. */
  11481. Light.prototype.toString = function (fullDetails) {
  11482. var ret = "Name: " + this.name;
  11483. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  11484. if (this.animations) {
  11485. for (var i = 0; i < this.animations.length; i++) {
  11486. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  11487. }
  11488. }
  11489. if (fullDetails) {
  11490. }
  11491. return ret;
  11492. };
  11493. Light.prototype.getShadowGenerator = function () {
  11494. return this._shadowGenerator;
  11495. };
  11496. Light.prototype.getAbsolutePosition = function () {
  11497. return BABYLON.Vector3.Zero();
  11498. };
  11499. Light.prototype.transferToEffect = function (effect, uniformName0, uniformName1) {
  11500. };
  11501. Light.prototype._getWorldMatrix = function () {
  11502. return BABYLON.Matrix.Identity();
  11503. };
  11504. Light.prototype.canAffectMesh = function (mesh) {
  11505. if (!mesh) {
  11506. return true;
  11507. }
  11508. if (this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  11509. return false;
  11510. }
  11511. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  11512. return false;
  11513. }
  11514. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  11515. return false;
  11516. }
  11517. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  11518. return false;
  11519. }
  11520. return true;
  11521. };
  11522. Light.prototype.getWorldMatrix = function () {
  11523. this._currentRenderId = this.getScene().getRenderId();
  11524. var worldMatrix = this._getWorldMatrix();
  11525. if (this.parent && this.parent.getWorldMatrix) {
  11526. if (!this._parentedWorldMatrix) {
  11527. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  11528. }
  11529. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  11530. this._markSyncedWithParent();
  11531. return this._parentedWorldMatrix;
  11532. }
  11533. return worldMatrix;
  11534. };
  11535. Light.prototype.dispose = function () {
  11536. if (this._shadowGenerator) {
  11537. this._shadowGenerator.dispose();
  11538. this._shadowGenerator = null;
  11539. }
  11540. // Animations
  11541. this.getScene().stopAnimation(this);
  11542. // Remove from scene
  11543. this.getScene().removeLight(this);
  11544. _super.prototype.dispose.call(this);
  11545. };
  11546. Light.prototype.getTypeID = function () {
  11547. return 0;
  11548. };
  11549. Light.prototype.clone = function (name) {
  11550. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  11551. };
  11552. Light.prototype.serialize = function () {
  11553. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  11554. // Type
  11555. serializationObject.type = this.getTypeID();
  11556. // Parent
  11557. if (this.parent) {
  11558. serializationObject.parentId = this.parent.id;
  11559. }
  11560. // Inclusion / exclusions
  11561. if (this.excludedMeshes.length > 0) {
  11562. serializationObject.excludedMeshesIds = [];
  11563. this.excludedMeshes.forEach(function (mesh) {
  11564. serializationObject.excludedMeshesIds.push(mesh.id);
  11565. });
  11566. }
  11567. if (this.includedOnlyMeshes.length > 0) {
  11568. serializationObject.includedOnlyMeshesIds = [];
  11569. this.includedOnlyMeshes.forEach(function (mesh) {
  11570. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  11571. });
  11572. }
  11573. // Animations
  11574. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  11575. serializationObject.ranges = this.serializeAnimationRanges();
  11576. return serializationObject;
  11577. };
  11578. Light.GetConstructorFromName = function (type, name, scene) {
  11579. switch (type) {
  11580. case 0:
  11581. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  11582. case 1:
  11583. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  11584. case 2:
  11585. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  11586. case 3:
  11587. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  11588. }
  11589. };
  11590. Light.Parse = function (parsedLight, scene) {
  11591. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  11592. // Inclusion / exclusions
  11593. if (parsedLight.excludedMeshesIds) {
  11594. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  11595. }
  11596. if (parsedLight.includedOnlyMeshesIds) {
  11597. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  11598. }
  11599. // Parent
  11600. if (parsedLight.parentId) {
  11601. light._waitingParentId = parsedLight.parentId;
  11602. }
  11603. // Animations
  11604. if (parsedLight.animations) {
  11605. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  11606. var parsedAnimation = parsedLight.animations[animationIndex];
  11607. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  11608. }
  11609. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  11610. }
  11611. if (parsedLight.autoAnimate) {
  11612. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  11613. }
  11614. return light;
  11615. };
  11616. return Light;
  11617. }(BABYLON.Node));
  11618. //lightmapMode Consts
  11619. Light._LIGHTMAP_DEFAULT = 0;
  11620. Light._LIGHTMAP_SPECULAR = 1;
  11621. Light._LIGHTMAP_SHADOWSONLY = 2;
  11622. __decorate([
  11623. BABYLON.serializeAsColor3()
  11624. ], Light.prototype, "diffuse", void 0);
  11625. __decorate([
  11626. BABYLON.serializeAsColor3()
  11627. ], Light.prototype, "specular", void 0);
  11628. __decorate([
  11629. BABYLON.serialize()
  11630. ], Light.prototype, "intensity", void 0);
  11631. __decorate([
  11632. BABYLON.serialize()
  11633. ], Light.prototype, "range", void 0);
  11634. __decorate([
  11635. BABYLON.serialize()
  11636. ], Light.prototype, "includeOnlyWithLayerMask", void 0);
  11637. __decorate([
  11638. BABYLON.serialize()
  11639. ], Light.prototype, "excludeWithLayerMask", void 0);
  11640. __decorate([
  11641. BABYLON.serialize()
  11642. ], Light.prototype, "lightmapMode", void 0);
  11643. __decorate([
  11644. BABYLON.serialize()
  11645. ], Light.prototype, "radius", void 0);
  11646. BABYLON.Light = Light;
  11647. })(BABYLON || (BABYLON = {}));
  11648. //# sourceMappingURL=babylon.light.js.map
  11649. var BABYLON;
  11650. (function (BABYLON) {
  11651. var PointLight = (function (_super) {
  11652. __extends(PointLight, _super);
  11653. function PointLight(name, position, scene) {
  11654. var _this = _super.call(this, name, scene) || this;
  11655. _this.position = position;
  11656. return _this;
  11657. }
  11658. PointLight.prototype.getClassName = function () {
  11659. return "PointLight";
  11660. };
  11661. PointLight.prototype.getAbsolutePosition = function () {
  11662. return this.transformedPosition ? this.transformedPosition : this.position;
  11663. };
  11664. PointLight.prototype.computeTransformedPosition = function () {
  11665. if (this.parent && this.parent.getWorldMatrix) {
  11666. if (!this.transformedPosition) {
  11667. this.transformedPosition = BABYLON.Vector3.Zero();
  11668. }
  11669. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11670. return true;
  11671. }
  11672. return false;
  11673. };
  11674. PointLight.prototype.transferToEffect = function (effect, positionUniformName) {
  11675. if (this.parent && this.parent.getWorldMatrix) {
  11676. this.computeTransformedPosition();
  11677. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0);
  11678. return;
  11679. }
  11680. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, 0);
  11681. };
  11682. PointLight.prototype.needCube = function () {
  11683. return true;
  11684. };
  11685. PointLight.prototype.supportsVSM = function () {
  11686. return false;
  11687. };
  11688. PointLight.prototype.needRefreshPerFrame = function () {
  11689. return false;
  11690. };
  11691. PointLight.prototype.getShadowDirection = function (faceIndex) {
  11692. switch (faceIndex) {
  11693. case 0:
  11694. return new BABYLON.Vector3(1, 0, 0);
  11695. case 1:
  11696. return new BABYLON.Vector3(-1, 0, 0);
  11697. case 2:
  11698. return new BABYLON.Vector3(0, -1, 0);
  11699. case 3:
  11700. return new BABYLON.Vector3(0, 1, 0);
  11701. case 4:
  11702. return new BABYLON.Vector3(0, 0, 1);
  11703. case 5:
  11704. return new BABYLON.Vector3(0, 0, -1);
  11705. }
  11706. return BABYLON.Vector3.Zero();
  11707. };
  11708. PointLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11709. var activeCamera = this.getScene().activeCamera;
  11710. BABYLON.Matrix.PerspectiveFovLHToRef(Math.PI / 2, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11711. };
  11712. PointLight.prototype._getWorldMatrix = function () {
  11713. if (!this._worldMatrix) {
  11714. this._worldMatrix = BABYLON.Matrix.Identity();
  11715. }
  11716. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11717. return this._worldMatrix;
  11718. };
  11719. PointLight.prototype.getTypeID = function () {
  11720. return 0;
  11721. };
  11722. return PointLight;
  11723. }(BABYLON.Light));
  11724. __decorate([
  11725. BABYLON.serializeAsVector3()
  11726. ], PointLight.prototype, "position", void 0);
  11727. BABYLON.PointLight = PointLight;
  11728. })(BABYLON || (BABYLON = {}));
  11729. //# sourceMappingURL=babylon.pointLight.js.map
  11730. var BABYLON;
  11731. (function (BABYLON) {
  11732. var SpotLight = (function (_super) {
  11733. __extends(SpotLight, _super);
  11734. function SpotLight(name, position, direction, angle, exponent, scene) {
  11735. var _this = _super.call(this, name, scene) || this;
  11736. _this.position = position;
  11737. _this.direction = direction;
  11738. _this.angle = angle;
  11739. _this.exponent = exponent;
  11740. return _this;
  11741. }
  11742. SpotLight.prototype.getClassName = function () {
  11743. return "SpotLight";
  11744. };
  11745. SpotLight.prototype.getAbsolutePosition = function () {
  11746. return this.transformedPosition ? this.transformedPosition : this.position;
  11747. };
  11748. SpotLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11749. var activeCamera = this.getScene().activeCamera;
  11750. BABYLON.Matrix.PerspectiveFovLHToRef(this.angle, 1.0, activeCamera.minZ, activeCamera.maxZ, matrix);
  11751. };
  11752. SpotLight.prototype.needCube = function () {
  11753. return false;
  11754. };
  11755. SpotLight.prototype.supportsVSM = function () {
  11756. return true;
  11757. };
  11758. SpotLight.prototype.needRefreshPerFrame = function () {
  11759. return false;
  11760. };
  11761. SpotLight.prototype.getShadowDirection = function (faceIndex) {
  11762. return this.direction;
  11763. };
  11764. SpotLight.prototype.setDirectionToTarget = function (target) {
  11765. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11766. return this.direction;
  11767. };
  11768. SpotLight.prototype.computeTransformedPosition = function () {
  11769. if (this.parent && this.parent.getWorldMatrix) {
  11770. if (!this.transformedPosition) {
  11771. this.transformedPosition = BABYLON.Vector3.Zero();
  11772. }
  11773. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11774. return true;
  11775. }
  11776. return false;
  11777. };
  11778. SpotLight.prototype.transferToEffect = function (effect, positionUniformName, directionUniformName) {
  11779. var normalizeDirection;
  11780. if (this.parent && this.parent.getWorldMatrix) {
  11781. if (!this._transformedDirection) {
  11782. this._transformedDirection = BABYLON.Vector3.Zero();
  11783. }
  11784. this.computeTransformedPosition();
  11785. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11786. effect.setFloat4(positionUniformName, this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent);
  11787. normalizeDirection = BABYLON.Vector3.Normalize(this._transformedDirection);
  11788. }
  11789. else {
  11790. effect.setFloat4(positionUniformName, this.position.x, this.position.y, this.position.z, this.exponent);
  11791. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11792. }
  11793. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5));
  11794. };
  11795. SpotLight.prototype._getWorldMatrix = function () {
  11796. if (!this._worldMatrix) {
  11797. this._worldMatrix = BABYLON.Matrix.Identity();
  11798. }
  11799. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11800. return this._worldMatrix;
  11801. };
  11802. SpotLight.prototype.getTypeID = function () {
  11803. return 2;
  11804. };
  11805. SpotLight.prototype.getRotation = function () {
  11806. this.direction.normalize();
  11807. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  11808. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  11809. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  11810. };
  11811. return SpotLight;
  11812. }(BABYLON.Light));
  11813. __decorate([
  11814. BABYLON.serializeAsVector3()
  11815. ], SpotLight.prototype, "position", void 0);
  11816. __decorate([
  11817. BABYLON.serializeAsVector3()
  11818. ], SpotLight.prototype, "direction", void 0);
  11819. __decorate([
  11820. BABYLON.serialize()
  11821. ], SpotLight.prototype, "angle", void 0);
  11822. __decorate([
  11823. BABYLON.serialize()
  11824. ], SpotLight.prototype, "exponent", void 0);
  11825. BABYLON.SpotLight = SpotLight;
  11826. })(BABYLON || (BABYLON = {}));
  11827. //# sourceMappingURL=babylon.spotLight.js.map
  11828. var BABYLON;
  11829. (function (BABYLON) {
  11830. var HemisphericLight = (function (_super) {
  11831. __extends(HemisphericLight, _super);
  11832. function HemisphericLight(name, direction, scene) {
  11833. var _this = _super.call(this, name, scene) || this;
  11834. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  11835. _this.direction = direction;
  11836. return _this;
  11837. }
  11838. HemisphericLight.prototype.getClassName = function () {
  11839. return "HemisphericLight";
  11840. };
  11841. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  11842. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  11843. return this.direction;
  11844. };
  11845. HemisphericLight.prototype.getShadowGenerator = function () {
  11846. return null;
  11847. };
  11848. HemisphericLight.prototype.transferToEffect = function (effect, directionUniformName, groundColorUniformName) {
  11849. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  11850. effect.setFloat4(directionUniformName, normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0);
  11851. effect.setColor3(groundColorUniformName, this.groundColor.scale(this.intensity));
  11852. };
  11853. HemisphericLight.prototype._getWorldMatrix = function () {
  11854. if (!this._worldMatrix) {
  11855. this._worldMatrix = BABYLON.Matrix.Identity();
  11856. }
  11857. return this._worldMatrix;
  11858. };
  11859. HemisphericLight.prototype.getTypeID = function () {
  11860. return 3;
  11861. };
  11862. return HemisphericLight;
  11863. }(BABYLON.Light));
  11864. __decorate([
  11865. BABYLON.serializeAsColor3()
  11866. ], HemisphericLight.prototype, "groundColor", void 0);
  11867. __decorate([
  11868. BABYLON.serializeAsVector3()
  11869. ], HemisphericLight.prototype, "direction", void 0);
  11870. BABYLON.HemisphericLight = HemisphericLight;
  11871. })(BABYLON || (BABYLON = {}));
  11872. //# sourceMappingURL=babylon.hemisphericLight.js.map
  11873. var BABYLON;
  11874. (function (BABYLON) {
  11875. var DirectionalLight = (function (_super) {
  11876. __extends(DirectionalLight, _super);
  11877. function DirectionalLight(name, direction, scene) {
  11878. var _this = _super.call(this, name, scene) || this;
  11879. _this.shadowOrthoScale = 0.5;
  11880. _this.autoUpdateExtends = true;
  11881. // Cache
  11882. _this._orthoLeft = Number.MAX_VALUE;
  11883. _this._orthoRight = Number.MIN_VALUE;
  11884. _this._orthoTop = Number.MIN_VALUE;
  11885. _this._orthoBottom = Number.MAX_VALUE;
  11886. _this.position = direction.scale(-1);
  11887. _this.direction = direction;
  11888. return _this;
  11889. }
  11890. DirectionalLight.prototype.getClassName = function () {
  11891. return "DirectionalLight";
  11892. };
  11893. DirectionalLight.prototype.getAbsolutePosition = function () {
  11894. return this.transformedPosition ? this.transformedPosition : this.position;
  11895. };
  11896. DirectionalLight.prototype.setDirectionToTarget = function (target) {
  11897. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  11898. return this.direction;
  11899. };
  11900. DirectionalLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  11901. var activeCamera = this.getScene().activeCamera;
  11902. // Check extends
  11903. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  11904. var tempVector3 = BABYLON.Vector3.Zero();
  11905. this._orthoLeft = Number.MAX_VALUE;
  11906. this._orthoRight = Number.MIN_VALUE;
  11907. this._orthoTop = Number.MIN_VALUE;
  11908. this._orthoBottom = Number.MAX_VALUE;
  11909. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  11910. var mesh = renderList[meshIndex];
  11911. if (!mesh) {
  11912. continue;
  11913. }
  11914. var boundingInfo = mesh.getBoundingInfo();
  11915. if (!boundingInfo) {
  11916. continue;
  11917. }
  11918. var boundingBox = boundingInfo.boundingBox;
  11919. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  11920. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  11921. if (tempVector3.x < this._orthoLeft)
  11922. this._orthoLeft = tempVector3.x;
  11923. if (tempVector3.y < this._orthoBottom)
  11924. this._orthoBottom = tempVector3.y;
  11925. if (tempVector3.x > this._orthoRight)
  11926. this._orthoRight = tempVector3.x;
  11927. if (tempVector3.y > this._orthoTop)
  11928. this._orthoTop = tempVector3.y;
  11929. }
  11930. }
  11931. }
  11932. var xOffset = this._orthoRight - this._orthoLeft;
  11933. var yOffset = this._orthoTop - this._orthoBottom;
  11934. 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);
  11935. };
  11936. DirectionalLight.prototype.supportsVSM = function () {
  11937. return true;
  11938. };
  11939. DirectionalLight.prototype.needRefreshPerFrame = function () {
  11940. return true;
  11941. };
  11942. DirectionalLight.prototype.needCube = function () {
  11943. return false;
  11944. };
  11945. DirectionalLight.prototype.getShadowDirection = function (faceIndex) {
  11946. return this.direction;
  11947. };
  11948. DirectionalLight.prototype.computeTransformedPosition = function () {
  11949. if (this.parent && this.parent.getWorldMatrix) {
  11950. if (!this.transformedPosition) {
  11951. this.transformedPosition = BABYLON.Vector3.Zero();
  11952. }
  11953. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  11954. return true;
  11955. }
  11956. return false;
  11957. };
  11958. DirectionalLight.prototype.transferToEffect = function (effect, directionUniformName) {
  11959. if (this.parent && this.parent.getWorldMatrix) {
  11960. if (!this._transformedDirection) {
  11961. this._transformedDirection = BABYLON.Vector3.Zero();
  11962. }
  11963. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this._transformedDirection);
  11964. effect.setFloat4(directionUniformName, this._transformedDirection.x, this._transformedDirection.y, this._transformedDirection.z, 1);
  11965. return;
  11966. }
  11967. effect.setFloat4(directionUniformName, this.direction.x, this.direction.y, this.direction.z, 1);
  11968. };
  11969. DirectionalLight.prototype._getWorldMatrix = function () {
  11970. if (!this._worldMatrix) {
  11971. this._worldMatrix = BABYLON.Matrix.Identity();
  11972. }
  11973. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  11974. return this._worldMatrix;
  11975. };
  11976. DirectionalLight.prototype.getTypeID = function () {
  11977. return 1;
  11978. };
  11979. return DirectionalLight;
  11980. }(BABYLON.Light));
  11981. __decorate([
  11982. BABYLON.serializeAsVector3()
  11983. ], DirectionalLight.prototype, "position", void 0);
  11984. __decorate([
  11985. BABYLON.serializeAsVector3()
  11986. ], DirectionalLight.prototype, "direction", void 0);
  11987. __decorate([
  11988. BABYLON.serialize()
  11989. ], DirectionalLight.prototype, "shadowOrthoScale", void 0);
  11990. __decorate([
  11991. BABYLON.serialize()
  11992. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  11993. BABYLON.DirectionalLight = DirectionalLight;
  11994. })(BABYLON || (BABYLON = {}));
  11995. //# sourceMappingURL=babylon.directionalLight.js.map
  11996. var BABYLON;
  11997. (function (BABYLON) {
  11998. var ShadowGenerator = (function () {
  11999. function ShadowGenerator(mapSize, light) {
  12000. var _this = this;
  12001. // Members
  12002. this._filter = ShadowGenerator.FILTER_NONE;
  12003. this.blurScale = 2;
  12004. this._blurBoxOffset = 0;
  12005. this._bias = 0.00005;
  12006. this._lightDirection = BABYLON.Vector3.Zero();
  12007. this.forceBackFacesOnly = false;
  12008. this._darkness = 0;
  12009. this._transparencyShadow = false;
  12010. this._viewMatrix = BABYLON.Matrix.Zero();
  12011. this._projectionMatrix = BABYLON.Matrix.Zero();
  12012. this._transformMatrix = BABYLON.Matrix.Zero();
  12013. this._worldViewProjection = BABYLON.Matrix.Zero();
  12014. this._currentFaceIndex = 0;
  12015. this._currentFaceIndexCache = 0;
  12016. this._useFullFloat = true;
  12017. this._light = light;
  12018. this._scene = light.getScene();
  12019. this._mapSize = mapSize;
  12020. light._shadowGenerator = this;
  12021. // Texture type fallback from float to int if not supported.
  12022. var textureType;
  12023. var caps = this._scene.getEngine().getCaps();
  12024. if (caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  12025. this._useFullFloat = true;
  12026. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  12027. }
  12028. else {
  12029. this._useFullFloat = false;
  12030. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  12031. }
  12032. // Render target
  12033. this._shadowMap = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, this._scene, false, true, textureType, light.needCube());
  12034. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12035. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12036. this._shadowMap.anisotropicFilteringLevel = 1;
  12037. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12038. this._shadowMap.renderParticles = false;
  12039. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  12040. _this._currentFaceIndex = faceIndex;
  12041. });
  12042. this._shadowMap.onAfterUnbindObservable.add(function () {
  12043. if (!_this.useBlurVarianceShadowMap) {
  12044. return;
  12045. }
  12046. if (!_this._shadowMap2) {
  12047. _this._shadowMap2 = new BABYLON.RenderTargetTexture(light.name + "_shadowMap", mapSize, _this._scene, false, true, textureType);
  12048. _this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12049. _this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  12050. _this._shadowMap2.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  12051. _this._downSamplePostprocess = new BABYLON.PassPostProcess("downScale", 1.0 / _this.blurScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, _this._scene.getEngine());
  12052. _this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  12053. effect.setTexture("textureSampler", _this._shadowMap);
  12054. });
  12055. _this.blurBoxOffset = 1;
  12056. }
  12057. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._boxBlurPostprocess], _this._shadowMap2.getInternalTexture());
  12058. });
  12059. // Custom render function
  12060. var renderSubMesh = function (subMesh) {
  12061. var mesh = subMesh.getRenderingMesh();
  12062. var scene = _this._scene;
  12063. var engine = scene.getEngine();
  12064. // Culling
  12065. engine.setState(subMesh.getMaterial().backFaceCulling);
  12066. // Managing instances
  12067. var batch = mesh._getInstancesRenderList(subMesh._id);
  12068. if (batch.mustReturn) {
  12069. return;
  12070. }
  12071. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  12072. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  12073. engine.enableEffect(_this._effect);
  12074. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  12075. var material = subMesh.getMaterial();
  12076. _this._effect.setMatrix("viewProjection", _this.getTransformMatrix());
  12077. _this._effect.setVector3("lightPosition", _this.getLight().position);
  12078. if (_this.getLight().needCube()) {
  12079. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  12080. }
  12081. // Alpha test
  12082. if (material && material.needAlphaTesting()) {
  12083. var alphaTexture = material.getAlphaTestTexture();
  12084. _this._effect.setTexture("diffuseSampler", alphaTexture);
  12085. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  12086. }
  12087. // Bones
  12088. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12089. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  12090. }
  12091. if (_this.forceBackFacesOnly) {
  12092. engine.setState(true, 0, false, true);
  12093. }
  12094. // Draw
  12095. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  12096. if (_this.forceBackFacesOnly) {
  12097. engine.setState(true, 0, false, false);
  12098. }
  12099. }
  12100. else {
  12101. // Need to reset refresh rate of the shadowMap
  12102. _this._shadowMap.resetRefreshCounter();
  12103. }
  12104. };
  12105. this._shadowMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  12106. var index;
  12107. for (index = 0; index < opaqueSubMeshes.length; index++) {
  12108. renderSubMesh(opaqueSubMeshes.data[index]);
  12109. }
  12110. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  12111. renderSubMesh(alphaTestSubMeshes.data[index]);
  12112. }
  12113. if (_this._transparencyShadow) {
  12114. for (index = 0; index < transparentSubMeshes.length; index++) {
  12115. renderSubMesh(transparentSubMeshes.data[index]);
  12116. }
  12117. }
  12118. };
  12119. this._shadowMap.onClearObservable.add(function (engine) {
  12120. if (_this.useBlurVarianceShadowMap || _this.useVarianceShadowMap) {
  12121. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  12122. }
  12123. else {
  12124. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  12125. }
  12126. });
  12127. }
  12128. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  12129. // Static
  12130. get: function () {
  12131. return ShadowGenerator._FILTER_NONE;
  12132. },
  12133. enumerable: true,
  12134. configurable: true
  12135. });
  12136. Object.defineProperty(ShadowGenerator, "FILTER_VARIANCESHADOWMAP", {
  12137. get: function () {
  12138. return ShadowGenerator._FILTER_VARIANCESHADOWMAP;
  12139. },
  12140. enumerable: true,
  12141. configurable: true
  12142. });
  12143. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  12144. get: function () {
  12145. return ShadowGenerator._FILTER_POISSONSAMPLING;
  12146. },
  12147. enumerable: true,
  12148. configurable: true
  12149. });
  12150. Object.defineProperty(ShadowGenerator, "FILTER_BLURVARIANCESHADOWMAP", {
  12151. get: function () {
  12152. return ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP;
  12153. },
  12154. enumerable: true,
  12155. configurable: true
  12156. });
  12157. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  12158. get: function () {
  12159. return this._bias;
  12160. },
  12161. set: function (bias) {
  12162. this._bias = bias;
  12163. },
  12164. enumerable: true,
  12165. configurable: true
  12166. });
  12167. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  12168. get: function () {
  12169. return this._blurBoxOffset;
  12170. },
  12171. set: function (value) {
  12172. var _this = this;
  12173. if (this._blurBoxOffset === value) {
  12174. return;
  12175. }
  12176. this._blurBoxOffset = value;
  12177. if (this._boxBlurPostprocess) {
  12178. this._boxBlurPostprocess.dispose();
  12179. }
  12180. 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);
  12181. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  12182. effect.setFloat2("screenSize", _this._mapSize / _this.blurScale, _this._mapSize / _this.blurScale);
  12183. });
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  12189. get: function () {
  12190. return this._filter;
  12191. },
  12192. set: function (value) {
  12193. if (this._filter === value) {
  12194. return;
  12195. }
  12196. this._filter = value;
  12197. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap || this.usePoissonSampling) {
  12198. this._shadowMap.anisotropicFilteringLevel = 16;
  12199. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  12200. }
  12201. else {
  12202. this._shadowMap.anisotropicFilteringLevel = 1;
  12203. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12204. }
  12205. },
  12206. enumerable: true,
  12207. configurable: true
  12208. });
  12209. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  12210. get: function () {
  12211. return this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP && this._light.supportsVSM();
  12212. },
  12213. set: function (value) {
  12214. this.filter = (value ? ShadowGenerator.FILTER_VARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12215. },
  12216. enumerable: true,
  12217. configurable: true
  12218. });
  12219. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  12220. get: function () {
  12221. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING ||
  12222. (!this._light.supportsVSM() && (this.filter === ShadowGenerator.FILTER_VARIANCESHADOWMAP ||
  12223. this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP));
  12224. },
  12225. set: function (value) {
  12226. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  12227. },
  12228. enumerable: true,
  12229. configurable: true
  12230. });
  12231. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  12232. get: function () {
  12233. return this.filter === ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP && this._light.supportsVSM();
  12234. },
  12235. set: function (value) {
  12236. this.filter = (value ? ShadowGenerator.FILTER_BLURVARIANCESHADOWMAP : ShadowGenerator.FILTER_NONE);
  12237. },
  12238. enumerable: true,
  12239. configurable: true
  12240. });
  12241. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  12242. var defines = [];
  12243. if (this._useFullFloat) {
  12244. defines.push("#define FULLFLOAT");
  12245. }
  12246. if (this.useVarianceShadowMap || this.useBlurVarianceShadowMap) {
  12247. defines.push("#define VSM");
  12248. }
  12249. if (this.getLight().needCube()) {
  12250. defines.push("#define CUBEMAP");
  12251. }
  12252. var attribs = [BABYLON.VertexBuffer.PositionKind];
  12253. var mesh = subMesh.getMesh();
  12254. var material = subMesh.getMaterial();
  12255. // Alpha test
  12256. if (material && material.needAlphaTesting()) {
  12257. defines.push("#define ALPHATEST");
  12258. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  12259. attribs.push(BABYLON.VertexBuffer.UVKind);
  12260. defines.push("#define UV1");
  12261. }
  12262. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  12263. var alphaTexture = material.getAlphaTestTexture();
  12264. if (alphaTexture.coordinatesIndex === 1) {
  12265. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  12266. defines.push("#define UV2");
  12267. }
  12268. }
  12269. }
  12270. // Bones
  12271. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  12272. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  12273. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  12274. if (mesh.numBoneInfluencers > 4) {
  12275. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  12276. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  12277. }
  12278. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  12279. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  12280. }
  12281. else {
  12282. defines.push("#define NUM_BONE_INFLUENCERS 0");
  12283. }
  12284. // Instances
  12285. if (useInstances) {
  12286. defines.push("#define INSTANCES");
  12287. attribs.push("world0");
  12288. attribs.push("world1");
  12289. attribs.push("world2");
  12290. attribs.push("world3");
  12291. }
  12292. // Get correct effect
  12293. var join = defines.join("\n");
  12294. if (this._cachedDefines !== join) {
  12295. this._cachedDefines = join;
  12296. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues"], ["diffuseSampler"], join);
  12297. }
  12298. return this._effect.isReady();
  12299. };
  12300. ShadowGenerator.prototype.getShadowMap = function () {
  12301. return this._shadowMap;
  12302. };
  12303. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  12304. if (this._shadowMap2) {
  12305. return this._shadowMap2;
  12306. }
  12307. return this._shadowMap;
  12308. };
  12309. ShadowGenerator.prototype.getLight = function () {
  12310. return this._light;
  12311. };
  12312. // Methods
  12313. ShadowGenerator.prototype.getTransformMatrix = function () {
  12314. var scene = this._scene;
  12315. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  12316. return this._transformMatrix;
  12317. }
  12318. this._currentRenderID = scene.getRenderId();
  12319. this._currentFaceIndexCache = this._currentFaceIndex;
  12320. var lightPosition = this._light.position;
  12321. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  12322. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  12323. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  12324. }
  12325. if (this._light.computeTransformedPosition()) {
  12326. lightPosition = this._light.transformedPosition;
  12327. }
  12328. if (this._light.needRefreshPerFrame() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  12329. this._cachedPosition = lightPosition.clone();
  12330. this._cachedDirection = this._lightDirection.clone();
  12331. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  12332. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  12333. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  12334. }
  12335. return this._transformMatrix;
  12336. };
  12337. ShadowGenerator.prototype.getDarkness = function () {
  12338. return this._darkness;
  12339. };
  12340. ShadowGenerator.prototype.setDarkness = function (darkness) {
  12341. if (darkness >= 1.0)
  12342. this._darkness = 1.0;
  12343. else if (darkness <= 0.0)
  12344. this._darkness = 0.0;
  12345. else
  12346. this._darkness = darkness;
  12347. };
  12348. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  12349. this._transparencyShadow = hasShadow;
  12350. };
  12351. ShadowGenerator.prototype._packHalf = function (depth) {
  12352. var scale = depth * 255.0;
  12353. var fract = scale - Math.floor(scale);
  12354. return new BABYLON.Vector2(depth - fract / 255.0, fract);
  12355. };
  12356. ShadowGenerator.prototype.dispose = function () {
  12357. this._shadowMap.dispose();
  12358. if (this._shadowMap2) {
  12359. this._shadowMap2.dispose();
  12360. }
  12361. if (this._downSamplePostprocess) {
  12362. this._downSamplePostprocess.dispose();
  12363. }
  12364. if (this._boxBlurPostprocess) {
  12365. this._boxBlurPostprocess.dispose();
  12366. }
  12367. };
  12368. ShadowGenerator.prototype.serialize = function () {
  12369. var serializationObject = {};
  12370. serializationObject.lightId = this._light.id;
  12371. serializationObject.mapSize = this.getShadowMap().getRenderSize();
  12372. serializationObject.useVarianceShadowMap = this.useVarianceShadowMap;
  12373. serializationObject.usePoissonSampling = this.usePoissonSampling;
  12374. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  12375. serializationObject.renderList = [];
  12376. for (var meshIndex = 0; meshIndex < this.getShadowMap().renderList.length; meshIndex++) {
  12377. var mesh = this.getShadowMap().renderList[meshIndex];
  12378. serializationObject.renderList.push(mesh.id);
  12379. }
  12380. return serializationObject;
  12381. };
  12382. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  12383. //casting to point light, as light is missing the position attr and typescript complains.
  12384. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  12385. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  12386. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  12387. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  12388. meshes.forEach(function (mesh) {
  12389. shadowGenerator.getShadowMap().renderList.push(mesh);
  12390. });
  12391. }
  12392. if (parsedShadowGenerator.usePoissonSampling) {
  12393. shadowGenerator.usePoissonSampling = true;
  12394. }
  12395. else if (parsedShadowGenerator.useVarianceShadowMap) {
  12396. shadowGenerator.useVarianceShadowMap = true;
  12397. }
  12398. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  12399. shadowGenerator.useBlurVarianceShadowMap = true;
  12400. if (parsedShadowGenerator.blurScale) {
  12401. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  12402. }
  12403. if (parsedShadowGenerator.blurBoxOffset) {
  12404. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  12405. }
  12406. }
  12407. if (parsedShadowGenerator.bias !== undefined) {
  12408. shadowGenerator.bias = parsedShadowGenerator.bias;
  12409. }
  12410. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  12411. return shadowGenerator;
  12412. };
  12413. return ShadowGenerator;
  12414. }());
  12415. ShadowGenerator._FILTER_NONE = 0;
  12416. ShadowGenerator._FILTER_VARIANCESHADOWMAP = 1;
  12417. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  12418. ShadowGenerator._FILTER_BLURVARIANCESHADOWMAP = 3;
  12419. BABYLON.ShadowGenerator = ShadowGenerator;
  12420. })(BABYLON || (BABYLON = {}));
  12421. //# sourceMappingURL=babylon.shadowGenerator.js.map
  12422. var BABYLON;
  12423. (function (BABYLON) {
  12424. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  12425. if (boxMin.x > sphereCenter.x + sphereRadius)
  12426. return false;
  12427. if (sphereCenter.x - sphereRadius > boxMax.x)
  12428. return false;
  12429. if (boxMin.y > sphereCenter.y + sphereRadius)
  12430. return false;
  12431. if (sphereCenter.y - sphereRadius > boxMax.y)
  12432. return false;
  12433. if (boxMin.z > sphereCenter.z + sphereRadius)
  12434. return false;
  12435. if (sphereCenter.z - sphereRadius > boxMax.z)
  12436. return false;
  12437. return true;
  12438. };
  12439. var getLowestRoot = (function () {
  12440. var result = { root: 0, found: false };
  12441. return function (a, b, c, maxR) {
  12442. result.root = 0;
  12443. result.found = false;
  12444. var determinant = b * b - 4.0 * a * c;
  12445. if (determinant < 0)
  12446. return result;
  12447. var sqrtD = Math.sqrt(determinant);
  12448. var r1 = (-b - sqrtD) / (2.0 * a);
  12449. var r2 = (-b + sqrtD) / (2.0 * a);
  12450. if (r1 > r2) {
  12451. var temp = r2;
  12452. r2 = r1;
  12453. r1 = temp;
  12454. }
  12455. if (r1 > 0 && r1 < maxR) {
  12456. result.root = r1;
  12457. result.found = true;
  12458. return result;
  12459. }
  12460. if (r2 > 0 && r2 < maxR) {
  12461. result.root = r2;
  12462. result.found = true;
  12463. return result;
  12464. }
  12465. return result;
  12466. };
  12467. })();
  12468. var Collider = (function () {
  12469. function Collider() {
  12470. this.radius = new BABYLON.Vector3(1, 1, 1);
  12471. this.retry = 0;
  12472. this.basePointWorld = BABYLON.Vector3.Zero();
  12473. this.velocityWorld = BABYLON.Vector3.Zero();
  12474. this.normalizedVelocity = BABYLON.Vector3.Zero();
  12475. this._collisionPoint = BABYLON.Vector3.Zero();
  12476. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  12477. this._tempVector = BABYLON.Vector3.Zero();
  12478. this._tempVector2 = BABYLON.Vector3.Zero();
  12479. this._tempVector3 = BABYLON.Vector3.Zero();
  12480. this._tempVector4 = BABYLON.Vector3.Zero();
  12481. this._edge = BABYLON.Vector3.Zero();
  12482. this._baseToVertex = BABYLON.Vector3.Zero();
  12483. this._destinationPoint = BABYLON.Vector3.Zero();
  12484. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  12485. this._displacementVector = BABYLON.Vector3.Zero();
  12486. }
  12487. // Methods
  12488. Collider.prototype._initialize = function (source, dir, e) {
  12489. this.velocity = dir;
  12490. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  12491. this.basePoint = source;
  12492. source.multiplyToRef(this.radius, this.basePointWorld);
  12493. dir.multiplyToRef(this.radius, this.velocityWorld);
  12494. this.velocityWorldLength = this.velocityWorld.length();
  12495. this.epsilon = e;
  12496. this.collisionFound = false;
  12497. };
  12498. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  12499. pa.subtractToRef(point, this._tempVector);
  12500. pb.subtractToRef(point, this._tempVector2);
  12501. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  12502. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12503. if (d < 0)
  12504. return false;
  12505. pc.subtractToRef(point, this._tempVector3);
  12506. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  12507. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12508. if (d < 0)
  12509. return false;
  12510. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  12511. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  12512. return d >= 0;
  12513. };
  12514. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  12515. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  12516. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  12517. if (distance > this.velocityWorldLength + max + sphereRadius) {
  12518. return false;
  12519. }
  12520. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  12521. return false;
  12522. return true;
  12523. };
  12524. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  12525. var t0;
  12526. var embeddedInPlane = false;
  12527. //defensive programming, actually not needed.
  12528. if (!trianglePlaneArray) {
  12529. trianglePlaneArray = [];
  12530. }
  12531. if (!trianglePlaneArray[faceIndex]) {
  12532. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  12533. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  12534. }
  12535. var trianglePlane = trianglePlaneArray[faceIndex];
  12536. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  12537. return;
  12538. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  12539. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  12540. if (normalDotVelocity == 0) {
  12541. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  12542. return;
  12543. embeddedInPlane = true;
  12544. t0 = 0;
  12545. }
  12546. else {
  12547. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12548. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  12549. if (t0 > t1) {
  12550. var temp = t1;
  12551. t1 = t0;
  12552. t0 = temp;
  12553. }
  12554. if (t0 > 1.0 || t1 < 0.0)
  12555. return;
  12556. if (t0 < 0)
  12557. t0 = 0;
  12558. if (t0 > 1.0)
  12559. t0 = 1.0;
  12560. }
  12561. this._collisionPoint.copyFromFloats(0, 0, 0);
  12562. var found = false;
  12563. var t = 1.0;
  12564. if (!embeddedInPlane) {
  12565. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  12566. this.velocity.scaleToRef(t0, this._tempVector);
  12567. this._planeIntersectionPoint.addInPlace(this._tempVector);
  12568. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  12569. found = true;
  12570. t = t0;
  12571. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  12572. }
  12573. }
  12574. if (!found) {
  12575. var velocitySquaredLength = this.velocity.lengthSquared();
  12576. var a = velocitySquaredLength;
  12577. this.basePoint.subtractToRef(p1, this._tempVector);
  12578. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12579. var c = this._tempVector.lengthSquared() - 1.0;
  12580. var lowestRoot = getLowestRoot(a, b, c, t);
  12581. if (lowestRoot.found) {
  12582. t = lowestRoot.root;
  12583. found = true;
  12584. this._collisionPoint.copyFrom(p1);
  12585. }
  12586. this.basePoint.subtractToRef(p2, this._tempVector);
  12587. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12588. c = this._tempVector.lengthSquared() - 1.0;
  12589. lowestRoot = getLowestRoot(a, b, c, t);
  12590. if (lowestRoot.found) {
  12591. t = lowestRoot.root;
  12592. found = true;
  12593. this._collisionPoint.copyFrom(p2);
  12594. }
  12595. this.basePoint.subtractToRef(p3, this._tempVector);
  12596. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  12597. c = this._tempVector.lengthSquared() - 1.0;
  12598. lowestRoot = getLowestRoot(a, b, c, t);
  12599. if (lowestRoot.found) {
  12600. t = lowestRoot.root;
  12601. found = true;
  12602. this._collisionPoint.copyFrom(p3);
  12603. }
  12604. p2.subtractToRef(p1, this._edge);
  12605. p1.subtractToRef(this.basePoint, this._baseToVertex);
  12606. var edgeSquaredLength = this._edge.lengthSquared();
  12607. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12608. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12609. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12610. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12611. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12612. lowestRoot = getLowestRoot(a, b, c, t);
  12613. if (lowestRoot.found) {
  12614. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12615. if (f >= 0.0 && f <= 1.0) {
  12616. t = lowestRoot.root;
  12617. found = true;
  12618. this._edge.scaleInPlace(f);
  12619. p1.addToRef(this._edge, this._collisionPoint);
  12620. }
  12621. }
  12622. p3.subtractToRef(p2, this._edge);
  12623. p2.subtractToRef(this.basePoint, this._baseToVertex);
  12624. edgeSquaredLength = this._edge.lengthSquared();
  12625. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12626. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12627. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12628. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12629. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12630. lowestRoot = getLowestRoot(a, b, c, t);
  12631. if (lowestRoot.found) {
  12632. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12633. if (f >= 0.0 && f <= 1.0) {
  12634. t = lowestRoot.root;
  12635. found = true;
  12636. this._edge.scaleInPlace(f);
  12637. p2.addToRef(this._edge, this._collisionPoint);
  12638. }
  12639. }
  12640. p1.subtractToRef(p3, this._edge);
  12641. p3.subtractToRef(this.basePoint, this._baseToVertex);
  12642. edgeSquaredLength = this._edge.lengthSquared();
  12643. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  12644. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  12645. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  12646. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  12647. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  12648. lowestRoot = getLowestRoot(a, b, c, t);
  12649. if (lowestRoot.found) {
  12650. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  12651. if (f >= 0.0 && f <= 1.0) {
  12652. t = lowestRoot.root;
  12653. found = true;
  12654. this._edge.scaleInPlace(f);
  12655. p3.addToRef(this._edge, this._collisionPoint);
  12656. }
  12657. }
  12658. }
  12659. if (found) {
  12660. var distToCollision = t * this.velocity.length();
  12661. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  12662. if (!this.intersectionPoint) {
  12663. this.intersectionPoint = this._collisionPoint.clone();
  12664. }
  12665. else {
  12666. this.intersectionPoint.copyFrom(this._collisionPoint);
  12667. }
  12668. this.nearestDistance = distToCollision;
  12669. this.collisionFound = true;
  12670. }
  12671. }
  12672. };
  12673. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  12674. for (var i = indexStart; i < indexEnd; i += 3) {
  12675. var p1 = pts[indices[i] - decal];
  12676. var p2 = pts[indices[i + 1] - decal];
  12677. var p3 = pts[indices[i + 2] - decal];
  12678. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  12679. }
  12680. };
  12681. Collider.prototype._getResponse = function (pos, vel) {
  12682. pos.addToRef(vel, this._destinationPoint);
  12683. vel.scaleInPlace((this.nearestDistance / vel.length()));
  12684. this.basePoint.addToRef(vel, pos);
  12685. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  12686. this._slidePlaneNormal.normalize();
  12687. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  12688. pos.addInPlace(this._displacementVector);
  12689. this.intersectionPoint.addInPlace(this._displacementVector);
  12690. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  12691. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  12692. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  12693. };
  12694. return Collider;
  12695. }());
  12696. BABYLON.Collider = Collider;
  12697. })(BABYLON || (BABYLON = {}));
  12698. //# sourceMappingURL=babylon.collider.js.map
  12699. var BABYLON;
  12700. (function (BABYLON) {
  12701. //WebWorker code will be inserted to this variable.
  12702. BABYLON.CollisionWorker = "";
  12703. var WorkerTaskType;
  12704. (function (WorkerTaskType) {
  12705. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  12706. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  12707. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  12708. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  12709. var WorkerReplyType;
  12710. (function (WorkerReplyType) {
  12711. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  12712. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  12713. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  12714. var CollisionCoordinatorWorker = (function () {
  12715. function CollisionCoordinatorWorker() {
  12716. var _this = this;
  12717. this._scaledPosition = BABYLON.Vector3.Zero();
  12718. this._scaledVelocity = BABYLON.Vector3.Zero();
  12719. this.onMeshUpdated = function (mesh) {
  12720. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  12721. };
  12722. this.onGeometryUpdated = function (geometry) {
  12723. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  12724. };
  12725. this._afterRender = function () {
  12726. if (!_this._init)
  12727. return;
  12728. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  12729. return;
  12730. }
  12731. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  12732. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  12733. if (_this._runningUpdated > 4) {
  12734. return;
  12735. }
  12736. ++_this._runningUpdated;
  12737. var payload = {
  12738. updatedMeshes: _this._addUpdateMeshesList,
  12739. updatedGeometries: _this._addUpdateGeometriesList,
  12740. removedGeometries: _this._toRemoveGeometryArray,
  12741. removedMeshes: _this._toRemoveMeshesArray
  12742. };
  12743. var message = {
  12744. payload: payload,
  12745. taskType: WorkerTaskType.UPDATE
  12746. };
  12747. var serializable = [];
  12748. for (var id in payload.updatedGeometries) {
  12749. if (payload.updatedGeometries.hasOwnProperty(id)) {
  12750. //prepare transferables
  12751. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  12752. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  12753. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  12754. }
  12755. }
  12756. _this._worker.postMessage(message, serializable);
  12757. _this._addUpdateMeshesList = {};
  12758. _this._addUpdateGeometriesList = {};
  12759. _this._toRemoveGeometryArray = [];
  12760. _this._toRemoveMeshesArray = [];
  12761. };
  12762. this._onMessageFromWorker = function (e) {
  12763. var returnData = e.data;
  12764. if (returnData.error != WorkerReplyType.SUCCESS) {
  12765. //TODO what errors can be returned from the worker?
  12766. BABYLON.Tools.Warn("error returned from worker!");
  12767. return;
  12768. }
  12769. switch (returnData.taskType) {
  12770. case WorkerTaskType.INIT:
  12771. _this._init = true;
  12772. //Update the worked with ALL of the scene's current state
  12773. _this._scene.meshes.forEach(function (mesh) {
  12774. _this.onMeshAdded(mesh);
  12775. });
  12776. _this._scene.getGeometries().forEach(function (geometry) {
  12777. _this.onGeometryAdded(geometry);
  12778. });
  12779. break;
  12780. case WorkerTaskType.UPDATE:
  12781. _this._runningUpdated--;
  12782. break;
  12783. case WorkerTaskType.COLLIDE:
  12784. _this._runningCollisionTask = false;
  12785. var returnPayload = returnData.payload;
  12786. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  12787. return;
  12788. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  12789. //cleanup
  12790. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  12791. break;
  12792. }
  12793. };
  12794. this._collisionsCallbackArray = [];
  12795. this._init = false;
  12796. this._runningUpdated = 0;
  12797. this._runningCollisionTask = false;
  12798. this._addUpdateMeshesList = {};
  12799. this._addUpdateGeometriesList = {};
  12800. this._toRemoveGeometryArray = [];
  12801. this._toRemoveMeshesArray = [];
  12802. }
  12803. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12804. if (!this._init)
  12805. return;
  12806. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  12807. return;
  12808. position.divideToRef(collider.radius, this._scaledPosition);
  12809. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12810. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  12811. var payload = {
  12812. collider: {
  12813. position: this._scaledPosition.asArray(),
  12814. velocity: this._scaledVelocity.asArray(),
  12815. radius: collider.radius.asArray()
  12816. },
  12817. collisionId: collisionIndex,
  12818. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  12819. maximumRetry: maximumRetry
  12820. };
  12821. var message = {
  12822. payload: payload,
  12823. taskType: WorkerTaskType.COLLIDE
  12824. };
  12825. this._worker.postMessage(message);
  12826. };
  12827. CollisionCoordinatorWorker.prototype.init = function (scene) {
  12828. this._scene = scene;
  12829. this._scene.registerAfterRender(this._afterRender);
  12830. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  12831. this._worker = new Worker(workerUrl);
  12832. this._worker.onmessage = this._onMessageFromWorker;
  12833. var message = {
  12834. payload: {},
  12835. taskType: WorkerTaskType.INIT
  12836. };
  12837. this._worker.postMessage(message);
  12838. };
  12839. CollisionCoordinatorWorker.prototype.destroy = function () {
  12840. this._scene.unregisterAfterRender(this._afterRender);
  12841. this._worker.terminate();
  12842. };
  12843. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  12844. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  12845. this.onMeshUpdated(mesh);
  12846. };
  12847. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  12848. this._toRemoveMeshesArray.push(mesh.uniqueId);
  12849. };
  12850. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  12851. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  12852. geometry.onGeometryUpdated = this.onGeometryUpdated;
  12853. this.onGeometryUpdated(geometry);
  12854. };
  12855. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  12856. this._toRemoveGeometryArray.push(geometry.id);
  12857. };
  12858. return CollisionCoordinatorWorker;
  12859. }());
  12860. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  12861. var submeshes = [];
  12862. if (mesh.subMeshes) {
  12863. submeshes = mesh.subMeshes.map(function (sm, idx) {
  12864. return {
  12865. position: idx,
  12866. verticesStart: sm.verticesStart,
  12867. verticesCount: sm.verticesCount,
  12868. indexStart: sm.indexStart,
  12869. indexCount: sm.indexCount,
  12870. hasMaterial: !!sm.getMaterial(),
  12871. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12872. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  12873. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12874. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  12875. };
  12876. });
  12877. }
  12878. var geometryId = null;
  12879. if (mesh instanceof BABYLON.Mesh) {
  12880. geometryId = mesh.geometry ? mesh.geometry.id : null;
  12881. }
  12882. else if (mesh instanceof BABYLON.InstancedMesh) {
  12883. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  12884. }
  12885. return {
  12886. uniqueId: mesh.uniqueId,
  12887. id: mesh.id,
  12888. name: mesh.name,
  12889. geometryId: geometryId,
  12890. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  12891. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  12892. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  12893. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  12894. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  12895. subMeshes: submeshes,
  12896. checkCollisions: mesh.checkCollisions
  12897. };
  12898. };
  12899. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  12900. return {
  12901. id: geometry.id,
  12902. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  12903. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  12904. indices: new Int32Array(geometry.getIndices() || []),
  12905. };
  12906. };
  12907. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  12908. var CollisionCoordinatorLegacy = (function () {
  12909. function CollisionCoordinatorLegacy() {
  12910. this._scaledPosition = BABYLON.Vector3.Zero();
  12911. this._scaledVelocity = BABYLON.Vector3.Zero();
  12912. this._finalPosition = BABYLON.Vector3.Zero();
  12913. }
  12914. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  12915. position.divideToRef(collider.radius, this._scaledPosition);
  12916. velocity.divideToRef(collider.radius, this._scaledVelocity);
  12917. collider.collidedMesh = null;
  12918. collider.retry = 0;
  12919. collider.initialVelocity = this._scaledVelocity;
  12920. collider.initialPosition = this._scaledPosition;
  12921. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  12922. this._finalPosition.multiplyInPlace(collider.radius);
  12923. //run the callback
  12924. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  12925. };
  12926. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  12927. this._scene = scene;
  12928. };
  12929. CollisionCoordinatorLegacy.prototype.destroy = function () {
  12930. //Legacy need no destruction method.
  12931. };
  12932. //No update in legacy mode
  12933. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  12934. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  12935. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  12936. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  12937. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  12938. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  12939. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  12940. if (excludedMesh === void 0) { excludedMesh = null; }
  12941. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  12942. if (collider.retry >= maximumRetry) {
  12943. finalPosition.copyFrom(position);
  12944. return;
  12945. }
  12946. collider._initialize(position, velocity, closeDistance);
  12947. // Check all meshes
  12948. for (var index = 0; index < this._scene.meshes.length; index++) {
  12949. var mesh = this._scene.meshes[index];
  12950. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh) {
  12951. mesh._checkCollision(collider);
  12952. }
  12953. }
  12954. if (!collider.collisionFound) {
  12955. position.addToRef(velocity, finalPosition);
  12956. return;
  12957. }
  12958. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  12959. collider._getResponse(position, velocity);
  12960. }
  12961. if (velocity.length() <= closeDistance) {
  12962. finalPosition.copyFrom(position);
  12963. return;
  12964. }
  12965. collider.retry++;
  12966. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  12967. };
  12968. return CollisionCoordinatorLegacy;
  12969. }());
  12970. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  12971. })(BABYLON || (BABYLON = {}));
  12972. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  12973. var BABYLON;
  12974. (function (BABYLON) {
  12975. var Camera = (function (_super) {
  12976. __extends(Camera, _super);
  12977. function Camera(name, position, scene) {
  12978. var _this = _super.call(this, name, scene) || this;
  12979. _this.upVector = BABYLON.Vector3.Up();
  12980. _this.orthoLeft = null;
  12981. _this.orthoRight = null;
  12982. _this.orthoBottom = null;
  12983. _this.orthoTop = null;
  12984. _this.fov = 0.8;
  12985. _this.minZ = 1.0;
  12986. _this.maxZ = 10000.0;
  12987. _this.inertia = 0.9;
  12988. _this.mode = Camera.PERSPECTIVE_CAMERA;
  12989. _this.isIntermediate = false;
  12990. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  12991. _this.layerMask = 0x0FFFFFFF;
  12992. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  12993. // Camera rig members
  12994. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  12995. _this._rigCameras = new Array();
  12996. // Cache
  12997. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  12998. _this._projectionMatrix = new BABYLON.Matrix();
  12999. _this._doNotComputeProjectionMatrix = false;
  13000. _this._postProcesses = new Array();
  13001. _this._transformMatrix = BABYLON.Matrix.Zero();
  13002. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  13003. _this._activeMeshes = new BABYLON.SmartArray(256);
  13004. _this._globalPosition = BABYLON.Vector3.Zero();
  13005. _this._refreshFrustumPlanes = true;
  13006. scene.addCamera(_this);
  13007. if (!scene.activeCamera) {
  13008. scene.activeCamera = _this;
  13009. }
  13010. _this.position = position;
  13011. return _this;
  13012. }
  13013. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  13014. get: function () {
  13015. return Camera._PERSPECTIVE_CAMERA;
  13016. },
  13017. enumerable: true,
  13018. configurable: true
  13019. });
  13020. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  13021. get: function () {
  13022. return Camera._ORTHOGRAPHIC_CAMERA;
  13023. },
  13024. enumerable: true,
  13025. configurable: true
  13026. });
  13027. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  13028. get: function () {
  13029. return Camera._FOVMODE_VERTICAL_FIXED;
  13030. },
  13031. enumerable: true,
  13032. configurable: true
  13033. });
  13034. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  13035. get: function () {
  13036. return Camera._FOVMODE_HORIZONTAL_FIXED;
  13037. },
  13038. enumerable: true,
  13039. configurable: true
  13040. });
  13041. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  13042. get: function () {
  13043. return Camera._RIG_MODE_NONE;
  13044. },
  13045. enumerable: true,
  13046. configurable: true
  13047. });
  13048. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  13049. get: function () {
  13050. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  13051. },
  13052. enumerable: true,
  13053. configurable: true
  13054. });
  13055. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  13056. get: function () {
  13057. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  13058. },
  13059. enumerable: true,
  13060. configurable: true
  13061. });
  13062. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  13063. get: function () {
  13064. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13065. },
  13066. enumerable: true,
  13067. configurable: true
  13068. });
  13069. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  13070. get: function () {
  13071. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  13072. },
  13073. enumerable: true,
  13074. configurable: true
  13075. });
  13076. Object.defineProperty(Camera, "RIG_MODE_VR", {
  13077. get: function () {
  13078. return Camera._RIG_MODE_VR;
  13079. },
  13080. enumerable: true,
  13081. configurable: true
  13082. });
  13083. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  13084. get: function () {
  13085. return Camera._RIG_MODE_WEBVR;
  13086. },
  13087. enumerable: true,
  13088. configurable: true
  13089. });
  13090. Camera.prototype.getClassName = function () {
  13091. return "Camera";
  13092. };
  13093. /**
  13094. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  13095. */
  13096. Camera.prototype.toString = function (fullDetails) {
  13097. var ret = "Name: " + this.name;
  13098. ret += ", type: " + this.getClassName();
  13099. if (this.animations) {
  13100. for (var i = 0; i < this.animations.length; i++) {
  13101. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  13102. }
  13103. }
  13104. if (fullDetails) {
  13105. }
  13106. return ret;
  13107. };
  13108. Object.defineProperty(Camera.prototype, "globalPosition", {
  13109. get: function () {
  13110. return this._globalPosition;
  13111. },
  13112. enumerable: true,
  13113. configurable: true
  13114. });
  13115. Camera.prototype.getActiveMeshes = function () {
  13116. return this._activeMeshes;
  13117. };
  13118. Camera.prototype.isActiveMesh = function (mesh) {
  13119. return (this._activeMeshes.indexOf(mesh) !== -1);
  13120. };
  13121. //Cache
  13122. Camera.prototype._initCache = function () {
  13123. _super.prototype._initCache.call(this);
  13124. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13125. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  13126. this._cache.mode = undefined;
  13127. this._cache.minZ = undefined;
  13128. this._cache.maxZ = undefined;
  13129. this._cache.fov = undefined;
  13130. this._cache.fovMode = undefined;
  13131. this._cache.aspectRatio = undefined;
  13132. this._cache.orthoLeft = undefined;
  13133. this._cache.orthoRight = undefined;
  13134. this._cache.orthoBottom = undefined;
  13135. this._cache.orthoTop = undefined;
  13136. this._cache.renderWidth = undefined;
  13137. this._cache.renderHeight = undefined;
  13138. };
  13139. Camera.prototype._updateCache = function (ignoreParentClass) {
  13140. if (!ignoreParentClass) {
  13141. _super.prototype._updateCache.call(this);
  13142. }
  13143. var engine = this.getEngine();
  13144. this._cache.position.copyFrom(this.position);
  13145. this._cache.upVector.copyFrom(this.upVector);
  13146. this._cache.mode = this.mode;
  13147. this._cache.minZ = this.minZ;
  13148. this._cache.maxZ = this.maxZ;
  13149. this._cache.fov = this.fov;
  13150. this._cache.fovMode = this.fovMode;
  13151. this._cache.aspectRatio = engine.getAspectRatio(this);
  13152. this._cache.orthoLeft = this.orthoLeft;
  13153. this._cache.orthoRight = this.orthoRight;
  13154. this._cache.orthoBottom = this.orthoBottom;
  13155. this._cache.orthoTop = this.orthoTop;
  13156. this._cache.renderWidth = engine.getRenderWidth();
  13157. this._cache.renderHeight = engine.getRenderHeight();
  13158. };
  13159. Camera.prototype._updateFromScene = function () {
  13160. this.updateCache();
  13161. this.update();
  13162. };
  13163. // Synchronized
  13164. Camera.prototype._isSynchronized = function () {
  13165. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  13166. };
  13167. Camera.prototype._isSynchronizedViewMatrix = function () {
  13168. if (!_super.prototype._isSynchronized.call(this))
  13169. return false;
  13170. return this._cache.position.equals(this.position)
  13171. && this._cache.upVector.equals(this.upVector)
  13172. && this.isSynchronizedWithParent();
  13173. };
  13174. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  13175. var check = this._cache.mode === this.mode
  13176. && this._cache.minZ === this.minZ
  13177. && this._cache.maxZ === this.maxZ;
  13178. if (!check) {
  13179. return false;
  13180. }
  13181. var engine = this.getEngine();
  13182. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13183. check = this._cache.fov === this.fov
  13184. && this._cache.fovMode === this.fovMode
  13185. && this._cache.aspectRatio === engine.getAspectRatio(this);
  13186. }
  13187. else {
  13188. check = this._cache.orthoLeft === this.orthoLeft
  13189. && this._cache.orthoRight === this.orthoRight
  13190. && this._cache.orthoBottom === this.orthoBottom
  13191. && this._cache.orthoTop === this.orthoTop
  13192. && this._cache.renderWidth === engine.getRenderWidth()
  13193. && this._cache.renderHeight === engine.getRenderHeight();
  13194. }
  13195. return check;
  13196. };
  13197. // Controls
  13198. Camera.prototype.attachControl = function (element, noPreventDefault) {
  13199. };
  13200. Camera.prototype.detachControl = function (element) {
  13201. };
  13202. Camera.prototype.update = function () {
  13203. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13204. this._updateRigCameras();
  13205. }
  13206. this._checkInputs();
  13207. };
  13208. Camera.prototype._checkInputs = function () {
  13209. };
  13210. Camera.prototype._cascadePostProcessesToRigCams = function () {
  13211. // invalidate framebuffer
  13212. if (this._postProcesses.length > 0) {
  13213. this._postProcesses[0].markTextureDirty();
  13214. }
  13215. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  13216. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  13217. var cam = this._rigCameras[i];
  13218. var rigPostProcess = cam._rigPostProcess;
  13219. // for VR rig, there does not have to be a post process
  13220. if (rigPostProcess) {
  13221. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  13222. if (isPass) {
  13223. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  13224. cam.isIntermediate = this._postProcesses.length === 0;
  13225. }
  13226. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  13227. rigPostProcess.markTextureDirty();
  13228. }
  13229. else {
  13230. cam._postProcesses = this._postProcesses.slice(0);
  13231. }
  13232. }
  13233. };
  13234. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  13235. if (insertAt === void 0) { insertAt = null; }
  13236. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  13237. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  13238. return 0;
  13239. }
  13240. if (insertAt == null || insertAt < 0) {
  13241. this._postProcesses.push(postProcess);
  13242. }
  13243. else {
  13244. this._postProcesses.splice(insertAt, 0, postProcess);
  13245. }
  13246. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13247. return this._postProcesses.indexOf(postProcess);
  13248. };
  13249. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  13250. if (atIndices === void 0) { atIndices = null; }
  13251. var result = [];
  13252. var i;
  13253. var index;
  13254. if (!atIndices) {
  13255. var idx = this._postProcesses.indexOf(postProcess);
  13256. if (idx !== -1) {
  13257. this._postProcesses.splice(idx, 1);
  13258. }
  13259. }
  13260. else {
  13261. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  13262. // iterate descending, so can just splice as we go
  13263. for (i = atIndices.length - 1; i >= 0; i--) {
  13264. if (this._postProcesses[atIndices[i]] !== postProcess) {
  13265. result.push(i);
  13266. continue;
  13267. }
  13268. this._postProcesses.splice(index, 1);
  13269. }
  13270. }
  13271. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  13272. return result;
  13273. };
  13274. Camera.prototype.getWorldMatrix = function () {
  13275. if (!this._worldMatrix) {
  13276. this._worldMatrix = BABYLON.Matrix.Identity();
  13277. }
  13278. var viewMatrix = this.getViewMatrix();
  13279. viewMatrix.invertToRef(this._worldMatrix);
  13280. return this._worldMatrix;
  13281. };
  13282. Camera.prototype._getViewMatrix = function () {
  13283. return BABYLON.Matrix.Identity();
  13284. };
  13285. Camera.prototype.getViewMatrix = function (force) {
  13286. this._computedViewMatrix = this._computeViewMatrix(force);
  13287. if (!force && this._isSynchronizedViewMatrix()) {
  13288. return this._computedViewMatrix;
  13289. }
  13290. this._refreshFrustumPlanes = true;
  13291. if (!this.parent || !this.parent.getWorldMatrix) {
  13292. this._globalPosition.copyFrom(this.position);
  13293. }
  13294. else {
  13295. if (!this._worldMatrix) {
  13296. this._worldMatrix = BABYLON.Matrix.Identity();
  13297. }
  13298. this._computedViewMatrix.invertToRef(this._worldMatrix);
  13299. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  13300. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  13301. this._computedViewMatrix.invert();
  13302. this._markSyncedWithParent();
  13303. }
  13304. this._currentRenderId = this.getScene().getRenderId();
  13305. return this._computedViewMatrix;
  13306. };
  13307. Camera.prototype._computeViewMatrix = function (force) {
  13308. if (!force && this._isSynchronizedViewMatrix()) {
  13309. return this._computedViewMatrix;
  13310. }
  13311. this._computedViewMatrix = this._getViewMatrix();
  13312. this._currentRenderId = this.getScene().getRenderId();
  13313. return this._computedViewMatrix;
  13314. };
  13315. Camera.prototype.freezeProjectionMatrix = function (projection) {
  13316. this._doNotComputeProjectionMatrix = true;
  13317. if (projection !== undefined) {
  13318. this._projectionMatrix = projection;
  13319. }
  13320. };
  13321. ;
  13322. Camera.prototype.unfreezeProjectionMatrix = function () {
  13323. this._doNotComputeProjectionMatrix = false;
  13324. };
  13325. ;
  13326. Camera.prototype.getProjectionMatrix = function (force) {
  13327. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  13328. return this._projectionMatrix;
  13329. }
  13330. this._refreshFrustumPlanes = true;
  13331. var engine = this.getEngine();
  13332. var scene = this.getScene();
  13333. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  13334. if (this.minZ <= 0) {
  13335. this.minZ = 0.1;
  13336. }
  13337. if (scene.useRightHandedSystem) {
  13338. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13339. }
  13340. else {
  13341. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  13342. }
  13343. return this._projectionMatrix;
  13344. }
  13345. var halfWidth = engine.getRenderWidth() / 2.0;
  13346. var halfHeight = engine.getRenderHeight() / 2.0;
  13347. if (scene.useRightHandedSystem) {
  13348. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13349. }
  13350. else {
  13351. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  13352. }
  13353. return this._projectionMatrix;
  13354. };
  13355. Camera.prototype.getTranformationMatrix = function () {
  13356. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  13357. return this._transformMatrix;
  13358. };
  13359. Camera.prototype.updateFrustumPlanes = function () {
  13360. if (!this._refreshFrustumPlanes) {
  13361. return;
  13362. }
  13363. this.getTranformationMatrix();
  13364. if (!this._frustumPlanes) {
  13365. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  13366. }
  13367. else {
  13368. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  13369. }
  13370. this._refreshFrustumPlanes = false;
  13371. };
  13372. Camera.prototype.isInFrustum = function (target) {
  13373. this.updateFrustumPlanes();
  13374. return target.isInFrustum(this._frustumPlanes);
  13375. };
  13376. Camera.prototype.isCompletelyInFrustum = function (target) {
  13377. this.updateFrustumPlanes();
  13378. return target.isCompletelyInFrustum(this._frustumPlanes);
  13379. };
  13380. Camera.prototype.dispose = function () {
  13381. // Animations
  13382. this.getScene().stopAnimation(this);
  13383. // Remove from scene
  13384. this.getScene().removeCamera(this);
  13385. while (this._rigCameras.length > 0) {
  13386. this._rigCameras.pop().dispose();
  13387. }
  13388. // Postprocesses
  13389. var i = this._postProcesses.length;
  13390. while (--i >= 0) {
  13391. this._postProcesses[i].dispose(this);
  13392. }
  13393. _super.prototype.dispose.call(this);
  13394. };
  13395. // ---- Camera rigs section ----
  13396. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  13397. while (this._rigCameras.length > 0) {
  13398. this._rigCameras.pop().dispose();
  13399. }
  13400. this.cameraRigMode = mode;
  13401. this._cameraRigParams = {};
  13402. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  13403. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  13404. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  13405. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  13406. // create the rig cameras, unless none
  13407. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  13408. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  13409. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  13410. }
  13411. switch (this.cameraRigMode) {
  13412. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  13413. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13414. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  13415. break;
  13416. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  13417. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  13418. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  13419. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  13420. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  13421. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  13422. break;
  13423. case Camera.RIG_MODE_VR:
  13424. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  13425. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  13426. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13427. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13428. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  13429. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  13430. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  13431. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  13432. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13433. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13434. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  13435. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  13436. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  13437. if (metrics.compensateDistortion) {
  13438. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  13439. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  13440. }
  13441. break;
  13442. case Camera.RIG_MODE_WEBVR:
  13443. if (rigParams.vrDisplay) {
  13444. //var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  13445. //var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  13446. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  13447. this._rigCameras[0].setCameraRigParameter("left", true);
  13448. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  13449. //this._rigCameras[0].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-leftEye.offset[0], leftEye.offset[1], -leftEye.offset[2]));
  13450. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13451. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13452. //this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  13453. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  13454. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  13455. //this._rigCameras[1].setCameraRigParameter("vrOffsetMatrix", Matrix.Translation(-rightEye.offset[0], rightEye.offset[1], -rightEye.offset[2]));
  13456. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  13457. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  13458. }
  13459. break;
  13460. }
  13461. this._cascadePostProcessesToRigCams();
  13462. this.
  13463. update();
  13464. };
  13465. Camera.prototype._getVRProjectionMatrix = function () {
  13466. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  13467. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  13468. return this._projectionMatrix;
  13469. };
  13470. Camera.prototype._getWebVRProjectionMatrix = function () {
  13471. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  13472. //babylon compatible matrix
  13473. [8, 9, 10, 11].forEach(function (num) {
  13474. projectionArray[num] *= -1;
  13475. });
  13476. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  13477. return this._projectionMatrix;
  13478. };
  13479. //Can be used, but we'll use the free camera's view matrix calculation
  13480. Camera.prototype._getWebVRViewMatrix = function () {
  13481. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  13482. //babylon compatible matrix
  13483. [8, 9, 10, 11].forEach(function (num) {
  13484. projectionArray[num] *= -1;
  13485. });
  13486. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._webvrViewMatrix);
  13487. return this._webvrViewMatrix;
  13488. };
  13489. Camera.prototype.setCameraRigParameter = function (name, value) {
  13490. if (!this._cameraRigParams) {
  13491. this._cameraRigParams = {};
  13492. }
  13493. this._cameraRigParams[name] = value;
  13494. //provisionnally:
  13495. if (name === "interaxialDistance") {
  13496. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  13497. }
  13498. };
  13499. /**
  13500. * needs to be overridden by children so sub has required properties to be copied
  13501. */
  13502. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  13503. return null;
  13504. };
  13505. /**
  13506. * May need to be overridden by children
  13507. */
  13508. Camera.prototype._updateRigCameras = function () {
  13509. for (var i = 0; i < this._rigCameras.length; i++) {
  13510. this._rigCameras[i].minZ = this.minZ;
  13511. this._rigCameras[i].maxZ = this.maxZ;
  13512. this._rigCameras[i].fov = this.fov;
  13513. }
  13514. // only update viewport when ANAGLYPH
  13515. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  13516. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  13517. }
  13518. };
  13519. Camera.prototype._setupInputs = function () {
  13520. };
  13521. Camera.prototype.serialize = function () {
  13522. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  13523. // Type
  13524. serializationObject.type = this.getClassName();
  13525. // Parent
  13526. if (this.parent) {
  13527. serializationObject.parentId = this.parent.id;
  13528. }
  13529. if (this.inputs) {
  13530. this.inputs.serialize(serializationObject);
  13531. }
  13532. // Animations
  13533. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  13534. serializationObject.ranges = this.serializeAnimationRanges();
  13535. return serializationObject;
  13536. };
  13537. Camera.prototype.clone = function (name) {
  13538. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  13539. };
  13540. Camera.prototype.getDirection = function (localAxis) {
  13541. var result = BABYLON.Vector3.Zero();
  13542. this.getDirectionToRef(localAxis, result);
  13543. return result;
  13544. };
  13545. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  13546. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13547. };
  13548. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  13549. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  13550. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  13551. switch (type) {
  13552. case "ArcRotateCamera":
  13553. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  13554. case "DeviceOrientationCamera":
  13555. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  13556. case "FollowCamera":
  13557. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  13558. case "ArcFollowCamera":
  13559. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  13560. case "GamepadCamera":
  13561. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  13562. case "TouchCamera":
  13563. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  13564. case "VirtualJoysticksCamera":
  13565. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  13566. case "WebVRFreeCamera":
  13567. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13568. case "VRDeviceOrientationFreeCamera":
  13569. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  13570. case "AnaglyphArcRotateCamera":
  13571. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13572. case "AnaglyphFreeCamera":
  13573. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13574. case "AnaglyphGamepadCamera":
  13575. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13576. case "AnaglyphUniversalCamera":
  13577. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  13578. case "StereoscopicArcRotateCamera":
  13579. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13580. case "StereoscopicFreeCamera":
  13581. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13582. case "StereoscopicGamepadCamera":
  13583. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13584. case "StereoscopicUniversalCamera":
  13585. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  13586. case "FreeCamera":
  13587. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13588. default:
  13589. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  13590. }
  13591. };
  13592. Camera.Parse = function (parsedCamera, scene) {
  13593. var type = parsedCamera.type;
  13594. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  13595. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  13596. // Parent
  13597. if (parsedCamera.parentId) {
  13598. camera._waitingParentId = parsedCamera.parentId;
  13599. }
  13600. //If camera has an input manager, let it parse inputs settings
  13601. if (camera.inputs) {
  13602. camera.inputs.parse(parsedCamera);
  13603. camera._setupInputs();
  13604. }
  13605. // Target
  13606. if (parsedCamera.target) {
  13607. if (camera.setTarget) {
  13608. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  13609. }
  13610. }
  13611. // Apply 3d rig, when found
  13612. if (parsedCamera.cameraRigMode) {
  13613. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  13614. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  13615. }
  13616. // Animations
  13617. if (parsedCamera.animations) {
  13618. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  13619. var parsedAnimation = parsedCamera.animations[animationIndex];
  13620. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  13621. }
  13622. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  13623. }
  13624. if (parsedCamera.autoAnimate) {
  13625. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  13626. }
  13627. return camera;
  13628. };
  13629. return Camera;
  13630. }(BABYLON.Node));
  13631. // Statics
  13632. Camera._PERSPECTIVE_CAMERA = 0;
  13633. Camera._ORTHOGRAPHIC_CAMERA = 1;
  13634. Camera._FOVMODE_VERTICAL_FIXED = 0;
  13635. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  13636. Camera._RIG_MODE_NONE = 0;
  13637. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  13638. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  13639. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  13640. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  13641. Camera._RIG_MODE_VR = 20;
  13642. Camera._RIG_MODE_WEBVR = 21;
  13643. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  13644. __decorate([
  13645. BABYLON.serializeAsVector3()
  13646. ], Camera.prototype, "position", void 0);
  13647. __decorate([
  13648. BABYLON.serializeAsVector3()
  13649. ], Camera.prototype, "upVector", void 0);
  13650. __decorate([
  13651. BABYLON.serialize()
  13652. ], Camera.prototype, "orthoLeft", void 0);
  13653. __decorate([
  13654. BABYLON.serialize()
  13655. ], Camera.prototype, "orthoRight", void 0);
  13656. __decorate([
  13657. BABYLON.serialize()
  13658. ], Camera.prototype, "orthoBottom", void 0);
  13659. __decorate([
  13660. BABYLON.serialize()
  13661. ], Camera.prototype, "orthoTop", void 0);
  13662. __decorate([
  13663. BABYLON.serialize()
  13664. ], Camera.prototype, "fov", void 0);
  13665. __decorate([
  13666. BABYLON.serialize()
  13667. ], Camera.prototype, "minZ", void 0);
  13668. __decorate([
  13669. BABYLON.serialize()
  13670. ], Camera.prototype, "maxZ", void 0);
  13671. __decorate([
  13672. BABYLON.serialize()
  13673. ], Camera.prototype, "inertia", void 0);
  13674. __decorate([
  13675. BABYLON.serialize()
  13676. ], Camera.prototype, "mode", void 0);
  13677. __decorate([
  13678. BABYLON.serialize()
  13679. ], Camera.prototype, "layerMask", void 0);
  13680. __decorate([
  13681. BABYLON.serialize()
  13682. ], Camera.prototype, "fovMode", void 0);
  13683. __decorate([
  13684. BABYLON.serialize()
  13685. ], Camera.prototype, "cameraRigMode", void 0);
  13686. __decorate([
  13687. BABYLON.serialize()
  13688. ], Camera.prototype, "interaxialDistance", void 0);
  13689. __decorate([
  13690. BABYLON.serialize()
  13691. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  13692. BABYLON.Camera = Camera;
  13693. })(BABYLON || (BABYLON = {}));
  13694. //# sourceMappingURL=babylon.camera.js.map
  13695. var BABYLON;
  13696. (function (BABYLON) {
  13697. BABYLON.CameraInputTypes = {};
  13698. var CameraInputsManager = (function () {
  13699. function CameraInputsManager(camera) {
  13700. this.attached = {};
  13701. this.camera = camera;
  13702. this.checkInputs = function () { };
  13703. }
  13704. CameraInputsManager.prototype.add = function (input) {
  13705. var type = input.getSimpleName();
  13706. if (this.attached[type]) {
  13707. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  13708. return;
  13709. }
  13710. this.attached[type] = input;
  13711. input.camera = this.camera;
  13712. //for checkInputs, we are dynamically creating a function
  13713. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  13714. if (input.checkInputs) {
  13715. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13716. }
  13717. if (this.attachedElement) {
  13718. input.attachControl(this.attachedElement);
  13719. }
  13720. };
  13721. CameraInputsManager.prototype.remove = function (inputToRemove) {
  13722. for (var cam in this.attached) {
  13723. var input = this.attached[cam];
  13724. if (input === inputToRemove) {
  13725. input.detachControl(this.attachedElement);
  13726. delete this.attached[cam];
  13727. this.rebuildInputCheck();
  13728. }
  13729. }
  13730. };
  13731. CameraInputsManager.prototype.removeByType = function (inputType) {
  13732. for (var cam in this.attached) {
  13733. var input = this.attached[cam];
  13734. if (input.getTypeName() === inputType) {
  13735. input.detachControl(this.attachedElement);
  13736. delete this.attached[cam];
  13737. this.rebuildInputCheck();
  13738. }
  13739. }
  13740. };
  13741. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  13742. var current = this.checkInputs;
  13743. return function () {
  13744. current();
  13745. fn();
  13746. };
  13747. };
  13748. CameraInputsManager.prototype.attachInput = function (input) {
  13749. input.attachControl(this.attachedElement, this.noPreventDefault);
  13750. };
  13751. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  13752. if (this.attachedElement) {
  13753. return;
  13754. }
  13755. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  13756. this.attachedElement = element;
  13757. this.noPreventDefault = noPreventDefault;
  13758. for (var cam in this.attached) {
  13759. var input = this.attached[cam];
  13760. this.attached[cam].attachControl(element, noPreventDefault);
  13761. }
  13762. };
  13763. CameraInputsManager.prototype.detachElement = function (element) {
  13764. if (this.attachedElement !== element) {
  13765. return;
  13766. }
  13767. for (var cam in this.attached) {
  13768. var input = this.attached[cam];
  13769. this.attached[cam].detachControl(element);
  13770. }
  13771. this.attachedElement = null;
  13772. };
  13773. CameraInputsManager.prototype.rebuildInputCheck = function () {
  13774. this.checkInputs = function () { };
  13775. for (var cam in this.attached) {
  13776. var input = this.attached[cam];
  13777. if (input.checkInputs) {
  13778. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  13779. }
  13780. }
  13781. };
  13782. CameraInputsManager.prototype.clear = function () {
  13783. if (this.attachedElement) {
  13784. this.detachElement(this.attachedElement);
  13785. }
  13786. this.attached = {};
  13787. this.attachedElement = null;
  13788. this.checkInputs = function () { };
  13789. };
  13790. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  13791. var inputs = {};
  13792. for (var cam in this.attached) {
  13793. var input = this.attached[cam];
  13794. var res = BABYLON.SerializationHelper.Serialize(input);
  13795. inputs[input.getTypeName()] = res;
  13796. }
  13797. serializedCamera.inputsmgr = inputs;
  13798. };
  13799. CameraInputsManager.prototype.parse = function (parsedCamera) {
  13800. var parsedInputs = parsedCamera.inputsmgr;
  13801. if (parsedInputs) {
  13802. this.clear();
  13803. for (var n in parsedInputs) {
  13804. var construct = BABYLON.CameraInputTypes[n];
  13805. if (construct) {
  13806. var parsedinput = parsedInputs[n];
  13807. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  13808. this.add(input);
  13809. }
  13810. }
  13811. }
  13812. else {
  13813. //2016-03-08 this part is for managing backward compatibility
  13814. for (var n in this.attached) {
  13815. var construct = BABYLON.CameraInputTypes[this.attached[n].getTypeName()];
  13816. if (construct) {
  13817. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  13818. this.remove(this.attached[n]);
  13819. this.add(input);
  13820. }
  13821. }
  13822. }
  13823. };
  13824. return CameraInputsManager;
  13825. }());
  13826. BABYLON.CameraInputsManager = CameraInputsManager;
  13827. })(BABYLON || (BABYLON = {}));
  13828. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  13829. var BABYLON;
  13830. (function (BABYLON) {
  13831. var FreeCameraMouseInput = (function () {
  13832. function FreeCameraMouseInput(touchEnabled) {
  13833. if (touchEnabled === void 0) { touchEnabled = true; }
  13834. this.touchEnabled = touchEnabled;
  13835. this.buttons = [0, 1, 2];
  13836. this.angularSensibility = 2000.0;
  13837. }
  13838. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  13839. var _this = this;
  13840. var engine = this.camera.getEngine();
  13841. if (!this._pointerInput) {
  13842. this._pointerInput = function (p, s) {
  13843. var evt = p.event;
  13844. if (!_this.touchEnabled && evt.pointerType === "touch") {
  13845. return;
  13846. }
  13847. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  13848. return;
  13849. }
  13850. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  13851. try {
  13852. evt.srcElement.setPointerCapture(evt.pointerId);
  13853. }
  13854. catch (e) {
  13855. }
  13856. _this.previousPosition = {
  13857. x: evt.clientX,
  13858. y: evt.clientY
  13859. };
  13860. if (!noPreventDefault) {
  13861. evt.preventDefault();
  13862. element.focus();
  13863. }
  13864. }
  13865. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  13866. try {
  13867. evt.srcElement.releasePointerCapture(evt.pointerId);
  13868. }
  13869. catch (e) {
  13870. }
  13871. _this.previousPosition = null;
  13872. if (!noPreventDefault) {
  13873. evt.preventDefault();
  13874. }
  13875. }
  13876. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  13877. if (!_this.previousPosition || engine.isPointerLock) {
  13878. return;
  13879. }
  13880. var offsetX = evt.clientX - _this.previousPosition.x;
  13881. var offsetY = evt.clientY - _this.previousPosition.y;
  13882. if (_this.camera.getScene().useRightHandedSystem) {
  13883. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13884. }
  13885. else {
  13886. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13887. }
  13888. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13889. _this.previousPosition = {
  13890. x: evt.clientX,
  13891. y: evt.clientY
  13892. };
  13893. if (!noPreventDefault) {
  13894. evt.preventDefault();
  13895. }
  13896. }
  13897. };
  13898. }
  13899. this._onMouseMove = function (evt) {
  13900. if (!engine.isPointerLock) {
  13901. return;
  13902. }
  13903. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  13904. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  13905. if (_this.camera.getScene().useRightHandedSystem) {
  13906. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  13907. }
  13908. else {
  13909. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  13910. }
  13911. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  13912. _this.previousPosition = null;
  13913. if (!noPreventDefault) {
  13914. evt.preventDefault();
  13915. }
  13916. };
  13917. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  13918. element.addEventListener("mousemove", this._onMouseMove, false);
  13919. };
  13920. FreeCameraMouseInput.prototype.detachControl = function (element) {
  13921. if (this._observer && element) {
  13922. this.camera.getScene().onPointerObservable.remove(this._observer);
  13923. element.removeEventListener("mousemove", this._onMouseMove);
  13924. this._observer = null;
  13925. this._onMouseMove = null;
  13926. this.previousPosition = null;
  13927. }
  13928. };
  13929. FreeCameraMouseInput.prototype.getTypeName = function () {
  13930. return "FreeCameraMouseInput";
  13931. };
  13932. FreeCameraMouseInput.prototype.getSimpleName = function () {
  13933. return "mouse";
  13934. };
  13935. return FreeCameraMouseInput;
  13936. }());
  13937. __decorate([
  13938. BABYLON.serialize()
  13939. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  13940. __decorate([
  13941. BABYLON.serialize()
  13942. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  13943. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  13944. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  13945. })(BABYLON || (BABYLON = {}));
  13946. //# sourceMappingURL=babylon.freecamera.input.mouse.js.map
  13947. var BABYLON;
  13948. (function (BABYLON) {
  13949. var FreeCameraKeyboardMoveInput = (function () {
  13950. function FreeCameraKeyboardMoveInput() {
  13951. this._keys = [];
  13952. this.keysUp = [38];
  13953. this.keysDown = [40];
  13954. this.keysLeft = [37];
  13955. this.keysRight = [39];
  13956. }
  13957. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  13958. var _this = this;
  13959. if (!this._onKeyDown) {
  13960. element.tabIndex = 1;
  13961. this._onKeyDown = function (evt) {
  13962. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13963. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13964. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13965. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13966. var index = _this._keys.indexOf(evt.keyCode);
  13967. if (index === -1) {
  13968. _this._keys.push(evt.keyCode);
  13969. }
  13970. if (!noPreventDefault) {
  13971. evt.preventDefault();
  13972. }
  13973. }
  13974. };
  13975. this._onKeyUp = function (evt) {
  13976. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  13977. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  13978. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  13979. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  13980. var index = _this._keys.indexOf(evt.keyCode);
  13981. if (index >= 0) {
  13982. _this._keys.splice(index, 1);
  13983. }
  13984. if (!noPreventDefault) {
  13985. evt.preventDefault();
  13986. }
  13987. }
  13988. };
  13989. element.addEventListener("keydown", this._onKeyDown, false);
  13990. element.addEventListener("keyup", this._onKeyUp, false);
  13991. BABYLON.Tools.RegisterTopRootEvents([
  13992. { name: "blur", handler: this._onLostFocus }
  13993. ]);
  13994. }
  13995. };
  13996. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  13997. if (this._onKeyDown) {
  13998. element.removeEventListener("keydown", this._onKeyDown);
  13999. element.removeEventListener("keyup", this._onKeyUp);
  14000. BABYLON.Tools.UnregisterTopRootEvents([
  14001. { name: "blur", handler: this._onLostFocus }
  14002. ]);
  14003. this._keys = [];
  14004. this._onKeyDown = null;
  14005. this._onKeyUp = null;
  14006. }
  14007. };
  14008. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14009. if (this._onKeyDown) {
  14010. var camera = this.camera;
  14011. // Keyboard
  14012. for (var index = 0; index < this._keys.length; index++) {
  14013. var keyCode = this._keys[index];
  14014. var speed = camera._computeLocalCameraSpeed();
  14015. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14016. camera._localDirection.copyFromFloats(-speed, 0, 0);
  14017. }
  14018. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14019. camera._localDirection.copyFromFloats(0, 0, speed);
  14020. }
  14021. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14022. camera._localDirection.copyFromFloats(speed, 0, 0);
  14023. }
  14024. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14025. camera._localDirection.copyFromFloats(0, 0, -speed);
  14026. }
  14027. if (camera.getScene().useRightHandedSystem) {
  14028. camera._localDirection.z *= -1;
  14029. }
  14030. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  14031. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  14032. camera.cameraDirection.addInPlace(camera._transformedDirection);
  14033. }
  14034. }
  14035. };
  14036. FreeCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14037. return "FreeCameraKeyboardMoveInput";
  14038. };
  14039. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  14040. this._keys = [];
  14041. };
  14042. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14043. return "keyboard";
  14044. };
  14045. return FreeCameraKeyboardMoveInput;
  14046. }());
  14047. __decorate([
  14048. BABYLON.serialize()
  14049. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14050. __decorate([
  14051. BABYLON.serialize()
  14052. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14053. __decorate([
  14054. BABYLON.serialize()
  14055. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14056. __decorate([
  14057. BABYLON.serialize()
  14058. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14059. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  14060. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  14061. })(BABYLON || (BABYLON = {}));
  14062. //# sourceMappingURL=babylon.freecamera.input.keyboard.js.map
  14063. var BABYLON;
  14064. (function (BABYLON) {
  14065. var FreeCameraTouchInput = (function () {
  14066. function FreeCameraTouchInput() {
  14067. this._offsetX = null;
  14068. this._offsetY = null;
  14069. this._pointerCount = 0;
  14070. this._pointerPressed = [];
  14071. this.touchAngularSensibility = 200000.0;
  14072. this.touchMoveSensibility = 250.0;
  14073. }
  14074. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  14075. var _this = this;
  14076. var previousPosition;
  14077. if (this._pointerInput === undefined) {
  14078. this._onLostFocus = function (evt) {
  14079. _this._offsetX = null;
  14080. _this._offsetY = null;
  14081. };
  14082. this._pointerInput = function (p, s) {
  14083. var evt = p.event;
  14084. if (evt.pointerType === "mouse") {
  14085. return;
  14086. }
  14087. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14088. if (!noPreventDefault) {
  14089. evt.preventDefault();
  14090. }
  14091. _this._pointerPressed.push(evt.pointerId);
  14092. if (_this._pointerPressed.length !== 1) {
  14093. return;
  14094. }
  14095. previousPosition = {
  14096. x: evt.clientX,
  14097. y: evt.clientY
  14098. };
  14099. }
  14100. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14101. if (!noPreventDefault) {
  14102. evt.preventDefault();
  14103. }
  14104. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14105. if (index === -1) {
  14106. return;
  14107. }
  14108. _this._pointerPressed.splice(index, 1);
  14109. if (index != 0) {
  14110. return;
  14111. }
  14112. previousPosition = null;
  14113. _this._offsetX = null;
  14114. _this._offsetY = null;
  14115. }
  14116. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14117. if (!noPreventDefault) {
  14118. evt.preventDefault();
  14119. }
  14120. if (!previousPosition) {
  14121. return;
  14122. }
  14123. var index = _this._pointerPressed.indexOf(evt.pointerId);
  14124. if (index != 0) {
  14125. return;
  14126. }
  14127. _this._offsetX = evt.clientX - previousPosition.x;
  14128. _this._offsetY = -(evt.clientY - previousPosition.y);
  14129. }
  14130. };
  14131. }
  14132. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14133. element.addEventListener("blur", this._onLostFocus);
  14134. };
  14135. FreeCameraTouchInput.prototype.detachControl = function (element) {
  14136. if (this._pointerInput && element) {
  14137. this.camera.getScene().onPointerObservable.remove(this._observer);
  14138. this._observer = null;
  14139. element.removeEventListener("blur", this._onLostFocus);
  14140. this._onLostFocus = null;
  14141. this._pointerPressed = [];
  14142. this._offsetX = null;
  14143. this._offsetY = null;
  14144. this._pointerCount = 0;
  14145. }
  14146. };
  14147. FreeCameraTouchInput.prototype.checkInputs = function () {
  14148. if (this._offsetX) {
  14149. var camera = this.camera;
  14150. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  14151. if (this._pointerPressed.length > 1) {
  14152. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  14153. }
  14154. else {
  14155. var speed = camera._computeLocalCameraSpeed();
  14156. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  14157. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  14158. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  14159. }
  14160. }
  14161. };
  14162. FreeCameraTouchInput.prototype.getTypeName = function () {
  14163. return "FreeCameraTouchInput";
  14164. };
  14165. FreeCameraTouchInput.prototype.getSimpleName = function () {
  14166. return "touch";
  14167. };
  14168. return FreeCameraTouchInput;
  14169. }());
  14170. __decorate([
  14171. BABYLON.serialize()
  14172. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  14173. __decorate([
  14174. BABYLON.serialize()
  14175. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  14176. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  14177. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  14178. })(BABYLON || (BABYLON = {}));
  14179. //# sourceMappingURL=babylon.freecamera.input.touch.js.map
  14180. var BABYLON;
  14181. (function (BABYLON) {
  14182. var FreeCameraDeviceOrientationInput = (function () {
  14183. function FreeCameraDeviceOrientationInput() {
  14184. var _this = this;
  14185. this._screenOrientationAngle = 0;
  14186. this._screenQuaternion = new BABYLON.Quaternion();
  14187. this._alpha = 0;
  14188. this._beta = 0;
  14189. this._gamma = 0;
  14190. this._orientationChanged = function () {
  14191. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  14192. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  14193. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  14194. };
  14195. this._deviceOrientation = function (evt) {
  14196. _this._alpha = evt.alpha;
  14197. _this._beta = evt.beta;
  14198. _this._gamma = evt.gamma;
  14199. };
  14200. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  14201. this._orientationChanged();
  14202. }
  14203. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  14204. get: function () {
  14205. return this._camera;
  14206. },
  14207. set: function (camera) {
  14208. this._camera = camera;
  14209. if (!this._camera.rotationQuaternion)
  14210. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  14211. },
  14212. enumerable: true,
  14213. configurable: true
  14214. });
  14215. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14216. window.addEventListener("orientationchange", this._orientationChanged);
  14217. window.addEventListener("deviceorientation", this._deviceOrientation);
  14218. //In certain cases, the attach control is called AFTER orientation was changed,
  14219. //So this is needed.
  14220. this._orientationChanged();
  14221. };
  14222. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  14223. window.removeEventListener("orientationchange", this._orientationChanged);
  14224. window.removeEventListener("deviceorientation", this._deviceOrientation);
  14225. };
  14226. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  14227. //if no device orientation provided, don't update the rotation.
  14228. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  14229. if (!this._alpha)
  14230. return;
  14231. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  14232. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  14233. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  14234. //Mirror on XY Plane
  14235. this._camera.rotationQuaternion.z *= -1;
  14236. this._camera.rotationQuaternion.w *= -1;
  14237. };
  14238. FreeCameraDeviceOrientationInput.prototype.getTypeName = function () {
  14239. return "FreeCameraDeviceOrientationInput";
  14240. };
  14241. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  14242. return "deviceOrientation";
  14243. };
  14244. return FreeCameraDeviceOrientationInput;
  14245. }());
  14246. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  14247. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  14248. })(BABYLON || (BABYLON = {}));
  14249. //# sourceMappingURL=babylon.freecamera.input.deviceorientation.js.map
  14250. var BABYLON;
  14251. (function (BABYLON) {
  14252. var FreeCameraGamepadInput = (function () {
  14253. function FreeCameraGamepadInput() {
  14254. this.gamepadAngularSensibility = 200;
  14255. this.gamepadMoveSensibility = 40;
  14256. }
  14257. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14258. var _this = this;
  14259. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14260. };
  14261. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  14262. if (this._gamepads) {
  14263. this._gamepads.dispose();
  14264. }
  14265. this.gamepad = null;
  14266. };
  14267. FreeCameraGamepadInput.prototype.checkInputs = function () {
  14268. if (this.gamepad) {
  14269. var camera = this.camera;
  14270. var LSValues = this.gamepad.leftStick;
  14271. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  14272. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14273. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  14274. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  14275. var RSValues = this.gamepad.rightStick;
  14276. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  14277. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  14278. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  14279. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  14280. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  14281. var speed = camera._computeLocalCameraSpeed() * 50.0;
  14282. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(LSValues.x * speed, 0, -LSValues.y * speed), cameraTransform);
  14283. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  14284. camera.cameraRotation = camera.cameraRotation.add(new BABYLON.Vector2(RSValues.y, RSValues.x));
  14285. }
  14286. };
  14287. FreeCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14288. // Only the first gamepad can control the camera
  14289. if (gamepad.index === 0) {
  14290. this.gamepad = gamepad;
  14291. }
  14292. };
  14293. FreeCameraGamepadInput.prototype.getTypeName = function () {
  14294. return "FreeCameraGamepadInput";
  14295. };
  14296. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  14297. return "gamepad";
  14298. };
  14299. return FreeCameraGamepadInput;
  14300. }());
  14301. __decorate([
  14302. BABYLON.serialize()
  14303. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  14304. __decorate([
  14305. BABYLON.serialize()
  14306. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14307. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  14308. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  14309. })(BABYLON || (BABYLON = {}));
  14310. //# sourceMappingURL=babylon.freecamera.input.gamepad.js.map
  14311. var BABYLON;
  14312. (function (BABYLON) {
  14313. var ArcRotateCameraKeyboardMoveInput = (function () {
  14314. function ArcRotateCameraKeyboardMoveInput() {
  14315. this._keys = [];
  14316. this.keysUp = [38];
  14317. this.keysDown = [40];
  14318. this.keysLeft = [37];
  14319. this.keysRight = [39];
  14320. }
  14321. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  14322. var _this = this;
  14323. element.tabIndex = 1;
  14324. this._onKeyDown = function (evt) {
  14325. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14326. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14327. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14328. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14329. var index = _this._keys.indexOf(evt.keyCode);
  14330. if (index === -1) {
  14331. _this._keys.push(evt.keyCode);
  14332. }
  14333. if (evt.preventDefault) {
  14334. if (!noPreventDefault) {
  14335. evt.preventDefault();
  14336. }
  14337. }
  14338. }
  14339. };
  14340. this._onKeyUp = function (evt) {
  14341. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  14342. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  14343. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  14344. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  14345. var index = _this._keys.indexOf(evt.keyCode);
  14346. if (index >= 0) {
  14347. _this._keys.splice(index, 1);
  14348. }
  14349. if (evt.preventDefault) {
  14350. if (!noPreventDefault) {
  14351. evt.preventDefault();
  14352. }
  14353. }
  14354. }
  14355. };
  14356. this._onLostFocus = function () {
  14357. _this._keys = [];
  14358. };
  14359. element.addEventListener("keydown", this._onKeyDown, false);
  14360. element.addEventListener("keyup", this._onKeyUp, false);
  14361. BABYLON.Tools.RegisterTopRootEvents([
  14362. { name: "blur", handler: this._onLostFocus }
  14363. ]);
  14364. };
  14365. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  14366. if (element) {
  14367. element.removeEventListener("keydown", this._onKeyDown);
  14368. element.removeEventListener("keyup", this._onKeyUp);
  14369. }
  14370. BABYLON.Tools.UnregisterTopRootEvents([
  14371. { name: "blur", handler: this._onLostFocus }
  14372. ]);
  14373. this._keys = [];
  14374. this._onKeyDown = null;
  14375. this._onKeyUp = null;
  14376. this._onLostFocus = null;
  14377. };
  14378. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  14379. if (this._onKeyDown) {
  14380. var camera = this.camera;
  14381. for (var index = 0; index < this._keys.length; index++) {
  14382. var keyCode = this._keys[index];
  14383. if (this.keysLeft.indexOf(keyCode) !== -1) {
  14384. camera.inertialAlphaOffset -= 0.01;
  14385. }
  14386. else if (this.keysUp.indexOf(keyCode) !== -1) {
  14387. camera.inertialBetaOffset -= 0.01;
  14388. }
  14389. else if (this.keysRight.indexOf(keyCode) !== -1) {
  14390. camera.inertialAlphaOffset += 0.01;
  14391. }
  14392. else if (this.keysDown.indexOf(keyCode) !== -1) {
  14393. camera.inertialBetaOffset += 0.01;
  14394. }
  14395. }
  14396. }
  14397. };
  14398. ArcRotateCameraKeyboardMoveInput.prototype.getTypeName = function () {
  14399. return "ArcRotateCameraKeyboardMoveInput";
  14400. };
  14401. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  14402. return "keyboard";
  14403. };
  14404. return ArcRotateCameraKeyboardMoveInput;
  14405. }());
  14406. __decorate([
  14407. BABYLON.serialize()
  14408. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  14409. __decorate([
  14410. BABYLON.serialize()
  14411. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  14412. __decorate([
  14413. BABYLON.serialize()
  14414. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  14415. __decorate([
  14416. BABYLON.serialize()
  14417. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  14418. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  14419. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  14420. })(BABYLON || (BABYLON = {}));
  14421. //# sourceMappingURL=babylon.arcrotatecamera.input.keyboard.js.map
  14422. var BABYLON;
  14423. (function (BABYLON) {
  14424. var ArcRotateCameraMouseWheelInput = (function () {
  14425. function ArcRotateCameraMouseWheelInput() {
  14426. this.wheelPrecision = 3.0;
  14427. }
  14428. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  14429. var _this = this;
  14430. this._wheel = function (p, s) {
  14431. //sanity check - this should be a PointerWheel event.
  14432. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  14433. return;
  14434. var event = p.event;
  14435. var delta = 0;
  14436. if (event.wheelDelta) {
  14437. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  14438. }
  14439. else if (event.detail) {
  14440. delta = -event.detail / _this.wheelPrecision;
  14441. }
  14442. if (delta)
  14443. _this.camera.inertialRadiusOffset += delta;
  14444. if (event.preventDefault) {
  14445. if (!noPreventDefault) {
  14446. event.preventDefault();
  14447. }
  14448. }
  14449. };
  14450. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  14451. };
  14452. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  14453. if (this._observer && element) {
  14454. this.camera.getScene().onPointerObservable.remove(this._observer);
  14455. this._observer = null;
  14456. this._wheel = null;
  14457. }
  14458. };
  14459. ArcRotateCameraMouseWheelInput.prototype.getTypeName = function () {
  14460. return "ArcRotateCameraMouseWheelInput";
  14461. };
  14462. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  14463. return "mousewheel";
  14464. };
  14465. return ArcRotateCameraMouseWheelInput;
  14466. }());
  14467. __decorate([
  14468. BABYLON.serialize()
  14469. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  14470. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  14471. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  14472. })(BABYLON || (BABYLON = {}));
  14473. //# sourceMappingURL=babylon.arcrotatecamera.input.mousewheel.js.map
  14474. var BABYLON;
  14475. (function (BABYLON) {
  14476. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  14477. var ArcRotateCameraPointersInput = (function () {
  14478. function ArcRotateCameraPointersInput() {
  14479. this.buttons = [0, 1, 2];
  14480. this.angularSensibilityX = 1000.0;
  14481. this.angularSensibilityY = 1000.0;
  14482. this.pinchPrecision = 6.0;
  14483. this.panningSensibility = 50.0;
  14484. this._isPanClick = false;
  14485. this.pinchInwards = true;
  14486. }
  14487. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  14488. var _this = this;
  14489. var engine = this.camera.getEngine();
  14490. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  14491. var pointA, pointB;
  14492. var previousPinchDistance = 0;
  14493. this._pointerInput = function (p, s) {
  14494. var evt = p.event;
  14495. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  14496. return;
  14497. }
  14498. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  14499. try {
  14500. evt.srcElement.setPointerCapture(evt.pointerId);
  14501. }
  14502. catch (e) {
  14503. }
  14504. // Manage panning with pan button click
  14505. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  14506. // manage pointers
  14507. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  14508. if (pointA === undefined) {
  14509. pointA = cacheSoloPointer;
  14510. }
  14511. else if (pointB === undefined) {
  14512. pointB = cacheSoloPointer;
  14513. }
  14514. if (!noPreventDefault) {
  14515. evt.preventDefault();
  14516. element.focus();
  14517. }
  14518. }
  14519. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  14520. try {
  14521. evt.srcElement.releasePointerCapture(evt.pointerId);
  14522. }
  14523. catch (e) {
  14524. }
  14525. cacheSoloPointer = null;
  14526. previousPinchDistance = 0;
  14527. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  14528. //but emptying completly pointers collection is required to fix a bug on iPhone :
  14529. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  14530. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  14531. pointA = pointB = undefined;
  14532. if (!noPreventDefault) {
  14533. evt.preventDefault();
  14534. }
  14535. }
  14536. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  14537. if (!noPreventDefault) {
  14538. evt.preventDefault();
  14539. }
  14540. // One button down
  14541. if (pointA && pointB === undefined) {
  14542. if (_this.panningSensibility !== 0 &&
  14543. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  14544. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  14545. _this.camera
  14546. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  14547. _this.camera
  14548. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  14549. }
  14550. else {
  14551. var offsetX = evt.clientX - cacheSoloPointer.x;
  14552. var offsetY = evt.clientY - cacheSoloPointer.y;
  14553. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14554. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14555. }
  14556. cacheSoloPointer.x = evt.clientX;
  14557. cacheSoloPointer.y = evt.clientY;
  14558. }
  14559. else if (pointA && pointB) {
  14560. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  14561. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  14562. ed.x = evt.clientX;
  14563. ed.y = evt.clientY;
  14564. var direction = _this.pinchInwards ? 1 : -1;
  14565. var distX = pointA.x - pointB.x;
  14566. var distY = pointA.y - pointB.y;
  14567. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  14568. if (previousPinchDistance === 0) {
  14569. previousPinchDistance = pinchSquaredDistance;
  14570. return;
  14571. }
  14572. if (pinchSquaredDistance !== previousPinchDistance) {
  14573. _this.camera
  14574. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  14575. (_this.pinchPrecision *
  14576. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  14577. direction);
  14578. previousPinchDistance = pinchSquaredDistance;
  14579. }
  14580. }
  14581. }
  14582. };
  14583. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  14584. this._onContextMenu = function (evt) {
  14585. evt.preventDefault();
  14586. };
  14587. if (!this.camera._useCtrlForPanning) {
  14588. element.addEventListener("contextmenu", this._onContextMenu, false);
  14589. }
  14590. this._onLostFocus = function () {
  14591. //this._keys = [];
  14592. pointA = pointB = undefined;
  14593. previousPinchDistance = 0;
  14594. cacheSoloPointer = null;
  14595. };
  14596. this._onMouseMove = function (evt) {
  14597. if (!engine.isPointerLock) {
  14598. return;
  14599. }
  14600. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  14601. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  14602. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  14603. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  14604. if (!noPreventDefault) {
  14605. evt.preventDefault();
  14606. }
  14607. };
  14608. this._onGestureStart = function (e) {
  14609. if (window.MSGesture === undefined) {
  14610. return;
  14611. }
  14612. if (!_this._MSGestureHandler) {
  14613. _this._MSGestureHandler = new MSGesture();
  14614. _this._MSGestureHandler.target = element;
  14615. }
  14616. _this._MSGestureHandler.addPointer(e.pointerId);
  14617. };
  14618. this._onGesture = function (e) {
  14619. _this.camera.radius *= e.scale;
  14620. if (e.preventDefault) {
  14621. if (!noPreventDefault) {
  14622. e.stopPropagation();
  14623. e.preventDefault();
  14624. }
  14625. }
  14626. };
  14627. element.addEventListener("mousemove", this._onMouseMove, false);
  14628. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  14629. element.addEventListener("MSGestureChange", this._onGesture, false);
  14630. element.addEventListener("keydown", this._onKeyDown, false);
  14631. element.addEventListener("keyup", this._onKeyUp, false);
  14632. BABYLON.Tools.RegisterTopRootEvents([
  14633. { name: "blur", handler: this._onLostFocus }
  14634. ]);
  14635. };
  14636. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  14637. if (element && this._observer) {
  14638. this.camera.getScene().onPointerObservable.remove(this._observer);
  14639. this._observer = null;
  14640. element.removeEventListener("contextmenu", this._onContextMenu);
  14641. element.removeEventListener("mousemove", this._onMouseMove);
  14642. element.removeEventListener("MSPointerDown", this._onGestureStart);
  14643. element.removeEventListener("MSGestureChange", this._onGesture);
  14644. element.removeEventListener("keydown", this._onKeyDown);
  14645. element.removeEventListener("keyup", this._onKeyUp);
  14646. this._isPanClick = false;
  14647. this.pinchInwards = true;
  14648. this._onKeyDown = null;
  14649. this._onKeyUp = null;
  14650. this._onMouseMove = null;
  14651. this._onGestureStart = null;
  14652. this._onGesture = null;
  14653. this._MSGestureHandler = null;
  14654. this._onLostFocus = null;
  14655. this._onContextMenu = null;
  14656. }
  14657. BABYLON.Tools.UnregisterTopRootEvents([
  14658. { name: "blur", handler: this._onLostFocus }
  14659. ]);
  14660. };
  14661. ArcRotateCameraPointersInput.prototype.getTypeName = function () {
  14662. return "ArcRotateCameraPointersInput";
  14663. };
  14664. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  14665. return "pointers";
  14666. };
  14667. return ArcRotateCameraPointersInput;
  14668. }());
  14669. __decorate([
  14670. BABYLON.serialize()
  14671. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  14672. __decorate([
  14673. BABYLON.serialize()
  14674. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  14675. __decorate([
  14676. BABYLON.serialize()
  14677. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  14678. __decorate([
  14679. BABYLON.serialize()
  14680. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  14681. __decorate([
  14682. BABYLON.serialize()
  14683. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  14684. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  14685. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  14686. })(BABYLON || (BABYLON = {}));
  14687. //# sourceMappingURL=babylon.arcrotatecamera.input.pointers.js.map
  14688. var BABYLON;
  14689. (function (BABYLON) {
  14690. var ArcRotateCameraGamepadInput = (function () {
  14691. function ArcRotateCameraGamepadInput() {
  14692. this.gamepadRotationSensibility = 80;
  14693. this.gamepadMoveSensibility = 40;
  14694. }
  14695. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  14696. var _this = this;
  14697. this._gamepads = new BABYLON.Gamepads(function (gamepad) { _this._onNewGameConnected(gamepad); });
  14698. };
  14699. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  14700. if (this._gamepads) {
  14701. this._gamepads.dispose();
  14702. }
  14703. this.gamepad = null;
  14704. };
  14705. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  14706. if (this.gamepad) {
  14707. var camera = this.camera;
  14708. var RSValues = this.gamepad.rightStick;
  14709. if (RSValues.x != 0) {
  14710. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  14711. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  14712. camera.inertialAlphaOffset += normalizedRX;
  14713. }
  14714. }
  14715. if (RSValues.y != 0) {
  14716. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  14717. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  14718. camera.inertialBetaOffset += normalizedRY;
  14719. }
  14720. }
  14721. var LSValues = this.gamepad.leftStick;
  14722. if (LSValues.y != 0) {
  14723. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  14724. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  14725. this.camera.inertialRadiusOffset -= normalizedLY;
  14726. }
  14727. }
  14728. }
  14729. };
  14730. ArcRotateCameraGamepadInput.prototype._onNewGameConnected = function (gamepad) {
  14731. // Only the first gamepad can control the camera
  14732. if (gamepad.index === 0) {
  14733. this.gamepad = gamepad;
  14734. }
  14735. };
  14736. ArcRotateCameraGamepadInput.prototype.getTypeName = function () {
  14737. return "ArcRotateCameraGamepadInput";
  14738. };
  14739. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  14740. return "gamepad";
  14741. };
  14742. return ArcRotateCameraGamepadInput;
  14743. }());
  14744. __decorate([
  14745. BABYLON.serialize()
  14746. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  14747. __decorate([
  14748. BABYLON.serialize()
  14749. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  14750. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  14751. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  14752. })(BABYLON || (BABYLON = {}));
  14753. //# sourceMappingURL=babylon.arcrotatecamera.input.gamepad.js.map
  14754. var BABYLON;
  14755. (function (BABYLON) {
  14756. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  14757. function ArcRotateCameraVRDeviceOrientationInput() {
  14758. this.alphaCorrection = 1;
  14759. this.betaCorrection = 1;
  14760. this.gammaCorrection = 1;
  14761. this._alpha = 0;
  14762. this._beta = 0;
  14763. this._gamma = 0;
  14764. this._dirty = false;
  14765. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  14766. }
  14767. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  14768. this.camera.attachControl(element, noPreventDefault);
  14769. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  14770. };
  14771. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  14772. var camera = this.camera;
  14773. this._alpha = +evt.alpha | 0;
  14774. this._beta = +evt.beta | 0;
  14775. this._gamma = +evt.gamma | 0;
  14776. this._dirty = true;
  14777. };
  14778. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  14779. if (this._dirty) {
  14780. this._dirty = false;
  14781. if (this._gamma < 0) {
  14782. this._gamma = 180 + this._gamma;
  14783. }
  14784. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  14785. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  14786. }
  14787. };
  14788. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  14789. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  14790. };
  14791. ArcRotateCameraVRDeviceOrientationInput.prototype.getTypeName = function () {
  14792. return "ArcRotateCameraVRDeviceOrientationInput";
  14793. };
  14794. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  14795. return "VRDeviceOrientation";
  14796. };
  14797. return ArcRotateCameraVRDeviceOrientationInput;
  14798. }());
  14799. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  14800. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  14801. })(BABYLON || (BABYLON = {}));
  14802. //# sourceMappingURL=babylon.arcrotatecamera.input.vrdeviceorientation.js.map
  14803. var BABYLON;
  14804. (function (BABYLON) {
  14805. var TargetCamera = (function (_super) {
  14806. __extends(TargetCamera, _super);
  14807. function TargetCamera(name, position, scene) {
  14808. var _this = _super.call(this, name, position, scene) || this;
  14809. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  14810. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  14811. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  14812. _this.speed = 2.0;
  14813. _this.noRotationConstraint = false;
  14814. _this.lockedTarget = null;
  14815. _this._currentTarget = BABYLON.Vector3.Zero();
  14816. _this._viewMatrix = BABYLON.Matrix.Zero();
  14817. _this._camMatrix = BABYLON.Matrix.Zero();
  14818. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  14819. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  14820. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  14821. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  14822. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  14823. _this._lookAtTemp = BABYLON.Matrix.Zero();
  14824. _this._tempMatrix = BABYLON.Matrix.Zero();
  14825. return _this;
  14826. }
  14827. TargetCamera.prototype.getFrontPosition = function (distance) {
  14828. var direction = this.getTarget().subtract(this.position);
  14829. direction.normalize();
  14830. direction.scaleInPlace(distance);
  14831. return this.globalPosition.add(direction);
  14832. };
  14833. TargetCamera.prototype._getLockedTargetPosition = function () {
  14834. if (!this.lockedTarget) {
  14835. return null;
  14836. }
  14837. if (this.lockedTarget.absolutePosition) {
  14838. this.lockedTarget.computeWorldMatrix();
  14839. }
  14840. return this.lockedTarget.absolutePosition || this.lockedTarget;
  14841. };
  14842. // Cache
  14843. TargetCamera.prototype._initCache = function () {
  14844. _super.prototype._initCache.call(this);
  14845. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14846. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14847. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14848. };
  14849. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  14850. if (!ignoreParentClass) {
  14851. _super.prototype._updateCache.call(this);
  14852. }
  14853. var lockedTargetPosition = this._getLockedTargetPosition();
  14854. if (!lockedTargetPosition) {
  14855. this._cache.lockedTarget = null;
  14856. }
  14857. else {
  14858. if (!this._cache.lockedTarget) {
  14859. this._cache.lockedTarget = lockedTargetPosition.clone();
  14860. }
  14861. else {
  14862. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  14863. }
  14864. }
  14865. this._cache.rotation.copyFrom(this.rotation);
  14866. if (this.rotationQuaternion)
  14867. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  14868. };
  14869. // Synchronized
  14870. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  14871. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  14872. return false;
  14873. }
  14874. var lockedTargetPosition = this._getLockedTargetPosition();
  14875. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  14876. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  14877. };
  14878. // Methods
  14879. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  14880. var engine = this.getEngine();
  14881. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  14882. };
  14883. // Target
  14884. TargetCamera.prototype.setTarget = function (target) {
  14885. this.upVector.normalize();
  14886. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  14887. this._camMatrix.invert();
  14888. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  14889. var vDir = target.subtract(this.position);
  14890. if (vDir.x >= 0.0) {
  14891. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  14892. }
  14893. else {
  14894. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  14895. }
  14896. this.rotation.z = 0;
  14897. if (isNaN(this.rotation.x)) {
  14898. this.rotation.x = 0;
  14899. }
  14900. if (isNaN(this.rotation.y)) {
  14901. this.rotation.y = 0;
  14902. }
  14903. if (isNaN(this.rotation.z)) {
  14904. this.rotation.z = 0;
  14905. }
  14906. if (this.rotationQuaternion) {
  14907. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  14908. }
  14909. };
  14910. TargetCamera.prototype.getTarget = function () {
  14911. return this._currentTarget;
  14912. };
  14913. TargetCamera.prototype._decideIfNeedsToMove = function () {
  14914. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  14915. };
  14916. TargetCamera.prototype._updatePosition = function () {
  14917. this.position.addInPlace(this.cameraDirection);
  14918. };
  14919. TargetCamera.prototype._checkInputs = function () {
  14920. var needToMove = this._decideIfNeedsToMove();
  14921. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  14922. // Move
  14923. if (needToMove) {
  14924. this._updatePosition();
  14925. }
  14926. // Rotate
  14927. if (needToRotate) {
  14928. this.rotation.x += this.cameraRotation.x;
  14929. this.rotation.y += this.cameraRotation.y;
  14930. if (!this.noRotationConstraint) {
  14931. var limit = (Math.PI / 2) * 0.95;
  14932. if (this.rotation.x > limit)
  14933. this.rotation.x = limit;
  14934. if (this.rotation.x < -limit)
  14935. this.rotation.x = -limit;
  14936. }
  14937. }
  14938. // Inertia
  14939. if (needToMove) {
  14940. if (Math.abs(this.cameraDirection.x) < BABYLON.Epsilon) {
  14941. this.cameraDirection.x = 0;
  14942. }
  14943. if (Math.abs(this.cameraDirection.y) < BABYLON.Epsilon) {
  14944. this.cameraDirection.y = 0;
  14945. }
  14946. if (Math.abs(this.cameraDirection.z) < BABYLON.Epsilon) {
  14947. this.cameraDirection.z = 0;
  14948. }
  14949. this.cameraDirection.scaleInPlace(this.inertia);
  14950. }
  14951. if (needToRotate) {
  14952. if (Math.abs(this.cameraRotation.x) < BABYLON.Epsilon) {
  14953. this.cameraRotation.x = 0;
  14954. }
  14955. if (Math.abs(this.cameraRotation.y) < BABYLON.Epsilon) {
  14956. this.cameraRotation.y = 0;
  14957. }
  14958. this.cameraRotation.scaleInPlace(this.inertia);
  14959. }
  14960. _super.prototype._checkInputs.call(this);
  14961. };
  14962. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  14963. if (this.rotationQuaternion) {
  14964. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  14965. //update the up vector!
  14966. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  14967. }
  14968. else {
  14969. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  14970. }
  14971. };
  14972. TargetCamera.prototype._getViewMatrix = function () {
  14973. if (!this.lockedTarget) {
  14974. // Compute
  14975. this._updateCameraRotationMatrix();
  14976. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  14977. // Computing target and final matrix
  14978. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  14979. }
  14980. else {
  14981. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  14982. }
  14983. if (this.getScene().useRightHandedSystem) {
  14984. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14985. }
  14986. else {
  14987. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  14988. }
  14989. return this._viewMatrix;
  14990. };
  14991. /**
  14992. * @override
  14993. * Override Camera.createRigCamera
  14994. */
  14995. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  14996. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  14997. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  14998. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  14999. if (!this.rotationQuaternion) {
  15000. this.rotationQuaternion = new BABYLON.Quaternion();
  15001. }
  15002. rigCamera._cameraRigParams = {};
  15003. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  15004. }
  15005. return rigCamera;
  15006. }
  15007. return null;
  15008. };
  15009. /**
  15010. * @override
  15011. * Override Camera._updateRigCameras
  15012. */
  15013. TargetCamera.prototype._updateRigCameras = function () {
  15014. var camLeft = this._rigCameras[0];
  15015. var camRight = this._rigCameras[1];
  15016. switch (this.cameraRigMode) {
  15017. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15018. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15019. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15020. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15021. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  15022. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  15023. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  15024. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  15025. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  15026. camLeft.setTarget(this.getTarget());
  15027. camRight.setTarget(this.getTarget());
  15028. break;
  15029. case BABYLON.Camera.RIG_MODE_VR:
  15030. case BABYLON.Camera.RIG_MODE_WEBVR:
  15031. if (camLeft.rotationQuaternion) {
  15032. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15033. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  15034. }
  15035. else {
  15036. camLeft.rotation.copyFrom(this.rotation);
  15037. camRight.rotation.copyFrom(this.rotation);
  15038. }
  15039. camLeft.position.copyFrom(this.position);
  15040. camRight.position.copyFrom(this.position);
  15041. break;
  15042. }
  15043. _super.prototype._updateRigCameras.call(this);
  15044. };
  15045. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  15046. if (!this._rigCamTransformMatrix) {
  15047. this._rigCamTransformMatrix = new BABYLON.Matrix();
  15048. }
  15049. var target = this.getTarget();
  15050. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  15051. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  15052. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  15053. };
  15054. TargetCamera.prototype.getClassName = function () {
  15055. return "TargetCamera";
  15056. };
  15057. return TargetCamera;
  15058. }(BABYLON.Camera));
  15059. __decorate([
  15060. BABYLON.serializeAsVector3()
  15061. ], TargetCamera.prototype, "rotation", void 0);
  15062. __decorate([
  15063. BABYLON.serialize()
  15064. ], TargetCamera.prototype, "speed", void 0);
  15065. __decorate([
  15066. BABYLON.serializeAsMeshReference("lockedTargetId")
  15067. ], TargetCamera.prototype, "lockedTarget", void 0);
  15068. BABYLON.TargetCamera = TargetCamera;
  15069. })(BABYLON || (BABYLON = {}));
  15070. //# sourceMappingURL=babylon.targetCamera.js.map
  15071. var BABYLON;
  15072. (function (BABYLON) {
  15073. var FreeCamera = (function (_super) {
  15074. __extends(FreeCamera, _super);
  15075. function FreeCamera(name, position, scene) {
  15076. var _this = _super.call(this, name, position, scene) || this;
  15077. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  15078. _this.checkCollisions = false;
  15079. _this.applyGravity = false;
  15080. _this._collider = new BABYLON.Collider();
  15081. _this._needMoveForGravity = false;
  15082. _this._oldPosition = BABYLON.Vector3.Zero();
  15083. _this._diffPosition = BABYLON.Vector3.Zero();
  15084. _this._newPosition = BABYLON.Vector3.Zero();
  15085. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15086. if (collidedMesh === void 0) { collidedMesh = null; }
  15087. //TODO move this to the collision coordinator!
  15088. if (_this.getScene().workerCollisions)
  15089. newPosition.multiplyInPlace(_this._collider.radius);
  15090. var updatePosition = function (newPos) {
  15091. _this._newPosition.copyFrom(newPos);
  15092. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  15093. var oldPosition = _this.position.clone();
  15094. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  15095. _this.position.addInPlace(_this._diffPosition);
  15096. if (_this.onCollide && collidedMesh) {
  15097. _this.onCollide(collidedMesh);
  15098. }
  15099. }
  15100. };
  15101. updatePosition(newPosition);
  15102. };
  15103. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  15104. _this.inputs.addKeyboard().addMouse();
  15105. return _this;
  15106. }
  15107. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  15108. //-- begin properties for backward compatibility for inputs
  15109. get: function () {
  15110. var mouse = this.inputs.attached["mouse"];
  15111. if (mouse)
  15112. return mouse.angularSensibility;
  15113. },
  15114. set: function (value) {
  15115. var mouse = this.inputs.attached["mouse"];
  15116. if (mouse)
  15117. mouse.angularSensibility = value;
  15118. },
  15119. enumerable: true,
  15120. configurable: true
  15121. });
  15122. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  15123. get: function () {
  15124. var keyboard = this.inputs.attached["keyboard"];
  15125. if (keyboard)
  15126. return keyboard.keysUp;
  15127. },
  15128. set: function (value) {
  15129. var keyboard = this.inputs.attached["keyboard"];
  15130. if (keyboard)
  15131. keyboard.keysUp = value;
  15132. },
  15133. enumerable: true,
  15134. configurable: true
  15135. });
  15136. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  15137. get: function () {
  15138. var keyboard = this.inputs.attached["keyboard"];
  15139. if (keyboard)
  15140. return keyboard.keysDown;
  15141. },
  15142. set: function (value) {
  15143. var keyboard = this.inputs.attached["keyboard"];
  15144. if (keyboard)
  15145. keyboard.keysDown = value;
  15146. },
  15147. enumerable: true,
  15148. configurable: true
  15149. });
  15150. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  15151. get: function () {
  15152. var keyboard = this.inputs.attached["keyboard"];
  15153. if (keyboard)
  15154. return keyboard.keysLeft;
  15155. },
  15156. set: function (value) {
  15157. var keyboard = this.inputs.attached["keyboard"];
  15158. if (keyboard)
  15159. keyboard.keysLeft = value;
  15160. },
  15161. enumerable: true,
  15162. configurable: true
  15163. });
  15164. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  15165. get: function () {
  15166. var keyboard = this.inputs.attached["keyboard"];
  15167. if (keyboard)
  15168. return keyboard.keysRight;
  15169. },
  15170. set: function (value) {
  15171. var keyboard = this.inputs.attached["keyboard"];
  15172. if (keyboard)
  15173. keyboard.keysRight = value;
  15174. },
  15175. enumerable: true,
  15176. configurable: true
  15177. });
  15178. // Controls
  15179. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  15180. this.inputs.attachElement(element, noPreventDefault);
  15181. };
  15182. FreeCamera.prototype.detachControl = function (element) {
  15183. this.inputs.detachElement(element);
  15184. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  15185. this.cameraRotation = new BABYLON.Vector2(0, 0);
  15186. };
  15187. FreeCamera.prototype._collideWithWorld = function (velocity) {
  15188. var globalPosition;
  15189. if (this.parent) {
  15190. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  15191. }
  15192. else {
  15193. globalPosition = this.position;
  15194. }
  15195. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  15196. this._collider.radius = this.ellipsoid;
  15197. //no need for clone, as long as gravity is not on.
  15198. var actualVelocity = velocity;
  15199. //add gravity to the velocity to prevent the dual-collision checking
  15200. if (this.applyGravity) {
  15201. //this prevents mending with cameraDirection, a global variable of the free camera class.
  15202. actualVelocity = velocity.add(this.getScene().gravity);
  15203. }
  15204. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15205. };
  15206. FreeCamera.prototype._checkInputs = function () {
  15207. if (!this._localDirection) {
  15208. this._localDirection = BABYLON.Vector3.Zero();
  15209. this._transformedDirection = BABYLON.Vector3.Zero();
  15210. }
  15211. this.inputs.checkInputs();
  15212. _super.prototype._checkInputs.call(this);
  15213. };
  15214. FreeCamera.prototype._decideIfNeedsToMove = function () {
  15215. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  15216. };
  15217. FreeCamera.prototype._updatePosition = function () {
  15218. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  15219. this._collideWithWorld(this.cameraDirection);
  15220. }
  15221. else {
  15222. this.position.addInPlace(this.cameraDirection);
  15223. }
  15224. };
  15225. FreeCamera.prototype.dispose = function () {
  15226. this.inputs.clear();
  15227. _super.prototype.dispose.call(this);
  15228. };
  15229. FreeCamera.prototype.getClassName = function () {
  15230. return "FreeCamera";
  15231. };
  15232. return FreeCamera;
  15233. }(BABYLON.TargetCamera));
  15234. __decorate([
  15235. BABYLON.serializeAsVector3()
  15236. ], FreeCamera.prototype, "ellipsoid", void 0);
  15237. __decorate([
  15238. BABYLON.serialize()
  15239. ], FreeCamera.prototype, "checkCollisions", void 0);
  15240. __decorate([
  15241. BABYLON.serialize()
  15242. ], FreeCamera.prototype, "applyGravity", void 0);
  15243. BABYLON.FreeCamera = FreeCamera;
  15244. })(BABYLON || (BABYLON = {}));
  15245. //# sourceMappingURL=babylon.freeCamera.js.map
  15246. var BABYLON;
  15247. (function (BABYLON) {
  15248. var FreeCameraInputsManager = (function (_super) {
  15249. __extends(FreeCameraInputsManager, _super);
  15250. function FreeCameraInputsManager(camera) {
  15251. return _super.call(this, camera) || this;
  15252. }
  15253. FreeCameraInputsManager.prototype.addKeyboard = function () {
  15254. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  15255. return this;
  15256. };
  15257. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  15258. if (touchEnabled === void 0) { touchEnabled = true; }
  15259. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  15260. return this;
  15261. };
  15262. FreeCameraInputsManager.prototype.addGamepad = function () {
  15263. this.add(new BABYLON.FreeCameraGamepadInput());
  15264. return this;
  15265. };
  15266. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  15267. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  15268. return this;
  15269. };
  15270. FreeCameraInputsManager.prototype.addTouch = function () {
  15271. this.add(new BABYLON.FreeCameraTouchInput());
  15272. return this;
  15273. };
  15274. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  15275. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  15276. return this;
  15277. };
  15278. return FreeCameraInputsManager;
  15279. }(BABYLON.CameraInputsManager));
  15280. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  15281. })(BABYLON || (BABYLON = {}));
  15282. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  15283. var BABYLON;
  15284. (function (BABYLON) {
  15285. var FollowCamera = (function (_super) {
  15286. __extends(FollowCamera, _super);
  15287. function FollowCamera(name, position, scene, lockedTarget) {
  15288. var _this = _super.call(this, name, position, scene) || this;
  15289. _this.radius = 12;
  15290. _this.rotationOffset = 0;
  15291. _this.heightOffset = 4;
  15292. _this.cameraAcceleration = 0.05;
  15293. _this.maxCameraSpeed = 20;
  15294. _this.lockedTarget = lockedTarget;
  15295. return _this;
  15296. }
  15297. FollowCamera.prototype.getRadians = function (degrees) {
  15298. return degrees * Math.PI / 180;
  15299. };
  15300. FollowCamera.prototype.follow = function (cameraTarget) {
  15301. if (!cameraTarget)
  15302. return;
  15303. var yRotation;
  15304. if (cameraTarget.rotationQuaternion) {
  15305. var rotMatrix = new BABYLON.Matrix();
  15306. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  15307. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  15308. }
  15309. else {
  15310. yRotation = cameraTarget.rotation.y;
  15311. }
  15312. var radians = this.getRadians(this.rotationOffset) + yRotation;
  15313. var targetX = cameraTarget.position.x + Math.sin(radians) * this.radius;
  15314. var targetZ = cameraTarget.position.z + Math.cos(radians) * this.radius;
  15315. var dx = targetX - this.position.x;
  15316. var dy = (cameraTarget.position.y + this.heightOffset) - this.position.y;
  15317. var dz = (targetZ) - this.position.z;
  15318. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  15319. var vy = dy * this.cameraAcceleration;
  15320. var vz = dz * this.cameraAcceleration * 2;
  15321. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  15322. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15323. }
  15324. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  15325. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15326. }
  15327. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  15328. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  15329. }
  15330. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  15331. this.setTarget(cameraTarget.position);
  15332. };
  15333. FollowCamera.prototype._checkInputs = function () {
  15334. _super.prototype._checkInputs.call(this);
  15335. this.follow(this.lockedTarget);
  15336. };
  15337. FollowCamera.prototype.getClassName = function () {
  15338. return "FollowCamera";
  15339. };
  15340. return FollowCamera;
  15341. }(BABYLON.TargetCamera));
  15342. __decorate([
  15343. BABYLON.serialize()
  15344. ], FollowCamera.prototype, "radius", void 0);
  15345. __decorate([
  15346. BABYLON.serialize()
  15347. ], FollowCamera.prototype, "rotationOffset", void 0);
  15348. __decorate([
  15349. BABYLON.serialize()
  15350. ], FollowCamera.prototype, "heightOffset", void 0);
  15351. __decorate([
  15352. BABYLON.serialize()
  15353. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  15354. __decorate([
  15355. BABYLON.serialize()
  15356. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  15357. __decorate([
  15358. BABYLON.serializeAsMeshReference("lockedTargetId")
  15359. ], FollowCamera.prototype, "lockedTarget", void 0);
  15360. BABYLON.FollowCamera = FollowCamera;
  15361. var ArcFollowCamera = (function (_super) {
  15362. __extends(ArcFollowCamera, _super);
  15363. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  15364. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15365. _this.alpha = alpha;
  15366. _this.beta = beta;
  15367. _this.radius = radius;
  15368. _this.target = target;
  15369. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  15370. _this.follow();
  15371. return _this;
  15372. }
  15373. ArcFollowCamera.prototype.follow = function () {
  15374. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  15375. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  15376. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  15377. this.position = this.target.position.add(this._cartesianCoordinates);
  15378. this.setTarget(this.target.position);
  15379. };
  15380. ArcFollowCamera.prototype._checkInputs = function () {
  15381. _super.prototype._checkInputs.call(this);
  15382. this.follow();
  15383. };
  15384. ArcFollowCamera.prototype.getClassName = function () {
  15385. return "ArcFollowCamera";
  15386. };
  15387. return ArcFollowCamera;
  15388. }(BABYLON.TargetCamera));
  15389. BABYLON.ArcFollowCamera = ArcFollowCamera;
  15390. })(BABYLON || (BABYLON = {}));
  15391. //# sourceMappingURL=babylon.followCamera.js.map
  15392. var BABYLON;
  15393. (function (BABYLON) {
  15394. // We're mainly based on the logic defined into the FreeCamera code
  15395. var TouchCamera = (function (_super) {
  15396. __extends(TouchCamera, _super);
  15397. //-- end properties for backward compatibility for inputs
  15398. function TouchCamera(name, position, scene) {
  15399. var _this = _super.call(this, name, position, scene) || this;
  15400. _this.inputs.addTouch();
  15401. _this._setupInputs();
  15402. return _this;
  15403. }
  15404. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  15405. //-- Begin properties for backward compatibility for inputs
  15406. get: function () {
  15407. var touch = this.inputs.attached["touch"];
  15408. if (touch)
  15409. return touch.touchAngularSensibility;
  15410. },
  15411. set: function (value) {
  15412. var touch = this.inputs.attached["touch"];
  15413. if (touch)
  15414. touch.touchAngularSensibility = value;
  15415. },
  15416. enumerable: true,
  15417. configurable: true
  15418. });
  15419. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  15420. get: function () {
  15421. var touch = this.inputs.attached["touch"];
  15422. if (touch)
  15423. return touch.touchMoveSensibility;
  15424. },
  15425. set: function (value) {
  15426. var touch = this.inputs.attached["touch"];
  15427. if (touch)
  15428. touch.touchMoveSensibility = value;
  15429. },
  15430. enumerable: true,
  15431. configurable: true
  15432. });
  15433. TouchCamera.prototype.getClassName = function () {
  15434. return "TouchCamera";
  15435. };
  15436. TouchCamera.prototype._setupInputs = function () {
  15437. var mouse = this.inputs.attached["mouse"];
  15438. if (mouse) {
  15439. mouse.touchEnabled = false;
  15440. }
  15441. };
  15442. return TouchCamera;
  15443. }(BABYLON.FreeCamera));
  15444. BABYLON.TouchCamera = TouchCamera;
  15445. })(BABYLON || (BABYLON = {}));
  15446. //# sourceMappingURL=babylon.touchCamera.js.map
  15447. var BABYLON;
  15448. (function (BABYLON) {
  15449. var ArcRotateCamera = (function (_super) {
  15450. __extends(ArcRotateCamera, _super);
  15451. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  15452. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  15453. _this.inertialAlphaOffset = 0;
  15454. _this.inertialBetaOffset = 0;
  15455. _this.inertialRadiusOffset = 0;
  15456. _this.lowerAlphaLimit = null;
  15457. _this.upperAlphaLimit = null;
  15458. _this.lowerBetaLimit = 0.01;
  15459. _this.upperBetaLimit = Math.PI;
  15460. _this.lowerRadiusLimit = null;
  15461. _this.upperRadiusLimit = null;
  15462. _this.inertialPanningX = 0;
  15463. _this.inertialPanningY = 0;
  15464. //-- end properties for backward compatibility for inputs
  15465. _this.zoomOnFactor = 1;
  15466. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  15467. _this.allowUpsideDown = true;
  15468. _this._viewMatrix = new BABYLON.Matrix();
  15469. // Panning
  15470. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  15471. _this.checkCollisions = false;
  15472. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  15473. _this._collider = new BABYLON.Collider();
  15474. _this._previousPosition = BABYLON.Vector3.Zero();
  15475. _this._collisionVelocity = BABYLON.Vector3.Zero();
  15476. _this._newPosition = BABYLON.Vector3.Zero();
  15477. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  15478. if (collidedMesh === void 0) { collidedMesh = null; }
  15479. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  15480. newPosition.multiplyInPlace(_this._collider.radius);
  15481. }
  15482. if (!collidedMesh) {
  15483. _this._previousPosition.copyFrom(_this.position);
  15484. }
  15485. else {
  15486. _this.setPosition(newPosition);
  15487. if (_this.onCollide) {
  15488. _this.onCollide(collidedMesh);
  15489. }
  15490. }
  15491. // Recompute because of constraints
  15492. var cosa = Math.cos(_this.alpha);
  15493. var sina = Math.sin(_this.alpha);
  15494. var cosb = Math.cos(_this.beta);
  15495. var sinb = Math.sin(_this.beta);
  15496. if (sinb === 0) {
  15497. sinb = 0.0001;
  15498. }
  15499. var target = _this._getTargetPosition();
  15500. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  15501. _this.position.copyFrom(_this._newPosition);
  15502. var up = _this.upVector;
  15503. if (_this.allowUpsideDown && _this.beta < 0) {
  15504. up = up.clone();
  15505. up = up.negate();
  15506. }
  15507. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  15508. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  15509. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  15510. _this._collisionTriggered = false;
  15511. };
  15512. if (!target) {
  15513. _this.target = BABYLON.Vector3.Zero();
  15514. }
  15515. else {
  15516. _this.target = target;
  15517. }
  15518. _this.alpha = alpha;
  15519. _this.beta = beta;
  15520. _this.radius = radius;
  15521. _this.getViewMatrix();
  15522. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  15523. _this.inputs.addKeyboard().addMouseWheel().addPointers().addGamepad();
  15524. return _this;
  15525. }
  15526. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  15527. //-- begin properties for backward compatibility for inputs
  15528. get: function () {
  15529. var pointers = this.inputs.attached["pointers"];
  15530. if (pointers)
  15531. return pointers.angularSensibilityX;
  15532. },
  15533. set: function (value) {
  15534. var pointers = this.inputs.attached["pointers"];
  15535. if (pointers) {
  15536. pointers.angularSensibilityX = value;
  15537. }
  15538. },
  15539. enumerable: true,
  15540. configurable: true
  15541. });
  15542. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  15543. get: function () {
  15544. var pointers = this.inputs.attached["pointers"];
  15545. if (pointers)
  15546. return pointers.angularSensibilityY;
  15547. },
  15548. set: function (value) {
  15549. var pointers = this.inputs.attached["pointers"];
  15550. if (pointers) {
  15551. pointers.angularSensibilityY = value;
  15552. }
  15553. },
  15554. enumerable: true,
  15555. configurable: true
  15556. });
  15557. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  15558. get: function () {
  15559. var pointers = this.inputs.attached["pointers"];
  15560. if (pointers)
  15561. return pointers.pinchPrecision;
  15562. },
  15563. set: function (value) {
  15564. var pointers = this.inputs.attached["pointers"];
  15565. if (pointers) {
  15566. pointers.pinchPrecision = value;
  15567. }
  15568. },
  15569. enumerable: true,
  15570. configurable: true
  15571. });
  15572. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  15573. get: function () {
  15574. var pointers = this.inputs.attached["pointers"];
  15575. if (pointers)
  15576. return pointers.panningSensibility;
  15577. },
  15578. set: function (value) {
  15579. var pointers = this.inputs.attached["pointers"];
  15580. if (pointers) {
  15581. pointers.panningSensibility = value;
  15582. }
  15583. },
  15584. enumerable: true,
  15585. configurable: true
  15586. });
  15587. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  15588. get: function () {
  15589. var keyboard = this.inputs.attached["keyboard"];
  15590. if (keyboard)
  15591. return keyboard.keysUp;
  15592. },
  15593. set: function (value) {
  15594. var keyboard = this.inputs.attached["keyboard"];
  15595. if (keyboard)
  15596. keyboard.keysUp = value;
  15597. },
  15598. enumerable: true,
  15599. configurable: true
  15600. });
  15601. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  15602. get: function () {
  15603. var keyboard = this.inputs.attached["keyboard"];
  15604. if (keyboard)
  15605. return keyboard.keysDown;
  15606. },
  15607. set: function (value) {
  15608. var keyboard = this.inputs.attached["keyboard"];
  15609. if (keyboard)
  15610. keyboard.keysDown = value;
  15611. },
  15612. enumerable: true,
  15613. configurable: true
  15614. });
  15615. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  15616. get: function () {
  15617. var keyboard = this.inputs.attached["keyboard"];
  15618. if (keyboard)
  15619. return keyboard.keysLeft;
  15620. },
  15621. set: function (value) {
  15622. var keyboard = this.inputs.attached["keyboard"];
  15623. if (keyboard)
  15624. keyboard.keysLeft = value;
  15625. },
  15626. enumerable: true,
  15627. configurable: true
  15628. });
  15629. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  15630. get: function () {
  15631. var keyboard = this.inputs.attached["keyboard"];
  15632. if (keyboard)
  15633. return keyboard.keysRight;
  15634. },
  15635. set: function (value) {
  15636. var keyboard = this.inputs.attached["keyboard"];
  15637. if (keyboard)
  15638. keyboard.keysRight = value;
  15639. },
  15640. enumerable: true,
  15641. configurable: true
  15642. });
  15643. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  15644. get: function () {
  15645. var mousewheel = this.inputs.attached["mousewheel"];
  15646. if (mousewheel)
  15647. return mousewheel.wheelPrecision;
  15648. },
  15649. set: function (value) {
  15650. var mousewheel = this.inputs.attached["mousewheel"];
  15651. if (mousewheel)
  15652. mousewheel.wheelPrecision = value;
  15653. },
  15654. enumerable: true,
  15655. configurable: true
  15656. });
  15657. // Cache
  15658. ArcRotateCamera.prototype._initCache = function () {
  15659. _super.prototype._initCache.call(this);
  15660. this._cache.target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  15661. this._cache.alpha = undefined;
  15662. this._cache.beta = undefined;
  15663. this._cache.radius = undefined;
  15664. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  15665. };
  15666. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  15667. if (!ignoreParentClass) {
  15668. _super.prototype._updateCache.call(this);
  15669. }
  15670. this._cache.target.copyFrom(this._getTargetPosition());
  15671. this._cache.alpha = this.alpha;
  15672. this._cache.beta = this.beta;
  15673. this._cache.radius = this.radius;
  15674. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  15675. };
  15676. ArcRotateCamera.prototype._getTargetPosition = function () {
  15677. if (this.target.getAbsolutePosition) {
  15678. var pos = this.target.getAbsolutePosition();
  15679. return this._targetBoundingCenter ? pos.add(this._targetBoundingCenter) : pos;
  15680. }
  15681. return this.target;
  15682. };
  15683. // Synchronized
  15684. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  15685. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  15686. return false;
  15687. return this._cache.target.equals(this.target)
  15688. && this._cache.alpha === this.alpha
  15689. && this._cache.beta === this.beta
  15690. && this._cache.radius === this.radius
  15691. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  15692. };
  15693. // Methods
  15694. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  15695. var _this = this;
  15696. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  15697. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  15698. this._useCtrlForPanning = useCtrlForPanning;
  15699. this._panningMouseButton = panningMouseButton;
  15700. this.inputs.attachElement(element, noPreventDefault);
  15701. this._reset = function () {
  15702. _this.inertialAlphaOffset = 0;
  15703. _this.inertialBetaOffset = 0;
  15704. _this.inertialRadiusOffset = 0;
  15705. };
  15706. };
  15707. ArcRotateCamera.prototype.detachControl = function (element) {
  15708. this.inputs.detachElement(element);
  15709. if (this._reset) {
  15710. this._reset();
  15711. }
  15712. };
  15713. ArcRotateCamera.prototype._checkInputs = function () {
  15714. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  15715. if (this._collisionTriggered) {
  15716. return;
  15717. }
  15718. this.inputs.checkInputs();
  15719. // Inertia
  15720. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  15721. if (this.getScene().useRightHandedSystem) {
  15722. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15723. }
  15724. else {
  15725. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  15726. }
  15727. this.beta += this.inertialBetaOffset;
  15728. this.radius -= this.inertialRadiusOffset;
  15729. this.inertialAlphaOffset *= this.inertia;
  15730. this.inertialBetaOffset *= this.inertia;
  15731. this.inertialRadiusOffset *= this.inertia;
  15732. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  15733. this.inertialAlphaOffset = 0;
  15734. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  15735. this.inertialBetaOffset = 0;
  15736. if (Math.abs(this.inertialRadiusOffset) < BABYLON.Epsilon)
  15737. this.inertialRadiusOffset = 0;
  15738. }
  15739. // Panning inertia
  15740. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  15741. if (!this._localDirection) {
  15742. this._localDirection = BABYLON.Vector3.Zero();
  15743. this._transformedDirection = BABYLON.Vector3.Zero();
  15744. }
  15745. this.inertialPanningX *= this.inertia;
  15746. this.inertialPanningY *= this.inertia;
  15747. if (Math.abs(this.inertialPanningX) < BABYLON.Epsilon)
  15748. this.inertialPanningX = 0;
  15749. if (Math.abs(this.inertialPanningY) < BABYLON.Epsilon)
  15750. this.inertialPanningY = 0;
  15751. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  15752. this._localDirection.multiplyInPlace(this.panningAxis);
  15753. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  15754. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  15755. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  15756. if (!this.panningAxis.y) {
  15757. this._transformedDirection.y = 0;
  15758. }
  15759. if (!this.target.getAbsolutePosition) {
  15760. this.target.addInPlace(this._transformedDirection);
  15761. }
  15762. }
  15763. // Limits
  15764. this._checkLimits();
  15765. _super.prototype._checkInputs.call(this);
  15766. };
  15767. ArcRotateCamera.prototype._checkLimits = function () {
  15768. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  15769. if (this.allowUpsideDown && this.beta > Math.PI) {
  15770. this.beta = this.beta - (2 * Math.PI);
  15771. }
  15772. }
  15773. else {
  15774. if (this.beta < this.lowerBetaLimit) {
  15775. this.beta = this.lowerBetaLimit;
  15776. }
  15777. }
  15778. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  15779. if (this.allowUpsideDown && this.beta < -Math.PI) {
  15780. this.beta = this.beta + (2 * Math.PI);
  15781. }
  15782. }
  15783. else {
  15784. if (this.beta > this.upperBetaLimit) {
  15785. this.beta = this.upperBetaLimit;
  15786. }
  15787. }
  15788. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  15789. this.alpha = this.lowerAlphaLimit;
  15790. }
  15791. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  15792. this.alpha = this.upperAlphaLimit;
  15793. }
  15794. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  15795. this.radius = this.lowerRadiusLimit;
  15796. }
  15797. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  15798. this.radius = this.upperRadiusLimit;
  15799. }
  15800. };
  15801. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  15802. var radiusv3 = this.position.subtract(this._getTargetPosition());
  15803. this.radius = radiusv3.length();
  15804. // Alpha
  15805. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  15806. if (radiusv3.z < 0) {
  15807. this.alpha = 2 * Math.PI - this.alpha;
  15808. }
  15809. // Beta
  15810. this.beta = Math.acos(radiusv3.y / this.radius);
  15811. this._checkLimits();
  15812. };
  15813. ArcRotateCamera.prototype.setPosition = function (position) {
  15814. if (this.position.equals(position)) {
  15815. return;
  15816. }
  15817. this.position.copyFrom(position);
  15818. this.rebuildAnglesAndRadius();
  15819. };
  15820. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter) {
  15821. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  15822. if (this._getTargetPosition().equals(target)) {
  15823. return;
  15824. }
  15825. if (toBoundingCenter && target.getBoundingInfo) {
  15826. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.center.clone();
  15827. }
  15828. else {
  15829. this._targetBoundingCenter = null;
  15830. }
  15831. this.target = target;
  15832. this.rebuildAnglesAndRadius();
  15833. };
  15834. ArcRotateCamera.prototype._getViewMatrix = function () {
  15835. // Compute
  15836. var cosa = Math.cos(this.alpha);
  15837. var sina = Math.sin(this.alpha);
  15838. var cosb = Math.cos(this.beta);
  15839. var sinb = Math.sin(this.beta);
  15840. if (sinb === 0) {
  15841. sinb = 0.0001;
  15842. }
  15843. var target = this._getTargetPosition();
  15844. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  15845. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  15846. this._collider.radius = this.collisionRadius;
  15847. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  15848. this._collisionTriggered = true;
  15849. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  15850. }
  15851. else {
  15852. this.position.copyFrom(this._newPosition);
  15853. var up = this.upVector;
  15854. if (this.allowUpsideDown && this.beta < 0) {
  15855. up = up.clone();
  15856. up = up.negate();
  15857. }
  15858. if (this.getScene().useRightHandedSystem) {
  15859. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  15860. }
  15861. else {
  15862. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  15863. }
  15864. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  15865. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  15866. }
  15867. this._currentTarget = target;
  15868. return this._viewMatrix;
  15869. };
  15870. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  15871. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15872. meshes = meshes || this.getScene().meshes;
  15873. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  15874. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  15875. this.radius = distance * this.zoomOnFactor;
  15876. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  15877. };
  15878. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  15879. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  15880. var meshesOrMinMaxVector;
  15881. var distance;
  15882. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  15883. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  15884. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  15885. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  15886. }
  15887. else {
  15888. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  15889. distance = meshesOrMinMaxVectorAndDistance.distance;
  15890. }
  15891. this.target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  15892. if (!doNotUpdateMaxZ) {
  15893. this.maxZ = distance * 2;
  15894. }
  15895. };
  15896. /**
  15897. * @override
  15898. * Override Camera.createRigCamera
  15899. */
  15900. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  15901. var alphaShift;
  15902. switch (this.cameraRigMode) {
  15903. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15904. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15905. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15906. case BABYLON.Camera.RIG_MODE_VR:
  15907. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  15908. break;
  15909. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15910. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  15911. break;
  15912. }
  15913. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this.target, this.getScene());
  15914. rigCam._cameraRigParams = {};
  15915. return rigCam;
  15916. };
  15917. /**
  15918. * @override
  15919. * Override Camera._updateRigCameras
  15920. */
  15921. ArcRotateCamera.prototype._updateRigCameras = function () {
  15922. var camLeft = this._rigCameras[0];
  15923. var camRight = this._rigCameras[1];
  15924. camLeft.beta = camRight.beta = this.beta;
  15925. camLeft.radius = camRight.radius = this.radius;
  15926. switch (this.cameraRigMode) {
  15927. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15928. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15929. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15930. case BABYLON.Camera.RIG_MODE_VR:
  15931. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15932. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15933. break;
  15934. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15935. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  15936. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  15937. break;
  15938. }
  15939. _super.prototype._updateRigCameras.call(this);
  15940. };
  15941. ArcRotateCamera.prototype.dispose = function () {
  15942. this.inputs.clear();
  15943. _super.prototype.dispose.call(this);
  15944. };
  15945. ArcRotateCamera.prototype.getClassName = function () {
  15946. return "ArcRotateCamera";
  15947. };
  15948. return ArcRotateCamera;
  15949. }(BABYLON.TargetCamera));
  15950. __decorate([
  15951. BABYLON.serialize()
  15952. ], ArcRotateCamera.prototype, "alpha", void 0);
  15953. __decorate([
  15954. BABYLON.serialize()
  15955. ], ArcRotateCamera.prototype, "beta", void 0);
  15956. __decorate([
  15957. BABYLON.serialize()
  15958. ], ArcRotateCamera.prototype, "radius", void 0);
  15959. __decorate([
  15960. BABYLON.serializeAsVector3()
  15961. ], ArcRotateCamera.prototype, "target", void 0);
  15962. __decorate([
  15963. BABYLON.serialize()
  15964. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  15965. __decorate([
  15966. BABYLON.serialize()
  15967. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  15968. __decorate([
  15969. BABYLON.serialize()
  15970. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  15971. __decorate([
  15972. BABYLON.serialize()
  15973. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  15974. __decorate([
  15975. BABYLON.serialize()
  15976. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  15977. __decorate([
  15978. BABYLON.serialize()
  15979. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  15980. __decorate([
  15981. BABYLON.serialize()
  15982. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  15983. __decorate([
  15984. BABYLON.serialize()
  15985. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  15986. __decorate([
  15987. BABYLON.serialize()
  15988. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  15989. __decorate([
  15990. BABYLON.serialize()
  15991. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  15992. __decorate([
  15993. BABYLON.serialize()
  15994. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  15995. __decorate([
  15996. BABYLON.serialize()
  15997. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  15998. __decorate([
  15999. BABYLON.serialize()
  16000. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  16001. BABYLON.ArcRotateCamera = ArcRotateCamera;
  16002. })(BABYLON || (BABYLON = {}));
  16003. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  16004. var BABYLON;
  16005. (function (BABYLON) {
  16006. var ArcRotateCameraInputsManager = (function (_super) {
  16007. __extends(ArcRotateCameraInputsManager, _super);
  16008. function ArcRotateCameraInputsManager(camera) {
  16009. return _super.call(this, camera) || this;
  16010. }
  16011. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  16012. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  16013. return this;
  16014. };
  16015. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  16016. this.add(new BABYLON.ArcRotateCameraPointersInput());
  16017. return this;
  16018. };
  16019. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  16020. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  16021. return this;
  16022. };
  16023. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  16024. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  16025. return this;
  16026. };
  16027. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  16028. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  16029. return this;
  16030. };
  16031. return ArcRotateCameraInputsManager;
  16032. }(BABYLON.CameraInputsManager));
  16033. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  16034. })(BABYLON || (BABYLON = {}));
  16035. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  16036. var BABYLON;
  16037. (function (BABYLON) {
  16038. var RenderingManager = (function () {
  16039. function RenderingManager(scene) {
  16040. this._renderingGroups = new Array();
  16041. this._autoClearDepthStencil = {};
  16042. this._customOpaqueSortCompareFn = {};
  16043. this._customAlphaTestSortCompareFn = {};
  16044. this._customTransparentSortCompareFn = {};
  16045. this._renderinGroupInfo = null;
  16046. this._scene = scene;
  16047. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  16048. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  16049. }
  16050. }
  16051. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  16052. if (depth === void 0) { depth = true; }
  16053. if (stencil === void 0) { stencil = true; }
  16054. if (this._depthStencilBufferAlreadyCleaned) {
  16055. return;
  16056. }
  16057. this._scene.getEngine().clear(null, false, depth, stencil);
  16058. this._depthStencilBufferAlreadyCleaned = true;
  16059. };
  16060. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  16061. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  16062. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  16063. var info = null;
  16064. if (observable) {
  16065. if (!this._renderinGroupInfo) {
  16066. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  16067. }
  16068. info = this._renderinGroupInfo;
  16069. info.scene = this._scene;
  16070. info.camera = this._scene.activeCamera;
  16071. }
  16072. // Dispatch sprites
  16073. if (renderSprites) {
  16074. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  16075. var manager = this._scene.spriteManagers[index];
  16076. this.dispatchSprites(manager);
  16077. }
  16078. }
  16079. // Render
  16080. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16081. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  16082. var renderingGroup = this._renderingGroups[index];
  16083. if (!renderingGroup && !observable)
  16084. continue;
  16085. this._currentIndex = index;
  16086. var renderingGroupMask = 0;
  16087. // Fire PRECLEAR stage
  16088. if (observable) {
  16089. renderingGroupMask = Math.pow(2, index);
  16090. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  16091. info.renderingGroupId = index;
  16092. observable.notifyObservers(info, renderingGroupMask);
  16093. }
  16094. // Clear depth/stencil if needed
  16095. var autoClear = this._autoClearDepthStencil[index];
  16096. if (autoClear && autoClear.autoClear) {
  16097. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  16098. }
  16099. if (observable) {
  16100. // Fire PREOPAQUE stage
  16101. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  16102. observable.notifyObservers(info, renderingGroupMask);
  16103. // Fire PRETRANSPARENT stage
  16104. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  16105. observable.notifyObservers(info, renderingGroupMask);
  16106. }
  16107. if (renderingGroup)
  16108. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  16109. // Fire POSTTRANSPARENT stage
  16110. if (observable) {
  16111. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  16112. observable.notifyObservers(info, renderingGroupMask);
  16113. }
  16114. }
  16115. };
  16116. RenderingManager.prototype.reset = function () {
  16117. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  16118. var renderingGroup = this._renderingGroups[index];
  16119. if (renderingGroup) {
  16120. renderingGroup.prepare();
  16121. }
  16122. }
  16123. };
  16124. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  16125. if (!this._renderingGroups[renderingGroupId]) {
  16126. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  16127. }
  16128. };
  16129. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  16130. var renderingGroupId = spriteManager.renderingGroupId || 0;
  16131. this._prepareRenderingGroup(renderingGroupId);
  16132. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  16133. };
  16134. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  16135. var renderingGroupId = particleSystem.renderingGroupId || 0;
  16136. this._prepareRenderingGroup(renderingGroupId);
  16137. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  16138. };
  16139. RenderingManager.prototype.dispatch = function (subMesh) {
  16140. var mesh = subMesh.getMesh();
  16141. var renderingGroupId = mesh.renderingGroupId || 0;
  16142. this._prepareRenderingGroup(renderingGroupId);
  16143. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  16144. };
  16145. /**
  16146. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  16147. * This allowed control for front to back rendering or reversly depending of the special needs.
  16148. *
  16149. * @param renderingGroupId The rendering group id corresponding to its index
  16150. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  16151. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  16152. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  16153. */
  16154. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16155. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16156. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16157. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16158. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  16159. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  16160. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  16161. if (this._renderingGroups[renderingGroupId]) {
  16162. var group = this._renderingGroups[renderingGroupId];
  16163. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  16164. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  16165. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  16166. }
  16167. };
  16168. /**
  16169. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  16170. *
  16171. * @param renderingGroupId The rendering group id corresponding to its index
  16172. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  16173. * @param depth Automatically clears depth between groups if true and autoClear is true.
  16174. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  16175. */
  16176. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  16177. if (depth === void 0) { depth = true; }
  16178. if (stencil === void 0) { stencil = true; }
  16179. this._autoClearDepthStencil[renderingGroupId] = {
  16180. autoClear: autoClearDepthStencil,
  16181. depth: depth,
  16182. stencil: stencil
  16183. };
  16184. };
  16185. return RenderingManager;
  16186. }());
  16187. /**
  16188. * The max id used for rendering groups (not included)
  16189. */
  16190. RenderingManager.MAX_RENDERINGGROUPS = 4;
  16191. /**
  16192. * The min id used for rendering groups (included)
  16193. */
  16194. RenderingManager.MIN_RENDERINGGROUPS = 0;
  16195. BABYLON.RenderingManager = RenderingManager;
  16196. })(BABYLON || (BABYLON = {}));
  16197. //# sourceMappingURL=babylon.renderingManager.js.map
  16198. var BABYLON;
  16199. (function (BABYLON) {
  16200. var RenderingGroup = (function () {
  16201. /**
  16202. * Creates a new rendering group.
  16203. * @param index The rendering group index
  16204. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  16205. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  16206. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  16207. */
  16208. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  16209. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  16210. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  16211. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  16212. this.index = index;
  16213. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  16214. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  16215. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  16216. this._particleSystems = new BABYLON.SmartArray(256);
  16217. this._spriteManagers = new BABYLON.SmartArray(256);
  16218. this._scene = scene;
  16219. this.opaqueSortCompareFn = opaqueSortCompareFn;
  16220. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  16221. this.transparentSortCompareFn = transparentSortCompareFn;
  16222. }
  16223. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  16224. /**
  16225. * Set the opaque sort comparison function.
  16226. * If null the sub meshes will be render in the order they were created
  16227. */
  16228. set: function (value) {
  16229. this._opaqueSortCompareFn = value;
  16230. if (value) {
  16231. this._renderOpaque = this.renderOpaqueSorted;
  16232. }
  16233. else {
  16234. this._renderOpaque = RenderingGroup.renderUnsorted;
  16235. }
  16236. },
  16237. enumerable: true,
  16238. configurable: true
  16239. });
  16240. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  16241. /**
  16242. * Set the alpha test sort comparison function.
  16243. * If null the sub meshes will be render in the order they were created
  16244. */
  16245. set: function (value) {
  16246. this._alphaTestSortCompareFn = value;
  16247. if (value) {
  16248. this._renderAlphaTest = this.renderAlphaTestSorted;
  16249. }
  16250. else {
  16251. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  16252. }
  16253. },
  16254. enumerable: true,
  16255. configurable: true
  16256. });
  16257. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  16258. /**
  16259. * Set the transparent sort comparison function.
  16260. * If null the sub meshes will be render in the order they were created
  16261. */
  16262. set: function (value) {
  16263. if (value) {
  16264. this._transparentSortCompareFn = value;
  16265. }
  16266. else {
  16267. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  16268. }
  16269. this._renderTransparent = this.renderTransparentSorted;
  16270. },
  16271. enumerable: true,
  16272. configurable: true
  16273. });
  16274. /**
  16275. * Render all the sub meshes contained in the group.
  16276. * @param customRenderFunction Used to override the default render behaviour of the group.
  16277. * @returns true if rendered some submeshes.
  16278. */
  16279. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  16280. if (customRenderFunction) {
  16281. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  16282. return;
  16283. }
  16284. var engine = this._scene.getEngine();
  16285. // Opaque
  16286. if (this._opaqueSubMeshes.length !== 0) {
  16287. this._renderOpaque(this._opaqueSubMeshes);
  16288. }
  16289. // Alpha test
  16290. if (this._alphaTestSubMeshes.length !== 0) {
  16291. engine.setAlphaTesting(true);
  16292. this._renderAlphaTest(this._alphaTestSubMeshes);
  16293. engine.setAlphaTesting(false);
  16294. }
  16295. // Sprites
  16296. if (renderSprites) {
  16297. this._renderSprites();
  16298. }
  16299. // Particles
  16300. if (renderParticles) {
  16301. this._renderParticles(activeMeshes);
  16302. }
  16303. if (this.onBeforeTransparentRendering) {
  16304. this.onBeforeTransparentRendering();
  16305. }
  16306. // Transparent
  16307. if (this._transparentSubMeshes.length !== 0) {
  16308. this._renderTransparent(this._transparentSubMeshes);
  16309. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  16310. }
  16311. };
  16312. /**
  16313. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  16314. * @param subMeshes The submeshes to render
  16315. */
  16316. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  16317. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16318. };
  16319. /**
  16320. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  16321. * @param subMeshes The submeshes to render
  16322. */
  16323. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  16324. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  16325. };
  16326. /**
  16327. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  16328. * @param subMeshes The submeshes to render
  16329. */
  16330. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  16331. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  16332. };
  16333. /**
  16334. * Renders the submeshes in a specified order.
  16335. * @param subMeshes The submeshes to sort before render
  16336. * @param sortCompareFn The comparison function use to sort
  16337. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  16338. * @param transparent Specifies to activate blending if true
  16339. */
  16340. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  16341. var subIndex = 0;
  16342. var subMesh;
  16343. for (; subIndex < subMeshes.length; subIndex++) {
  16344. subMesh = subMeshes.data[subIndex];
  16345. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  16346. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  16347. }
  16348. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  16349. sortedArray.sort(sortCompareFn);
  16350. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  16351. subMesh = sortedArray[subIndex];
  16352. subMesh.render(transparent);
  16353. }
  16354. };
  16355. /**
  16356. * Renders the submeshes in the order they were dispatched (no sort applied).
  16357. * @param subMeshes The submeshes to render
  16358. */
  16359. RenderingGroup.renderUnsorted = function (subMeshes) {
  16360. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  16361. var submesh = subMeshes.data[subIndex];
  16362. submesh.render(false);
  16363. }
  16364. };
  16365. /**
  16366. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16367. * are rendered back to front if in the same alpha index.
  16368. *
  16369. * @param a The first submesh
  16370. * @param b The second submesh
  16371. * @returns The result of the comparison
  16372. */
  16373. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  16374. // Alpha index first
  16375. if (a._alphaIndex > b._alphaIndex) {
  16376. return 1;
  16377. }
  16378. if (a._alphaIndex < b._alphaIndex) {
  16379. return -1;
  16380. }
  16381. // Then distance to camera
  16382. return RenderingGroup.backToFrontSortCompare(a, b);
  16383. };
  16384. /**
  16385. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16386. * are rendered back to front.
  16387. *
  16388. * @param a The first submesh
  16389. * @param b The second submesh
  16390. * @returns The result of the comparison
  16391. */
  16392. RenderingGroup.backToFrontSortCompare = function (a, b) {
  16393. // Then distance to camera
  16394. if (a._distanceToCamera < b._distanceToCamera) {
  16395. return 1;
  16396. }
  16397. if (a._distanceToCamera > b._distanceToCamera) {
  16398. return -1;
  16399. }
  16400. return 0;
  16401. };
  16402. /**
  16403. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  16404. * are rendered front to back (prevent overdraw).
  16405. *
  16406. * @param a The first submesh
  16407. * @param b The second submesh
  16408. * @returns The result of the comparison
  16409. */
  16410. RenderingGroup.frontToBackSortCompare = function (a, b) {
  16411. // Then distance to camera
  16412. if (a._distanceToCamera < b._distanceToCamera) {
  16413. return -1;
  16414. }
  16415. if (a._distanceToCamera > b._distanceToCamera) {
  16416. return 1;
  16417. }
  16418. return 0;
  16419. };
  16420. /**
  16421. * Resets the different lists of submeshes to prepare a new frame.
  16422. */
  16423. RenderingGroup.prototype.prepare = function () {
  16424. this._opaqueSubMeshes.reset();
  16425. this._transparentSubMeshes.reset();
  16426. this._alphaTestSubMeshes.reset();
  16427. this._particleSystems.reset();
  16428. this._spriteManagers.reset();
  16429. };
  16430. /**
  16431. * Inserts the submesh in its correct queue depending on its material.
  16432. * @param subMesh The submesh to dispatch
  16433. */
  16434. RenderingGroup.prototype.dispatch = function (subMesh) {
  16435. var material = subMesh.getMaterial();
  16436. var mesh = subMesh.getMesh();
  16437. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  16438. this._transparentSubMeshes.push(subMesh);
  16439. }
  16440. else if (material.needAlphaTesting()) {
  16441. this._alphaTestSubMeshes.push(subMesh);
  16442. }
  16443. else {
  16444. this._opaqueSubMeshes.push(subMesh); // Opaque
  16445. }
  16446. };
  16447. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  16448. this._spriteManagers.push(spriteManager);
  16449. };
  16450. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  16451. this._particleSystems.push(particleSystem);
  16452. };
  16453. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  16454. if (this._particleSystems.length === 0) {
  16455. return;
  16456. }
  16457. // Particles
  16458. var activeCamera = this._scene.activeCamera;
  16459. this._scene._particlesDuration.beginMonitoring();
  16460. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16461. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16462. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16463. continue;
  16464. }
  16465. if (!particleSystem.emitter.position || !activeMeshes || activeMeshes.indexOf(particleSystem.emitter) !== -1) {
  16466. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16467. }
  16468. }
  16469. this._scene._particlesDuration.endMonitoring(false);
  16470. };
  16471. RenderingGroup.prototype._renderSprites = function () {
  16472. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16473. return;
  16474. }
  16475. // Sprites
  16476. var activeCamera = this._scene.activeCamera;
  16477. this._scene._spritesDuration.beginMonitoring();
  16478. for (var id = 0; id < this._spriteManagers.length; id++) {
  16479. var spriteManager = this._scene.spriteManagers[id];
  16480. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16481. spriteManager.render();
  16482. }
  16483. }
  16484. this._scene._spritesDuration.endMonitoring(false);
  16485. };
  16486. return RenderingGroup;
  16487. }());
  16488. BABYLON.RenderingGroup = RenderingGroup;
  16489. })(BABYLON || (BABYLON = {}));
  16490. //# sourceMappingURL=babylon.renderingGroup.js.map
  16491. var BABYLON;
  16492. (function (BABYLON) {
  16493. var PointerEventTypes = (function () {
  16494. function PointerEventTypes() {
  16495. }
  16496. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16497. get: function () {
  16498. return PointerEventTypes._POINTERDOWN;
  16499. },
  16500. enumerable: true,
  16501. configurable: true
  16502. });
  16503. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16504. get: function () {
  16505. return PointerEventTypes._POINTERUP;
  16506. },
  16507. enumerable: true,
  16508. configurable: true
  16509. });
  16510. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16511. get: function () {
  16512. return PointerEventTypes._POINTERMOVE;
  16513. },
  16514. enumerable: true,
  16515. configurable: true
  16516. });
  16517. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16518. get: function () {
  16519. return PointerEventTypes._POINTERWHEEL;
  16520. },
  16521. enumerable: true,
  16522. configurable: true
  16523. });
  16524. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16525. get: function () {
  16526. return PointerEventTypes._POINTERPICK;
  16527. },
  16528. enumerable: true,
  16529. configurable: true
  16530. });
  16531. return PointerEventTypes;
  16532. }());
  16533. PointerEventTypes._POINTERDOWN = 0x01;
  16534. PointerEventTypes._POINTERUP = 0x02;
  16535. PointerEventTypes._POINTERMOVE = 0x04;
  16536. PointerEventTypes._POINTERWHEEL = 0x08;
  16537. PointerEventTypes._POINTERPICK = 0x10;
  16538. BABYLON.PointerEventTypes = PointerEventTypes;
  16539. var PointerInfoBase = (function () {
  16540. function PointerInfoBase(type, event) {
  16541. this.type = type;
  16542. this.event = event;
  16543. }
  16544. return PointerInfoBase;
  16545. }());
  16546. BABYLON.PointerInfoBase = PointerInfoBase;
  16547. /**
  16548. * This class is used to store pointer related info for the onPrePointerObservable event.
  16549. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16550. */
  16551. var PointerInfoPre = (function (_super) {
  16552. __extends(PointerInfoPre, _super);
  16553. function PointerInfoPre(type, event, localX, localY) {
  16554. var _this = _super.call(this, type, event) || this;
  16555. _this.skipOnPointerObservable = false;
  16556. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16557. return _this;
  16558. }
  16559. return PointerInfoPre;
  16560. }(PointerInfoBase));
  16561. BABYLON.PointerInfoPre = PointerInfoPre;
  16562. /**
  16563. * This type contains all the data related to a pointer event in Babylon.js.
  16564. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  16565. */
  16566. var PointerInfo = (function (_super) {
  16567. __extends(PointerInfo, _super);
  16568. function PointerInfo(type, event, pickInfo) {
  16569. var _this = _super.call(this, type, event) || this;
  16570. _this.pickInfo = pickInfo;
  16571. return _this;
  16572. }
  16573. return PointerInfo;
  16574. }(PointerInfoBase));
  16575. BABYLON.PointerInfo = PointerInfo;
  16576. /**
  16577. * This class is used by the onRenderingGroupObservable
  16578. */
  16579. var RenderingGroupInfo = (function () {
  16580. function RenderingGroupInfo() {
  16581. }
  16582. return RenderingGroupInfo;
  16583. }());
  16584. /**
  16585. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16586. * This stage will be fired no matter what
  16587. */
  16588. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16589. /**
  16590. * Called before opaque object are rendered.
  16591. * This stage will be fired only if there's 3D Opaque content to render
  16592. */
  16593. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16594. /**
  16595. * Called after the opaque objects are rendered and before the transparent ones
  16596. * This stage will be fired only if there's 3D transparent content to render
  16597. */
  16598. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16599. /**
  16600. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16601. * This stage will be fired no matter what
  16602. */
  16603. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16604. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16605. /**
  16606. * Represents a scene to be rendered by the engine.
  16607. * @see http://doc.babylonjs.com/page.php?p=21911
  16608. */
  16609. var Scene = (function () {
  16610. /**
  16611. * @constructor
  16612. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16613. */
  16614. function Scene(engine) {
  16615. // Members
  16616. this.autoClear = true;
  16617. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16618. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16619. this.forceWireframe = false;
  16620. this.forcePointsCloud = false;
  16621. this.forceShowBoundingBoxes = false;
  16622. this.animationsEnabled = true;
  16623. this.constantlyUpdateMeshUnderPointer = false;
  16624. this.useRightHandedSystem = false;
  16625. this.hoverCursor = "pointer";
  16626. // Metadata
  16627. this.metadata = null;
  16628. // Events
  16629. /**
  16630. * An event triggered when the scene is disposed.
  16631. * @type {BABYLON.Observable}
  16632. */
  16633. this.onDisposeObservable = new BABYLON.Observable();
  16634. /**
  16635. * An event triggered before rendering the scene
  16636. * @type {BABYLON.Observable}
  16637. */
  16638. this.onBeforeRenderObservable = new BABYLON.Observable();
  16639. /**
  16640. * An event triggered after rendering the scene
  16641. * @type {BABYLON.Observable}
  16642. */
  16643. this.onAfterRenderObservable = new BABYLON.Observable();
  16644. /**
  16645. * An event triggered when the scene is ready
  16646. * @type {BABYLON.Observable}
  16647. */
  16648. this.onReadyObservable = new BABYLON.Observable();
  16649. /**
  16650. * An event triggered before rendering a camera
  16651. * @type {BABYLON.Observable}
  16652. */
  16653. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16654. /**
  16655. * An event triggered after rendering a camera
  16656. * @type {BABYLON.Observable}
  16657. */
  16658. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16659. /**
  16660. * An event triggered when a camera is created
  16661. * @type {BABYLON.Observable}
  16662. */
  16663. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16664. /**
  16665. * An event triggered when a camera is removed
  16666. * @type {BABYLON.Observable}
  16667. */
  16668. this.onCameraRemovedObservable = new BABYLON.Observable();
  16669. /**
  16670. * An event triggered when a light is created
  16671. * @type {BABYLON.Observable}
  16672. */
  16673. this.onNewLightAddedObservable = new BABYLON.Observable();
  16674. /**
  16675. * An event triggered when a light is removed
  16676. * @type {BABYLON.Observable}
  16677. */
  16678. this.onLightRemovedObservable = new BABYLON.Observable();
  16679. /**
  16680. * An event triggered when a geometry is created
  16681. * @type {BABYLON.Observable}
  16682. */
  16683. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16684. /**
  16685. * An event triggered when a geometry is removed
  16686. * @type {BABYLON.Observable}
  16687. */
  16688. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16689. /**
  16690. * An event triggered when a mesh is created
  16691. * @type {BABYLON.Observable}
  16692. */
  16693. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16694. /**
  16695. * An event triggered when a mesh is removed
  16696. * @type {BABYLON.Observable}
  16697. */
  16698. this.onMeshRemovedObservable = new BABYLON.Observable();
  16699. /**
  16700. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16701. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16702. * If you wish to register an Observer only for a given set of renderingGroup, use the mask with a combination of the renderingGroup index elevated to the power of two (1 for renderingGroup 0, 2 for renderingrOup1, 4 for 2 and 8 for 3)
  16703. */
  16704. this.onRenderingGroupObservable = new BABYLON.Observable();
  16705. // Animations
  16706. this.animations = [];
  16707. /**
  16708. * This observable event is triggered when any mouse event registered during Scene.attach() is called BEFORE the 3D engine to process anything (mesh/sprite picking for instance).
  16709. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16710. */
  16711. this.onPrePointerObservable = new BABYLON.Observable();
  16712. /**
  16713. * Observable event triggered each time an input event is received from the rendering canvas
  16714. */
  16715. this.onPointerObservable = new BABYLON.Observable();
  16716. 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
  16717. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16718. this._startingPointerTime = 0;
  16719. // Fog
  16720. /**
  16721. * is fog enabled on this scene.
  16722. * @type {boolean}
  16723. */
  16724. this.fogEnabled = true;
  16725. this.fogMode = Scene.FOGMODE_NONE;
  16726. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16727. this.fogDensity = 0.1;
  16728. this.fogStart = 0;
  16729. this.fogEnd = 1000.0;
  16730. // Lights
  16731. /**
  16732. * is shadow enabled on this scene.
  16733. * @type {boolean}
  16734. */
  16735. this.shadowsEnabled = true;
  16736. /**
  16737. * is light enabled on this scene.
  16738. * @type {boolean}
  16739. */
  16740. this.lightsEnabled = true;
  16741. /**
  16742. * All of the lights added to this scene.
  16743. * @see BABYLON.Light
  16744. * @type {BABYLON.Light[]}
  16745. */
  16746. this.lights = new Array();
  16747. // Cameras
  16748. /**
  16749. * All of the cameras added to this scene.
  16750. * @see BABYLON.Camera
  16751. * @type {BABYLON.Camera[]}
  16752. */
  16753. this.cameras = new Array();
  16754. this.activeCameras = new Array();
  16755. // Meshes
  16756. /**
  16757. * All of the (abstract) meshes added to this scene.
  16758. * @see BABYLON.AbstractMesh
  16759. * @type {BABYLON.AbstractMesh[]}
  16760. */
  16761. this.meshes = new Array();
  16762. // Geometries
  16763. this._geometries = new Array();
  16764. this.materials = new Array();
  16765. this.multiMaterials = new Array();
  16766. // Textures
  16767. this.texturesEnabled = true;
  16768. this.textures = new Array();
  16769. // Particles
  16770. this.particlesEnabled = true;
  16771. this.particleSystems = new Array();
  16772. // Sprites
  16773. this.spritesEnabled = true;
  16774. this.spriteManagers = new Array();
  16775. // Layers
  16776. this.layers = new Array();
  16777. this.highlightLayers = new Array();
  16778. // Skeletons
  16779. this.skeletonsEnabled = true;
  16780. this.skeletons = new Array();
  16781. // Lens flares
  16782. this.lensFlaresEnabled = true;
  16783. this.lensFlareSystems = new Array();
  16784. // Collisions
  16785. this.collisionsEnabled = true;
  16786. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16787. // Postprocesses
  16788. this.postProcessesEnabled = true;
  16789. // Customs render targets
  16790. this.renderTargetsEnabled = true;
  16791. this.dumpNextRenderTargets = false;
  16792. this.customRenderTargets = new Array();
  16793. // Imported meshes
  16794. this.importedMeshesFiles = new Array();
  16795. // Probes
  16796. this.probesEnabled = true;
  16797. this.reflectionProbes = new Array();
  16798. this._actionManagers = new Array();
  16799. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16800. // Procedural textures
  16801. this.proceduralTexturesEnabled = true;
  16802. this._proceduralTextures = new Array();
  16803. this.soundTracks = new Array();
  16804. this._audioEnabled = true;
  16805. this._headphone = false;
  16806. // Performance counters
  16807. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16808. this._totalLightsCounter = new BABYLON.PerfCounter();
  16809. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16810. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16811. this._totalVertices = new BABYLON.PerfCounter();
  16812. this._activeIndices = new BABYLON.PerfCounter();
  16813. this._activeParticles = new BABYLON.PerfCounter();
  16814. this._lastFrameDuration = new BABYLON.PerfCounter();
  16815. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16816. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16817. this._particlesDuration = new BABYLON.PerfCounter();
  16818. this._renderDuration = new BABYLON.PerfCounter();
  16819. this._spritesDuration = new BABYLON.PerfCounter();
  16820. this._activeBones = new BABYLON.PerfCounter();
  16821. this._animationTime = 0;
  16822. this.animationTimeScale = 1;
  16823. this._renderId = 0;
  16824. this._executeWhenReadyTimeoutId = -1;
  16825. this._intermediateRendering = false;
  16826. this._toBeDisposed = new BABYLON.SmartArray(256);
  16827. this._pendingData = []; //ANY
  16828. this._activeMeshes = new BABYLON.SmartArray(256);
  16829. this._processedMaterials = new BABYLON.SmartArray(256);
  16830. this._renderTargets = new BABYLON.SmartArray(256);
  16831. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16832. this._activeSkeletons = new BABYLON.SmartArray(32);
  16833. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16834. this._activeAnimatables = new Array();
  16835. this._transformMatrix = BABYLON.Matrix.Zero();
  16836. this._edgesRenderers = new BABYLON.SmartArray(16);
  16837. this._uniqueIdCounter = 0;
  16838. this._engine = engine;
  16839. engine.scenes.push(this);
  16840. this._externalData = new BABYLON.StringDictionary();
  16841. this._uid = null;
  16842. this._renderingManager = new BABYLON.RenderingManager(this);
  16843. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16844. this.postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16845. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16846. if (BABYLON.OutlineRenderer) {
  16847. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16848. }
  16849. this.attachControl();
  16850. if (BABYLON.SoundTrack) {
  16851. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16852. }
  16853. //simplification queue
  16854. if (BABYLON.SimplificationQueue) {
  16855. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16856. }
  16857. //collision coordinator initialization. For now legacy per default.
  16858. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16859. }
  16860. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16861. get: function () {
  16862. return Scene._FOGMODE_NONE;
  16863. },
  16864. enumerable: true,
  16865. configurable: true
  16866. });
  16867. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16868. get: function () {
  16869. return Scene._FOGMODE_EXP;
  16870. },
  16871. enumerable: true,
  16872. configurable: true
  16873. });
  16874. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16875. get: function () {
  16876. return Scene._FOGMODE_EXP2;
  16877. },
  16878. enumerable: true,
  16879. configurable: true
  16880. });
  16881. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16882. get: function () {
  16883. return Scene._FOGMODE_LINEAR;
  16884. },
  16885. enumerable: true,
  16886. configurable: true
  16887. });
  16888. Object.defineProperty(Scene.prototype, "onDispose", {
  16889. set: function (callback) {
  16890. if (this._onDisposeObserver) {
  16891. this.onDisposeObservable.remove(this._onDisposeObserver);
  16892. }
  16893. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Object.defineProperty(Scene.prototype, "beforeRender", {
  16899. set: function (callback) {
  16900. if (this._onBeforeRenderObserver) {
  16901. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16902. }
  16903. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Object.defineProperty(Scene.prototype, "afterRender", {
  16909. set: function (callback) {
  16910. if (this._onAfterRenderObserver) {
  16911. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16912. }
  16913. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16919. set: function (callback) {
  16920. if (this._onBeforeCameraRenderObserver) {
  16921. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16922. }
  16923. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16929. set: function (callback) {
  16930. if (this._onAfterCameraRenderObserver) {
  16931. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16932. }
  16933. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16934. },
  16935. enumerable: true,
  16936. configurable: true
  16937. });
  16938. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16939. get: function () {
  16940. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16941. },
  16942. enumerable: true,
  16943. configurable: true
  16944. });
  16945. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16946. get: function () {
  16947. if (!this._defaultMaterial) {
  16948. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16949. }
  16950. return this._defaultMaterial;
  16951. },
  16952. enumerable: true,
  16953. configurable: true
  16954. });
  16955. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16956. get: function () {
  16957. return this._frustumPlanes;
  16958. },
  16959. enumerable: true,
  16960. configurable: true
  16961. });
  16962. Object.defineProperty(Scene.prototype, "debugLayer", {
  16963. // Properties
  16964. get: function () {
  16965. if (!this._debugLayer) {
  16966. this._debugLayer = new BABYLON.DebugLayer(this);
  16967. }
  16968. return this._debugLayer;
  16969. },
  16970. enumerable: true,
  16971. configurable: true
  16972. });
  16973. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16974. get: function () {
  16975. return this._workerCollisions;
  16976. },
  16977. set: function (enabled) {
  16978. enabled = (enabled && !!Worker);
  16979. this._workerCollisions = enabled;
  16980. if (this.collisionCoordinator) {
  16981. this.collisionCoordinator.destroy();
  16982. }
  16983. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16984. this.collisionCoordinator.init(this);
  16985. },
  16986. enumerable: true,
  16987. configurable: true
  16988. });
  16989. Object.defineProperty(Scene.prototype, "SelectionOctree", {
  16990. get: function () {
  16991. return this._selectionOctree;
  16992. },
  16993. enumerable: true,
  16994. configurable: true
  16995. });
  16996. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16997. /**
  16998. * The mesh that is currently under the pointer.
  16999. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  17000. */
  17001. get: function () {
  17002. return this._pointerOverMesh;
  17003. },
  17004. enumerable: true,
  17005. configurable: true
  17006. });
  17007. Object.defineProperty(Scene.prototype, "pointerX", {
  17008. /**
  17009. * Current on-screen X position of the pointer
  17010. * @return {number} X position of the pointer
  17011. */
  17012. get: function () {
  17013. return this._pointerX;
  17014. },
  17015. enumerable: true,
  17016. configurable: true
  17017. });
  17018. Object.defineProperty(Scene.prototype, "pointerY", {
  17019. /**
  17020. * Current on-screen Y position of the pointer
  17021. * @return {number} Y position of the pointer
  17022. */
  17023. get: function () {
  17024. return this._pointerY;
  17025. },
  17026. enumerable: true,
  17027. configurable: true
  17028. });
  17029. Scene.prototype.getCachedMaterial = function () {
  17030. return this._cachedMaterial;
  17031. };
  17032. Scene.prototype.getBoundingBoxRenderer = function () {
  17033. return this._boundingBoxRenderer;
  17034. };
  17035. Scene.prototype.getOutlineRenderer = function () {
  17036. return this._outlineRenderer;
  17037. };
  17038. Scene.prototype.getEngine = function () {
  17039. return this._engine;
  17040. };
  17041. Scene.prototype.getTotalVertices = function () {
  17042. return this._totalVertices.current;
  17043. };
  17044. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  17045. get: function () {
  17046. return this._totalVertices;
  17047. },
  17048. enumerable: true,
  17049. configurable: true
  17050. });
  17051. Scene.prototype.getActiveIndices = function () {
  17052. return this._activeIndices.current;
  17053. };
  17054. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  17055. get: function () {
  17056. return this._activeIndices;
  17057. },
  17058. enumerable: true,
  17059. configurable: true
  17060. });
  17061. Scene.prototype.getActiveParticles = function () {
  17062. return this._activeParticles.current;
  17063. };
  17064. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  17065. get: function () {
  17066. return this._activeParticles;
  17067. },
  17068. enumerable: true,
  17069. configurable: true
  17070. });
  17071. Scene.prototype.getActiveBones = function () {
  17072. return this._activeBones.current;
  17073. };
  17074. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  17075. get: function () {
  17076. return this._activeBones;
  17077. },
  17078. enumerable: true,
  17079. configurable: true
  17080. });
  17081. // Stats
  17082. Scene.prototype.getLastFrameDuration = function () {
  17083. return this._lastFrameDuration.current;
  17084. };
  17085. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  17086. get: function () {
  17087. return this._lastFrameDuration;
  17088. },
  17089. enumerable: true,
  17090. configurable: true
  17091. });
  17092. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  17093. return this._evaluateActiveMeshesDuration.current;
  17094. };
  17095. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  17096. get: function () {
  17097. return this._evaluateActiveMeshesDuration;
  17098. },
  17099. enumerable: true,
  17100. configurable: true
  17101. });
  17102. Scene.prototype.getActiveMeshes = function () {
  17103. return this._activeMeshes;
  17104. };
  17105. Scene.prototype.getRenderTargetsDuration = function () {
  17106. return this._renderTargetsDuration.current;
  17107. };
  17108. Scene.prototype.getRenderDuration = function () {
  17109. return this._renderDuration.current;
  17110. };
  17111. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  17112. get: function () {
  17113. return this._renderDuration;
  17114. },
  17115. enumerable: true,
  17116. configurable: true
  17117. });
  17118. Scene.prototype.getParticlesDuration = function () {
  17119. return this._particlesDuration.current;
  17120. };
  17121. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  17122. get: function () {
  17123. return this._particlesDuration;
  17124. },
  17125. enumerable: true,
  17126. configurable: true
  17127. });
  17128. Scene.prototype.getSpritesDuration = function () {
  17129. return this._spritesDuration.current;
  17130. };
  17131. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  17132. get: function () {
  17133. return this._spritesDuration;
  17134. },
  17135. enumerable: true,
  17136. configurable: true
  17137. });
  17138. Scene.prototype.getAnimationRatio = function () {
  17139. return this._animationRatio;
  17140. };
  17141. Scene.prototype.getRenderId = function () {
  17142. return this._renderId;
  17143. };
  17144. Scene.prototype.incrementRenderId = function () {
  17145. this._renderId++;
  17146. };
  17147. Scene.prototype._updatePointerPosition = function (evt) {
  17148. var canvasRect = this._engine.getRenderingCanvasClientRect();
  17149. this._pointerX = evt.clientX - canvasRect.left;
  17150. this._pointerY = evt.clientY - canvasRect.top;
  17151. this._unTranslatedPointerX = this._pointerX;
  17152. this._unTranslatedPointerY = this._pointerY;
  17153. if (this.cameraToUseForPointers) {
  17154. this._pointerX = this._pointerX - this.cameraToUseForPointers.viewport.x * this._engine.getRenderWidth();
  17155. this._pointerY = this._pointerY - this.cameraToUseForPointers.viewport.y * this._engine.getRenderHeight();
  17156. }
  17157. };
  17158. // Pointers handling
  17159. /**
  17160. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17161. * @param attachUp defines if you want to attach events to pointerup
  17162. * @param attachDown defines if you want to attach events to pointerdown
  17163. * @param attachMove defines if you want to attach events to pointermove
  17164. */
  17165. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17166. var _this = this;
  17167. if (attachUp === void 0) { attachUp = true; }
  17168. if (attachDown === void 0) { attachDown = true; }
  17169. if (attachMove === void 0) { attachMove = true; }
  17170. var spritePredicate = function (sprite) {
  17171. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17172. };
  17173. this._onPointerMove = function (evt) {
  17174. _this._updatePointerPosition(evt);
  17175. // PreObservable support
  17176. if (_this.onPrePointerObservable.hasObservers()) {
  17177. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17178. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17179. _this.onPrePointerObservable.notifyObservers(pi, type);
  17180. if (pi.skipOnPointerObservable) {
  17181. return;
  17182. }
  17183. }
  17184. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17185. return;
  17186. }
  17187. var canvas = _this._engine.getRenderingCanvas();
  17188. if (!_this.pointerMovePredicate) {
  17189. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && (_this.constantlyUpdateMeshUnderPointer || mesh.actionManager !== null && mesh.actionManager !== undefined); };
  17190. }
  17191. // Meshes
  17192. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17193. if (pickResult.hit && pickResult.pickedMesh) {
  17194. _this.setPointerOverSprite(null);
  17195. _this.setPointerOverMesh(pickResult.pickedMesh);
  17196. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17197. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17198. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17199. }
  17200. else {
  17201. canvas.style.cursor = _this.hoverCursor;
  17202. }
  17203. }
  17204. else {
  17205. canvas.style.cursor = "";
  17206. }
  17207. }
  17208. else {
  17209. _this.setPointerOverMesh(null);
  17210. // Sprites
  17211. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17212. if (pickResult.hit && pickResult.pickedSprite) {
  17213. _this.setPointerOverSprite(pickResult.pickedSprite);
  17214. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17215. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17216. }
  17217. else {
  17218. canvas.style.cursor = _this.hoverCursor;
  17219. }
  17220. }
  17221. else {
  17222. _this.setPointerOverSprite(null);
  17223. // Restore pointer
  17224. canvas.style.cursor = "";
  17225. }
  17226. }
  17227. if (_this.onPointerMove) {
  17228. _this.onPointerMove(evt, pickResult);
  17229. }
  17230. if (_this.onPointerObservable.hasObservers()) {
  17231. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17232. var pi = new PointerInfo(type, evt, pickResult);
  17233. _this.onPointerObservable.notifyObservers(pi, type);
  17234. }
  17235. };
  17236. this._onPointerDown = function (evt) {
  17237. _this._updatePointerPosition(evt);
  17238. // PreObservable support
  17239. if (_this.onPrePointerObservable.hasObservers()) {
  17240. var type = PointerEventTypes.POINTERDOWN;
  17241. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17242. _this.onPrePointerObservable.notifyObservers(pi, type);
  17243. if (pi.skipOnPointerObservable) {
  17244. return;
  17245. }
  17246. }
  17247. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17248. return;
  17249. }
  17250. _this._startingPointerPosition.x = _this._pointerX;
  17251. _this._startingPointerPosition.y = _this._pointerY;
  17252. _this._startingPointerTime = new Date().getTime();
  17253. if (!_this.pointerDownPredicate) {
  17254. _this.pointerDownPredicate = function (mesh) {
  17255. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17256. };
  17257. }
  17258. // Meshes
  17259. _this._pickedDownMesh = null;
  17260. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17261. if (pickResult.hit && pickResult.pickedMesh) {
  17262. if (pickResult.pickedMesh.actionManager) {
  17263. _this._pickedDownMesh = pickResult.pickedMesh;
  17264. if (pickResult.pickedMesh.actionManager.hasPickTriggers) {
  17265. switch (evt.button) {
  17266. case 0:
  17267. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17268. break;
  17269. case 1:
  17270. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17271. break;
  17272. case 2:
  17273. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17274. break;
  17275. }
  17276. if (pickResult.pickedMesh.actionManager) {
  17277. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17278. }
  17279. }
  17280. if (pickResult.pickedMesh.actionManager && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17281. var that = _this;
  17282. window.setTimeout(function () {
  17283. 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);
  17284. if (pickResult.hit && pickResult.pickedMesh) {
  17285. if (pickResult.pickedMesh.actionManager) {
  17286. 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)) {
  17287. that._startingPointerTime = 0;
  17288. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17289. }
  17290. }
  17291. }
  17292. }, BABYLON.ActionManager.LongPressDelay);
  17293. }
  17294. }
  17295. }
  17296. if (_this.onPointerDown) {
  17297. _this.onPointerDown(evt, pickResult);
  17298. }
  17299. if (_this.onPointerObservable.hasObservers()) {
  17300. var type = PointerEventTypes.POINTERDOWN;
  17301. var pi = new PointerInfo(type, evt, pickResult);
  17302. _this.onPointerObservable.notifyObservers(pi, type);
  17303. }
  17304. // Sprites
  17305. _this._pickedDownSprite = null;
  17306. if (_this.spriteManagers.length > 0) {
  17307. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17308. if (pickResult.hit && pickResult.pickedSprite) {
  17309. if (pickResult.pickedSprite.actionManager) {
  17310. _this._pickedDownSprite = pickResult.pickedSprite;
  17311. switch (evt.button) {
  17312. case 0:
  17313. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17314. break;
  17315. case 1:
  17316. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17317. break;
  17318. case 2:
  17319. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17320. break;
  17321. }
  17322. if (pickResult.pickedSprite.actionManager) {
  17323. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17324. }
  17325. }
  17326. }
  17327. }
  17328. };
  17329. this._onPointerUp = function (evt) {
  17330. _this._updatePointerPosition(evt);
  17331. // PreObservable support
  17332. if (_this.onPrePointerObservable.hasObservers()) {
  17333. var type = PointerEventTypes.POINTERUP;
  17334. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17335. _this.onPrePointerObservable.notifyObservers(pi, type);
  17336. if (pi.skipOnPointerObservable) {
  17337. return;
  17338. }
  17339. }
  17340. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17341. return;
  17342. }
  17343. if (!_this.pointerUpPredicate) {
  17344. _this.pointerUpPredicate = function (mesh) {
  17345. return mesh.isPickable && mesh.isVisible && mesh.isReady();
  17346. };
  17347. }
  17348. // Meshes
  17349. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerUpPredicate, false, _this.cameraToUseForPointers);
  17350. if (pickResult.hit && pickResult.pickedMesh) {
  17351. if (_this._pickedDownMesh != null && pickResult.pickedMesh == _this._pickedDownMesh) {
  17352. if (_this.onPointerPick) {
  17353. _this.onPointerPick(evt, pickResult);
  17354. }
  17355. if (_this.onPointerObservable.hasObservers()) {
  17356. var type = PointerEventTypes.POINTERPICK;
  17357. var pi = new PointerInfo(type, evt, pickResult);
  17358. _this.onPointerObservable.notifyObservers(pi, type);
  17359. }
  17360. }
  17361. if (pickResult.pickedMesh.actionManager) {
  17362. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17363. if (pickResult.pickedMesh.actionManager) {
  17364. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17365. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17366. }
  17367. }
  17368. }
  17369. }
  17370. if (_this._pickedDownMesh && _this._pickedDownMesh.actionManager && _this._pickedDownMesh !== pickResult.pickedMesh) {
  17371. _this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(_this._pickedDownMesh, evt));
  17372. }
  17373. if (_this.onPointerUp) {
  17374. _this.onPointerUp(evt, pickResult);
  17375. }
  17376. if (_this.onPointerObservable.hasObservers()) {
  17377. var type = PointerEventTypes.POINTERUP;
  17378. var pi = new PointerInfo(type, evt, pickResult);
  17379. _this.onPointerObservable.notifyObservers(pi, type);
  17380. }
  17381. _this._startingPointerTime = 0;
  17382. // Sprites
  17383. if (_this.spriteManagers.length > 0) {
  17384. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17385. if (pickResult.hit && pickResult.pickedSprite) {
  17386. if (pickResult.pickedSprite.actionManager) {
  17387. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17388. if (pickResult.pickedSprite.actionManager) {
  17389. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < BABYLON.ActionManager.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < BABYLON.ActionManager.DragMovementThreshold) {
  17390. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17391. }
  17392. }
  17393. }
  17394. }
  17395. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== pickResult.pickedSprite) {
  17396. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  17397. }
  17398. }
  17399. };
  17400. this._onKeyDown = function (evt) {
  17401. if (_this.actionManager) {
  17402. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17403. }
  17404. };
  17405. this._onKeyUp = function (evt) {
  17406. if (_this.actionManager) {
  17407. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17408. }
  17409. };
  17410. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17411. var canvas = this._engine.getRenderingCanvas();
  17412. if (attachMove) {
  17413. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17414. // Wheel
  17415. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17416. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17417. }
  17418. if (attachDown) {
  17419. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17420. }
  17421. if (attachUp) {
  17422. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17423. }
  17424. canvas.tabIndex = 1;
  17425. canvas.addEventListener("keydown", this._onKeyDown, false);
  17426. canvas.addEventListener("keyup", this._onKeyUp, false);
  17427. };
  17428. Scene.prototype.detachControl = function () {
  17429. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17430. var canvas = this._engine.getRenderingCanvas();
  17431. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17432. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17433. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17434. // Wheel
  17435. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17436. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17437. canvas.removeEventListener("keydown", this._onKeyDown);
  17438. canvas.removeEventListener("keyup", this._onKeyUp);
  17439. };
  17440. // Ready
  17441. Scene.prototype.isReady = function () {
  17442. if (this._pendingData.length > 0) {
  17443. return false;
  17444. }
  17445. var index;
  17446. for (index = 0; index < this._geometries.length; index++) {
  17447. var geometry = this._geometries[index];
  17448. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17449. return false;
  17450. }
  17451. }
  17452. for (index = 0; index < this.meshes.length; index++) {
  17453. var mesh = this.meshes[index];
  17454. if (!mesh.isReady()) {
  17455. return false;
  17456. }
  17457. var mat = mesh.material;
  17458. if (mat) {
  17459. if (!mat.isReady(mesh)) {
  17460. return false;
  17461. }
  17462. }
  17463. }
  17464. return true;
  17465. };
  17466. Scene.prototype.resetCachedMaterial = function () {
  17467. this._cachedMaterial = null;
  17468. };
  17469. Scene.prototype.registerBeforeRender = function (func) {
  17470. this.onBeforeRenderObservable.add(func);
  17471. };
  17472. Scene.prototype.unregisterBeforeRender = function (func) {
  17473. this.onBeforeRenderObservable.removeCallback(func);
  17474. };
  17475. Scene.prototype.registerAfterRender = function (func) {
  17476. this.onAfterRenderObservable.add(func);
  17477. };
  17478. Scene.prototype.unregisterAfterRender = function (func) {
  17479. this.onAfterRenderObservable.removeCallback(func);
  17480. };
  17481. Scene.prototype._addPendingData = function (data) {
  17482. this._pendingData.push(data);
  17483. };
  17484. Scene.prototype._removePendingData = function (data) {
  17485. var index = this._pendingData.indexOf(data);
  17486. if (index !== -1) {
  17487. this._pendingData.splice(index, 1);
  17488. }
  17489. };
  17490. Scene.prototype.getWaitingItemsCount = function () {
  17491. return this._pendingData.length;
  17492. };
  17493. /**
  17494. * Registers a function to be executed when the scene is ready.
  17495. * @param {Function} func - the function to be executed.
  17496. */
  17497. Scene.prototype.executeWhenReady = function (func) {
  17498. var _this = this;
  17499. this.onReadyObservable.add(func);
  17500. if (this._executeWhenReadyTimeoutId !== -1) {
  17501. return;
  17502. }
  17503. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17504. _this._checkIsReady();
  17505. }, 150);
  17506. };
  17507. Scene.prototype._checkIsReady = function () {
  17508. var _this = this;
  17509. if (this.isReady()) {
  17510. this.onReadyObservable.notifyObservers(this);
  17511. this.onReadyObservable.clear();
  17512. this._executeWhenReadyTimeoutId = -1;
  17513. return;
  17514. }
  17515. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17516. _this._checkIsReady();
  17517. }, 150);
  17518. };
  17519. // Animations
  17520. /**
  17521. * Will start the animation sequence of a given target
  17522. * @param target - the target
  17523. * @param {number} from - from which frame should animation start
  17524. * @param {number} to - till which frame should animation run.
  17525. * @param {boolean} [loop] - should the animation loop
  17526. * @param {number} [speedRatio] - the speed in which to run the animation
  17527. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17528. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17529. * @return {BABYLON.Animatable} the animatable object created for this animation
  17530. * @see BABYLON.Animatable
  17531. * @see http://doc.babylonjs.com/page.php?p=22081
  17532. */
  17533. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17534. if (speedRatio === void 0) { speedRatio = 1.0; }
  17535. this.stopAnimation(target);
  17536. if (!animatable) {
  17537. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17538. }
  17539. // Local animations
  17540. if (target.animations) {
  17541. animatable.appendAnimations(target, target.animations);
  17542. }
  17543. // Children animations
  17544. if (target.getAnimatables) {
  17545. var animatables = target.getAnimatables();
  17546. for (var index = 0; index < animatables.length; index++) {
  17547. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17548. }
  17549. }
  17550. animatable.reset();
  17551. return animatable;
  17552. };
  17553. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17554. if (speedRatio === undefined) {
  17555. speedRatio = 1.0;
  17556. }
  17557. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17558. return animatable;
  17559. };
  17560. Scene.prototype.getAnimatableByTarget = function (target) {
  17561. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17562. if (this._activeAnimatables[index].target === target) {
  17563. return this._activeAnimatables[index];
  17564. }
  17565. }
  17566. return null;
  17567. };
  17568. Object.defineProperty(Scene.prototype, "Animatables", {
  17569. get: function () {
  17570. return this._activeAnimatables;
  17571. },
  17572. enumerable: true,
  17573. configurable: true
  17574. });
  17575. /**
  17576. * Will stop the animation of the given target
  17577. * @param target - the target
  17578. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17579. * @see beginAnimation
  17580. */
  17581. Scene.prototype.stopAnimation = function (target, animationName) {
  17582. var animatable = this.getAnimatableByTarget(target);
  17583. if (animatable) {
  17584. animatable.stop(animationName);
  17585. }
  17586. };
  17587. Scene.prototype._animate = function () {
  17588. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17589. return;
  17590. }
  17591. // Getting time
  17592. var now = BABYLON.Tools.Now;
  17593. if (!this._animationTimeLast) {
  17594. if (this._pendingData.length > 0) {
  17595. return;
  17596. }
  17597. this._animationTimeLast = now;
  17598. }
  17599. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17600. this._animationTime += deltaTime;
  17601. this._animationTimeLast = now;
  17602. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17603. this._activeAnimatables[index]._animate(this._animationTime);
  17604. }
  17605. };
  17606. // Matrix
  17607. Scene.prototype.getViewMatrix = function () {
  17608. return this._viewMatrix;
  17609. };
  17610. Scene.prototype.getProjectionMatrix = function () {
  17611. return this._projectionMatrix;
  17612. };
  17613. Scene.prototype.getTransformMatrix = function () {
  17614. return this._transformMatrix;
  17615. };
  17616. Scene.prototype.setTransformMatrix = function (view, projection) {
  17617. this._viewMatrix = view;
  17618. this._projectionMatrix = projection;
  17619. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17620. // Update frustum
  17621. if (!this._frustumPlanes) {
  17622. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17623. }
  17624. else {
  17625. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17626. }
  17627. };
  17628. // Methods
  17629. Scene.prototype.addMesh = function (newMesh) {
  17630. newMesh.uniqueId = this._uniqueIdCounter++;
  17631. var position = this.meshes.push(newMesh);
  17632. //notify the collision coordinator
  17633. this.collisionCoordinator.onMeshAdded(newMesh);
  17634. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17635. };
  17636. Scene.prototype.removeMesh = function (toRemove) {
  17637. var index = this.meshes.indexOf(toRemove);
  17638. if (index !== -1) {
  17639. // Remove from the scene if mesh found
  17640. this.meshes.splice(index, 1);
  17641. }
  17642. //notify the collision coordinator
  17643. this.collisionCoordinator.onMeshRemoved(toRemove);
  17644. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17645. return index;
  17646. };
  17647. Scene.prototype.removeSkeleton = function (toRemove) {
  17648. var index = this.skeletons.indexOf(toRemove);
  17649. if (index !== -1) {
  17650. // Remove from the scene if mesh found
  17651. this.skeletons.splice(index, 1);
  17652. }
  17653. return index;
  17654. };
  17655. Scene.prototype.removeLight = function (toRemove) {
  17656. var index = this.lights.indexOf(toRemove);
  17657. if (index !== -1) {
  17658. // Remove from the scene if mesh found
  17659. this.lights.splice(index, 1);
  17660. }
  17661. this.onLightRemovedObservable.notifyObservers(toRemove);
  17662. return index;
  17663. };
  17664. Scene.prototype.removeCamera = function (toRemove) {
  17665. var index = this.cameras.indexOf(toRemove);
  17666. if (index !== -1) {
  17667. // Remove from the scene if mesh found
  17668. this.cameras.splice(index, 1);
  17669. }
  17670. // Remove from activeCameras
  17671. var index2 = this.activeCameras.indexOf(toRemove);
  17672. if (index2 !== -1) {
  17673. // Remove from the scene if mesh found
  17674. this.activeCameras.splice(index2, 1);
  17675. }
  17676. // Reset the activeCamera
  17677. if (this.activeCamera === toRemove) {
  17678. if (this.cameras.length > 0) {
  17679. this.activeCamera = this.cameras[0];
  17680. }
  17681. else {
  17682. this.activeCamera = null;
  17683. }
  17684. }
  17685. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17686. return index;
  17687. };
  17688. Scene.prototype.addLight = function (newLight) {
  17689. newLight.uniqueId = this._uniqueIdCounter++;
  17690. var position = this.lights.push(newLight);
  17691. this.onNewLightAddedObservable.notifyObservers(newLight);
  17692. };
  17693. Scene.prototype.addCamera = function (newCamera) {
  17694. newCamera.uniqueId = this._uniqueIdCounter++;
  17695. var position = this.cameras.push(newCamera);
  17696. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17697. };
  17698. /**
  17699. * Switch active camera
  17700. * @param {Camera} newCamera - new active camera
  17701. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17702. */
  17703. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17704. if (attachControl === void 0) { attachControl = true; }
  17705. var canvas = this._engine.getRenderingCanvas();
  17706. this.activeCamera.detachControl(canvas);
  17707. this.activeCamera = newCamera;
  17708. if (attachControl) {
  17709. newCamera.attachControl(canvas);
  17710. }
  17711. };
  17712. /**
  17713. * sets the active camera of the scene using its ID
  17714. * @param {string} id - the camera's ID
  17715. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17716. * @see activeCamera
  17717. */
  17718. Scene.prototype.setActiveCameraByID = function (id) {
  17719. var camera = this.getCameraByID(id);
  17720. if (camera) {
  17721. this.activeCamera = camera;
  17722. return camera;
  17723. }
  17724. return null;
  17725. };
  17726. /**
  17727. * sets the active camera of the scene using its name
  17728. * @param {string} name - the camera's name
  17729. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17730. * @see activeCamera
  17731. */
  17732. Scene.prototype.setActiveCameraByName = function (name) {
  17733. var camera = this.getCameraByName(name);
  17734. if (camera) {
  17735. this.activeCamera = camera;
  17736. return camera;
  17737. }
  17738. return null;
  17739. };
  17740. /**
  17741. * get a material using its id
  17742. * @param {string} the material's ID
  17743. * @return {BABYLON.Material|null} the material or null if none found.
  17744. */
  17745. Scene.prototype.getMaterialByID = function (id) {
  17746. for (var index = 0; index < this.materials.length; index++) {
  17747. if (this.materials[index].id === id) {
  17748. return this.materials[index];
  17749. }
  17750. }
  17751. return null;
  17752. };
  17753. /**
  17754. * get a material using its name
  17755. * @param {string} the material's name
  17756. * @return {BABYLON.Material|null} the material or null if none found.
  17757. */
  17758. Scene.prototype.getMaterialByName = function (name) {
  17759. for (var index = 0; index < this.materials.length; index++) {
  17760. if (this.materials[index].name === name) {
  17761. return this.materials[index];
  17762. }
  17763. }
  17764. return null;
  17765. };
  17766. Scene.prototype.getLensFlareSystemByName = function (name) {
  17767. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17768. if (this.lensFlareSystems[index].name === name) {
  17769. return this.lensFlareSystems[index];
  17770. }
  17771. }
  17772. return null;
  17773. };
  17774. Scene.prototype.getLensFlareSystemByID = function (id) {
  17775. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17776. if (this.lensFlareSystems[index].id === id) {
  17777. return this.lensFlareSystems[index];
  17778. }
  17779. }
  17780. return null;
  17781. };
  17782. Scene.prototype.getCameraByID = function (id) {
  17783. for (var index = 0; index < this.cameras.length; index++) {
  17784. if (this.cameras[index].id === id) {
  17785. return this.cameras[index];
  17786. }
  17787. }
  17788. return null;
  17789. };
  17790. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17791. for (var index = 0; index < this.cameras.length; index++) {
  17792. if (this.cameras[index].uniqueId === uniqueId) {
  17793. return this.cameras[index];
  17794. }
  17795. }
  17796. return null;
  17797. };
  17798. /**
  17799. * get a camera using its name
  17800. * @param {string} the camera's name
  17801. * @return {BABYLON.Camera|null} the camera or null if none found.
  17802. */
  17803. Scene.prototype.getCameraByName = function (name) {
  17804. for (var index = 0; index < this.cameras.length; index++) {
  17805. if (this.cameras[index].name === name) {
  17806. return this.cameras[index];
  17807. }
  17808. }
  17809. return null;
  17810. };
  17811. /**
  17812. * get a bone using its id
  17813. * @param {string} the bone's id
  17814. * @return {BABYLON.Bone|null} the bone or null if not found
  17815. */
  17816. Scene.prototype.getBoneByID = function (id) {
  17817. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17818. var skeleton = this.skeletons[skeletonIndex];
  17819. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17820. if (skeleton.bones[boneIndex].id === id) {
  17821. return skeleton.bones[boneIndex];
  17822. }
  17823. }
  17824. }
  17825. return null;
  17826. };
  17827. /**
  17828. * get a bone using its id
  17829. * @param {string} the bone's name
  17830. * @return {BABYLON.Bone|null} the bone or null if not found
  17831. */
  17832. Scene.prototype.getBoneByName = function (name) {
  17833. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17834. var skeleton = this.skeletons[skeletonIndex];
  17835. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17836. if (skeleton.bones[boneIndex].name === name) {
  17837. return skeleton.bones[boneIndex];
  17838. }
  17839. }
  17840. }
  17841. return null;
  17842. };
  17843. /**
  17844. * get a light node using its name
  17845. * @param {string} the light's name
  17846. * @return {BABYLON.Light|null} the light or null if none found.
  17847. */
  17848. Scene.prototype.getLightByName = function (name) {
  17849. for (var index = 0; index < this.lights.length; index++) {
  17850. if (this.lights[index].name === name) {
  17851. return this.lights[index];
  17852. }
  17853. }
  17854. return null;
  17855. };
  17856. /**
  17857. * get a light node using its ID
  17858. * @param {string} the light's id
  17859. * @return {BABYLON.Light|null} the light or null if none found.
  17860. */
  17861. Scene.prototype.getLightByID = function (id) {
  17862. for (var index = 0; index < this.lights.length; index++) {
  17863. if (this.lights[index].id === id) {
  17864. return this.lights[index];
  17865. }
  17866. }
  17867. return null;
  17868. };
  17869. /**
  17870. * get a light node using its scene-generated unique ID
  17871. * @param {number} the light's unique id
  17872. * @return {BABYLON.Light|null} the light or null if none found.
  17873. */
  17874. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17875. for (var index = 0; index < this.lights.length; index++) {
  17876. if (this.lights[index].uniqueId === uniqueId) {
  17877. return this.lights[index];
  17878. }
  17879. }
  17880. return null;
  17881. };
  17882. /**
  17883. * get a particle system by id
  17884. * @param id {number} the particle system id
  17885. * @return {BABYLON.ParticleSystem|null} the corresponding system or null if none found.
  17886. */
  17887. Scene.prototype.getParticleSystemByID = function (id) {
  17888. for (var index = 0; index < this.particleSystems.length; index++) {
  17889. if (this.particleSystems[index].id === id) {
  17890. return this.particleSystems[index];
  17891. }
  17892. }
  17893. return null;
  17894. };
  17895. /**
  17896. * get a geometry using its ID
  17897. * @param {string} the geometry's id
  17898. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17899. */
  17900. Scene.prototype.getGeometryByID = function (id) {
  17901. for (var index = 0; index < this._geometries.length; index++) {
  17902. if (this._geometries[index].id === id) {
  17903. return this._geometries[index];
  17904. }
  17905. }
  17906. return null;
  17907. };
  17908. /**
  17909. * add a new geometry to this scene.
  17910. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17911. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17912. * @return {boolean} was the geometry added or not
  17913. */
  17914. Scene.prototype.pushGeometry = function (geometry, force) {
  17915. if (!force && this.getGeometryByID(geometry.id)) {
  17916. return false;
  17917. }
  17918. this._geometries.push(geometry);
  17919. //notify the collision coordinator
  17920. this.collisionCoordinator.onGeometryAdded(geometry);
  17921. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17922. return true;
  17923. };
  17924. /**
  17925. * Removes an existing geometry
  17926. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  17927. * @return {boolean} was the geometry removed or not
  17928. */
  17929. Scene.prototype.removeGeometry = function (geometry) {
  17930. var index = this._geometries.indexOf(geometry);
  17931. if (index > -1) {
  17932. this._geometries.splice(index, 1);
  17933. //notify the collision coordinator
  17934. this.collisionCoordinator.onGeometryDeleted(geometry);
  17935. this.onGeometryRemovedObservable.notifyObservers(geometry);
  17936. return true;
  17937. }
  17938. return false;
  17939. };
  17940. Scene.prototype.getGeometries = function () {
  17941. return this._geometries;
  17942. };
  17943. /**
  17944. * Get the first added mesh found of a given ID
  17945. * @param {string} id - the id to search for
  17946. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17947. */
  17948. Scene.prototype.getMeshByID = function (id) {
  17949. for (var index = 0; index < this.meshes.length; index++) {
  17950. if (this.meshes[index].id === id) {
  17951. return this.meshes[index];
  17952. }
  17953. }
  17954. return null;
  17955. };
  17956. Scene.prototype.getMeshesByID = function (id) {
  17957. return this.meshes.filter(function (m) {
  17958. return m.id === id;
  17959. });
  17960. };
  17961. /**
  17962. * Get a mesh with its auto-generated unique id
  17963. * @param {number} uniqueId - the unique id to search for
  17964. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17965. */
  17966. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  17967. for (var index = 0; index < this.meshes.length; index++) {
  17968. if (this.meshes[index].uniqueId === uniqueId) {
  17969. return this.meshes[index];
  17970. }
  17971. }
  17972. return null;
  17973. };
  17974. /**
  17975. * Get a the last added mesh found of a given ID
  17976. * @param {string} id - the id to search for
  17977. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  17978. */
  17979. Scene.prototype.getLastMeshByID = function (id) {
  17980. for (var index = this.meshes.length - 1; index >= 0; index--) {
  17981. if (this.meshes[index].id === id) {
  17982. return this.meshes[index];
  17983. }
  17984. }
  17985. return null;
  17986. };
  17987. /**
  17988. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  17989. * @param {string} id - the id to search for
  17990. * @return {BABYLON.Node|null} the node found or null if not found at all.
  17991. */
  17992. Scene.prototype.getLastEntryByID = function (id) {
  17993. var index;
  17994. for (index = this.meshes.length - 1; index >= 0; index--) {
  17995. if (this.meshes[index].id === id) {
  17996. return this.meshes[index];
  17997. }
  17998. }
  17999. for (index = this.cameras.length - 1; index >= 0; index--) {
  18000. if (this.cameras[index].id === id) {
  18001. return this.cameras[index];
  18002. }
  18003. }
  18004. for (index = this.lights.length - 1; index >= 0; index--) {
  18005. if (this.lights[index].id === id) {
  18006. return this.lights[index];
  18007. }
  18008. }
  18009. return null;
  18010. };
  18011. Scene.prototype.getNodeByID = function (id) {
  18012. var mesh = this.getMeshByID(id);
  18013. if (mesh) {
  18014. return mesh;
  18015. }
  18016. var light = this.getLightByID(id);
  18017. if (light) {
  18018. return light;
  18019. }
  18020. var camera = this.getCameraByID(id);
  18021. if (camera) {
  18022. return camera;
  18023. }
  18024. var bone = this.getBoneByID(id);
  18025. return bone;
  18026. };
  18027. Scene.prototype.getNodeByName = function (name) {
  18028. var mesh = this.getMeshByName(name);
  18029. if (mesh) {
  18030. return mesh;
  18031. }
  18032. var light = this.getLightByName(name);
  18033. if (light) {
  18034. return light;
  18035. }
  18036. var camera = this.getCameraByName(name);
  18037. if (camera) {
  18038. return camera;
  18039. }
  18040. var bone = this.getBoneByName(name);
  18041. return bone;
  18042. };
  18043. Scene.prototype.getMeshByName = function (name) {
  18044. for (var index = 0; index < this.meshes.length; index++) {
  18045. if (this.meshes[index].name === name) {
  18046. return this.meshes[index];
  18047. }
  18048. }
  18049. return null;
  18050. };
  18051. Scene.prototype.getSoundByName = function (name) {
  18052. var index;
  18053. if (BABYLON.AudioEngine) {
  18054. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18055. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18056. return this.mainSoundTrack.soundCollection[index];
  18057. }
  18058. }
  18059. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18060. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18061. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18062. return this.soundTracks[sdIndex].soundCollection[index];
  18063. }
  18064. }
  18065. }
  18066. }
  18067. return null;
  18068. };
  18069. Scene.prototype.getLastSkeletonByID = function (id) {
  18070. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18071. if (this.skeletons[index].id === id) {
  18072. return this.skeletons[index];
  18073. }
  18074. }
  18075. return null;
  18076. };
  18077. Scene.prototype.getSkeletonById = function (id) {
  18078. for (var index = 0; index < this.skeletons.length; index++) {
  18079. if (this.skeletons[index].id === id) {
  18080. return this.skeletons[index];
  18081. }
  18082. }
  18083. return null;
  18084. };
  18085. Scene.prototype.getSkeletonByName = function (name) {
  18086. for (var index = 0; index < this.skeletons.length; index++) {
  18087. if (this.skeletons[index].name === name) {
  18088. return this.skeletons[index];
  18089. }
  18090. }
  18091. return null;
  18092. };
  18093. Scene.prototype.isActiveMesh = function (mesh) {
  18094. return (this._activeMeshes.indexOf(mesh) !== -1);
  18095. };
  18096. Object.defineProperty(Scene.prototype, "uid", {
  18097. /**
  18098. * Return a unique id as a string which can serve as an identifier for the scene
  18099. */
  18100. get: function () {
  18101. if (!this._uid) {
  18102. this._uid = BABYLON.Tools.RandomId();
  18103. }
  18104. return this._uid;
  18105. },
  18106. enumerable: true,
  18107. configurable: true
  18108. });
  18109. /**
  18110. * Add an externaly attached data from its key.
  18111. * This method call will fail and return false, if such key already exists.
  18112. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18113. * @param key the unique key that identifies the data
  18114. * @param data the data object to associate to the key for this Engine instance
  18115. * @return true if no such key were already present and the data was added successfully, false otherwise
  18116. */
  18117. Scene.prototype.addExternalData = function (key, data) {
  18118. return this._externalData.add(key, data);
  18119. };
  18120. /**
  18121. * Get an externaly attached data from its key
  18122. * @param key the unique key that identifies the data
  18123. * @return the associated data, if present (can be null), or undefined if not present
  18124. */
  18125. Scene.prototype.getExternalData = function (key) {
  18126. return this._externalData.get(key);
  18127. };
  18128. /**
  18129. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18130. * @param key the unique key that identifies the data
  18131. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18132. * @return the associated data, can be null if the factory returned null.
  18133. */
  18134. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18135. return this._externalData.getOrAddWithFactory(key, factory);
  18136. };
  18137. /**
  18138. * Remove an externaly attached data from the Engine instance
  18139. * @param key the unique key that identifies the data
  18140. * @return true if the data was successfully removed, false if it doesn't exist
  18141. */
  18142. Scene.prototype.removeExternalData = function (key) {
  18143. return this._externalData.remove(key);
  18144. };
  18145. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18146. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18147. var material = subMesh.getMaterial();
  18148. if (mesh.showSubMeshesBoundingBox) {
  18149. this._boundingBoxRenderer.renderList.push(subMesh.getBoundingInfo().boundingBox);
  18150. }
  18151. if (material) {
  18152. // Render targets
  18153. if (material.getRenderTargetTextures) {
  18154. if (this._processedMaterials.indexOf(material) === -1) {
  18155. this._processedMaterials.push(material);
  18156. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18157. }
  18158. }
  18159. // Dispatch
  18160. this._activeIndices.addCount(subMesh.indexCount, false);
  18161. this._renderingManager.dispatch(subMesh);
  18162. }
  18163. }
  18164. };
  18165. Scene.prototype._isInIntermediateRendering = function () {
  18166. return this._intermediateRendering;
  18167. };
  18168. Scene.prototype._evaluateActiveMeshes = function () {
  18169. this.activeCamera._activeMeshes.reset();
  18170. this._activeMeshes.reset();
  18171. this._renderingManager.reset();
  18172. this._processedMaterials.reset();
  18173. this._activeParticleSystems.reset();
  18174. this._activeSkeletons.reset();
  18175. this._softwareSkinnedMeshes.reset();
  18176. this._boundingBoxRenderer.reset();
  18177. this._edgesRenderers.reset();
  18178. // Meshes
  18179. var meshes;
  18180. var len;
  18181. if (this._selectionOctree) {
  18182. var selection = this._selectionOctree.select(this._frustumPlanes);
  18183. meshes = selection.data;
  18184. len = selection.length;
  18185. }
  18186. else {
  18187. len = this.meshes.length;
  18188. meshes = this.meshes;
  18189. }
  18190. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18191. var mesh = meshes[meshIndex];
  18192. if (mesh.isBlocked) {
  18193. continue;
  18194. }
  18195. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18196. if (!mesh.isReady() || !mesh.isEnabled()) {
  18197. continue;
  18198. }
  18199. mesh.computeWorldMatrix();
  18200. // Intersections
  18201. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18202. this._meshesForIntersections.pushNoDuplicate(mesh);
  18203. }
  18204. // Switch to current LOD
  18205. var meshLOD = mesh.getLOD(this.activeCamera);
  18206. if (!meshLOD) {
  18207. continue;
  18208. }
  18209. mesh._preActivate();
  18210. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18211. this._activeMeshes.push(mesh);
  18212. this.activeCamera._activeMeshes.push(mesh);
  18213. mesh._activate(this._renderId);
  18214. this._activeMesh(mesh, meshLOD);
  18215. }
  18216. }
  18217. // Particle systems
  18218. this._particlesDuration.beginMonitoring();
  18219. var beforeParticlesDate = BABYLON.Tools.Now;
  18220. if (this.particlesEnabled) {
  18221. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18222. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18223. var particleSystem = this.particleSystems[particleIndex];
  18224. if (!particleSystem.isStarted()) {
  18225. continue;
  18226. }
  18227. if (!particleSystem.emitter.position || (particleSystem.emitter && particleSystem.emitter.isEnabled())) {
  18228. this._activeParticleSystems.push(particleSystem);
  18229. particleSystem.animate();
  18230. this._renderingManager.dispatchParticles(particleSystem);
  18231. }
  18232. }
  18233. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18234. }
  18235. this._particlesDuration.endMonitoring(false);
  18236. };
  18237. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18238. if (mesh.skeleton && this.skeletonsEnabled) {
  18239. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18240. mesh.skeleton.prepare();
  18241. }
  18242. if (!mesh.computeBonesUsingShaders) {
  18243. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18244. }
  18245. }
  18246. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18247. this._boundingBoxRenderer.renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18248. }
  18249. if (sourceMesh._edgesRenderer) {
  18250. this._edgesRenderers.push(sourceMesh._edgesRenderer);
  18251. }
  18252. if (mesh && mesh.subMeshes) {
  18253. // Submeshes Octrees
  18254. var len;
  18255. var subMeshes;
  18256. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18257. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18258. len = intersections.length;
  18259. subMeshes = intersections.data;
  18260. }
  18261. else {
  18262. subMeshes = mesh.subMeshes;
  18263. len = subMeshes.length;
  18264. }
  18265. for (var subIndex = 0; subIndex < len; subIndex++) {
  18266. var subMesh = subMeshes[subIndex];
  18267. this._evaluateSubMesh(subMesh, mesh);
  18268. }
  18269. }
  18270. };
  18271. Scene.prototype.updateTransformMatrix = function (force) {
  18272. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18273. };
  18274. Scene.prototype._renderForCamera = function (camera) {
  18275. var engine = this._engine;
  18276. var startTime = BABYLON.Tools.Now;
  18277. this.activeCamera = camera;
  18278. if (!this.activeCamera)
  18279. throw new Error("Active camera not set");
  18280. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18281. // Viewport
  18282. engine.setViewport(this.activeCamera.viewport);
  18283. // Camera
  18284. this.resetCachedMaterial();
  18285. this._renderId++;
  18286. this.updateTransformMatrix();
  18287. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18288. // Meshes
  18289. this._evaluateActiveMeshesDuration.beginMonitoring();
  18290. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18291. this._evaluateActiveMeshes();
  18292. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18293. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18294. // Software skinning
  18295. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18296. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18297. mesh.applySkeleton(mesh.skeleton);
  18298. }
  18299. // Render targets
  18300. this._renderTargetsDuration.beginMonitoring();
  18301. var needsRestoreFrameBuffer = false;
  18302. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18303. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18304. this._intermediateRendering = true;
  18305. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18306. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18307. var renderTarget = this._renderTargets.data[renderIndex];
  18308. if (renderTarget._shouldRender()) {
  18309. this._renderId++;
  18310. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18311. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18312. }
  18313. }
  18314. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18315. this._intermediateRendering = false;
  18316. this._renderId++;
  18317. needsRestoreFrameBuffer = true; // Restore back buffer
  18318. }
  18319. // Render HighlightLayer Texture
  18320. var stencilState = this._engine.getStencilBuffer();
  18321. var renderhighlights = false;
  18322. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18323. this._intermediateRendering = true;
  18324. for (var i = 0; i < this.highlightLayers.length; i++) {
  18325. var highlightLayer = this.highlightLayers[i];
  18326. if (highlightLayer.shouldRender() &&
  18327. (!highlightLayer.camera ||
  18328. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18329. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18330. renderhighlights = true;
  18331. var renderTarget = highlightLayer._mainTexture;
  18332. if (renderTarget._shouldRender()) {
  18333. this._renderId++;
  18334. renderTarget.render(false, false);
  18335. needsRestoreFrameBuffer = true;
  18336. }
  18337. }
  18338. }
  18339. this._intermediateRendering = false;
  18340. this._renderId++;
  18341. }
  18342. if (needsRestoreFrameBuffer) {
  18343. engine.restoreDefaultFramebuffer();
  18344. }
  18345. this._renderTargetsDuration.endMonitoring(false);
  18346. // Prepare Frame
  18347. this.postProcessManager._prepareFrame();
  18348. this._renderDuration.beginMonitoring();
  18349. // Backgrounds
  18350. var layerIndex;
  18351. var layer;
  18352. if (this.layers.length) {
  18353. engine.setDepthBuffer(false);
  18354. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18355. layer = this.layers[layerIndex];
  18356. if (layer.isBackground) {
  18357. layer.render();
  18358. }
  18359. }
  18360. engine.setDepthBuffer(true);
  18361. }
  18362. // Render
  18363. BABYLON.Tools.StartPerformanceCounter("Main render");
  18364. // Activate HighlightLayer stencil
  18365. if (renderhighlights) {
  18366. this._engine.setStencilBuffer(true);
  18367. }
  18368. this._renderingManager.render(null, null, true, true);
  18369. // Restore HighlightLayer stencil
  18370. if (renderhighlights) {
  18371. this._engine.setStencilBuffer(stencilState);
  18372. }
  18373. BABYLON.Tools.EndPerformanceCounter("Main render");
  18374. // Bounding boxes
  18375. this._boundingBoxRenderer.render();
  18376. // Edges
  18377. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  18378. this._edgesRenderers.data[edgesRendererIndex].render();
  18379. }
  18380. // Lens flares
  18381. if (this.lensFlaresEnabled) {
  18382. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18383. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18384. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18385. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18386. lensFlareSystem.render();
  18387. }
  18388. }
  18389. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18390. }
  18391. // Foregrounds
  18392. if (this.layers.length) {
  18393. engine.setDepthBuffer(false);
  18394. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18395. layer = this.layers[layerIndex];
  18396. if (!layer.isBackground) {
  18397. layer.render();
  18398. }
  18399. }
  18400. engine.setDepthBuffer(true);
  18401. }
  18402. // Highlight Layer
  18403. if (renderhighlights) {
  18404. engine.setDepthBuffer(false);
  18405. for (var i = 0; i < this.highlightLayers.length; i++) {
  18406. if (this.highlightLayers[i].shouldRender()) {
  18407. this.highlightLayers[i].render();
  18408. }
  18409. }
  18410. engine.setDepthBuffer(true);
  18411. }
  18412. this._renderDuration.endMonitoring(false);
  18413. // Finalize frame
  18414. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18415. // Update camera
  18416. this.activeCamera._updateFromScene();
  18417. // Reset some special arrays
  18418. this._renderTargets.reset();
  18419. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18420. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18421. };
  18422. Scene.prototype._processSubCameras = function (camera) {
  18423. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18424. this._renderForCamera(camera);
  18425. return;
  18426. }
  18427. // rig cameras
  18428. for (var index = 0; index < camera._rigCameras.length; index++) {
  18429. this._renderForCamera(camera._rigCameras[index]);
  18430. }
  18431. this.activeCamera = camera;
  18432. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18433. // Update camera
  18434. this.activeCamera._updateFromScene();
  18435. };
  18436. Scene.prototype._checkIntersections = function () {
  18437. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18438. var sourceMesh = this._meshesForIntersections.data[index];
  18439. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18440. var action = sourceMesh.actionManager.actions[actionIndex];
  18441. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18442. var parameters = action.getTriggerParameter();
  18443. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18444. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18445. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18446. if (areIntersecting && currentIntersectionInProgress === -1) {
  18447. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18448. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18449. sourceMesh._intersectionsInProgress.push(otherMesh);
  18450. }
  18451. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18452. sourceMesh._intersectionsInProgress.push(otherMesh);
  18453. }
  18454. }
  18455. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18456. //They intersected, and now they don't.
  18457. //is this trigger an exit trigger? execute an event.
  18458. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18459. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18460. }
  18461. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18462. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18463. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18464. }
  18465. }
  18466. }
  18467. }
  18468. }
  18469. };
  18470. Scene.prototype.render = function () {
  18471. this._lastFrameDuration.beginMonitoring();
  18472. this._particlesDuration.fetchNewFrame();
  18473. this._spritesDuration.fetchNewFrame();
  18474. this._activeParticles.fetchNewFrame();
  18475. this._renderDuration.fetchNewFrame();
  18476. this._renderTargetsDuration.fetchNewFrame();
  18477. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18478. this._totalVertices.fetchNewFrame();
  18479. this._activeIndices.fetchNewFrame();
  18480. this._activeBones.fetchNewFrame();
  18481. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18482. this._meshesForIntersections.reset();
  18483. this.resetCachedMaterial();
  18484. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18485. // Actions
  18486. if (this.actionManager) {
  18487. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18488. }
  18489. //Simplification Queue
  18490. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18491. this.simplificationQueue.executeNext();
  18492. }
  18493. // Animations
  18494. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18495. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18496. this._animate();
  18497. // Physics
  18498. if (this._physicsEngine) {
  18499. BABYLON.Tools.StartPerformanceCounter("Physics");
  18500. this._physicsEngine._step(deltaTime / 1000.0);
  18501. BABYLON.Tools.EndPerformanceCounter("Physics");
  18502. }
  18503. // Before render
  18504. this.onBeforeRenderObservable.notifyObservers(this);
  18505. // Customs render targets
  18506. this._renderTargetsDuration.beginMonitoring();
  18507. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18508. var engine = this.getEngine();
  18509. var currentActiveCamera = this.activeCamera;
  18510. if (this.renderTargetsEnabled) {
  18511. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18512. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18513. var renderTarget = this.customRenderTargets[customIndex];
  18514. if (renderTarget._shouldRender()) {
  18515. this._renderId++;
  18516. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18517. if (!this.activeCamera)
  18518. throw new Error("Active camera not set");
  18519. // Viewport
  18520. engine.setViewport(this.activeCamera.viewport);
  18521. // Camera
  18522. this.updateTransformMatrix();
  18523. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18524. }
  18525. }
  18526. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18527. this._renderId++;
  18528. }
  18529. if (this.customRenderTargets.length > 0) {
  18530. engine.restoreDefaultFramebuffer();
  18531. }
  18532. this._renderTargetsDuration.endMonitoring();
  18533. this.activeCamera = currentActiveCamera;
  18534. // Procedural textures
  18535. if (this.proceduralTexturesEnabled) {
  18536. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18537. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18538. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18539. if (proceduralTexture._shouldRender()) {
  18540. proceduralTexture.render();
  18541. }
  18542. }
  18543. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18544. }
  18545. // Clear
  18546. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, true, true);
  18547. // Shadows
  18548. if (this.shadowsEnabled) {
  18549. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18550. var light = this.lights[lightIndex];
  18551. var shadowGenerator = light.getShadowGenerator();
  18552. if (light.isEnabled() && shadowGenerator && shadowGenerator.getShadowMap().getScene().textures.indexOf(shadowGenerator.getShadowMap()) !== -1) {
  18553. this._renderTargets.push(shadowGenerator.getShadowMap());
  18554. }
  18555. }
  18556. }
  18557. // Depth renderer
  18558. if (this._depthRenderer) {
  18559. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18560. }
  18561. // RenderPipeline
  18562. this.postProcessRenderPipelineManager.update();
  18563. // Multi-cameras?
  18564. if (this.activeCameras.length > 0) {
  18565. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18566. if (cameraIndex > 0) {
  18567. this._engine.clear(null, false, true, true);
  18568. }
  18569. this._processSubCameras(this.activeCameras[cameraIndex]);
  18570. }
  18571. }
  18572. else {
  18573. if (!this.activeCamera) {
  18574. throw new Error("No camera defined");
  18575. }
  18576. this._processSubCameras(this.activeCamera);
  18577. }
  18578. // Intersection checks
  18579. this._checkIntersections();
  18580. // Update the audio listener attached to the camera
  18581. if (BABYLON.AudioEngine) {
  18582. this._updateAudioParameters();
  18583. }
  18584. // After render
  18585. if (this.afterRender) {
  18586. this.afterRender();
  18587. }
  18588. this.onAfterRenderObservable.notifyObservers(this);
  18589. // Cleaning
  18590. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18591. this._toBeDisposed.data[index].dispose();
  18592. this._toBeDisposed[index] = null;
  18593. }
  18594. this._toBeDisposed.reset();
  18595. if (this.dumpNextRenderTargets) {
  18596. this.dumpNextRenderTargets = false;
  18597. }
  18598. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18599. this._lastFrameDuration.endMonitoring();
  18600. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18601. this._totalLightsCounter.addCount(this.lights.length, true);
  18602. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18603. this._totalTexturesCounter.addCount(this.textures.length, true);
  18604. this._activeBones.addCount(0, true);
  18605. this._activeIndices.addCount(0, true);
  18606. this._activeParticles.addCount(0, true);
  18607. };
  18608. Scene.prototype._updateAudioParameters = function () {
  18609. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18610. return;
  18611. }
  18612. var listeningCamera;
  18613. var audioEngine = BABYLON.Engine.audioEngine;
  18614. if (this.activeCameras.length > 0) {
  18615. listeningCamera = this.activeCameras[0];
  18616. }
  18617. else {
  18618. listeningCamera = this.activeCamera;
  18619. }
  18620. if (listeningCamera && audioEngine.canUseWebAudio) {
  18621. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18622. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18623. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18624. cameraDirection.normalize();
  18625. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18626. var i;
  18627. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18628. var sound = this.mainSoundTrack.soundCollection[i];
  18629. if (sound.useCustomAttenuation) {
  18630. sound.updateDistanceFromListener();
  18631. }
  18632. }
  18633. for (i = 0; i < this.soundTracks.length; i++) {
  18634. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18635. sound = this.soundTracks[i].soundCollection[j];
  18636. if (sound.useCustomAttenuation) {
  18637. sound.updateDistanceFromListener();
  18638. }
  18639. }
  18640. }
  18641. }
  18642. };
  18643. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18644. // Audio
  18645. get: function () {
  18646. return this._audioEnabled;
  18647. },
  18648. set: function (value) {
  18649. this._audioEnabled = value;
  18650. if (BABYLON.AudioEngine) {
  18651. if (this._audioEnabled) {
  18652. this._enableAudio();
  18653. }
  18654. else {
  18655. this._disableAudio();
  18656. }
  18657. }
  18658. },
  18659. enumerable: true,
  18660. configurable: true
  18661. });
  18662. Scene.prototype._disableAudio = function () {
  18663. var i;
  18664. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18665. this.mainSoundTrack.soundCollection[i].pause();
  18666. }
  18667. for (i = 0; i < this.soundTracks.length; i++) {
  18668. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18669. this.soundTracks[i].soundCollection[j].pause();
  18670. }
  18671. }
  18672. };
  18673. Scene.prototype._enableAudio = function () {
  18674. var i;
  18675. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18676. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18677. this.mainSoundTrack.soundCollection[i].play();
  18678. }
  18679. }
  18680. for (i = 0; i < this.soundTracks.length; i++) {
  18681. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18682. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18683. this.soundTracks[i].soundCollection[j].play();
  18684. }
  18685. }
  18686. }
  18687. };
  18688. Object.defineProperty(Scene.prototype, "headphone", {
  18689. get: function () {
  18690. return this._headphone;
  18691. },
  18692. set: function (value) {
  18693. this._headphone = value;
  18694. if (BABYLON.AudioEngine) {
  18695. if (this._headphone) {
  18696. this._switchAudioModeForHeadphones();
  18697. }
  18698. else {
  18699. this._switchAudioModeForNormalSpeakers();
  18700. }
  18701. }
  18702. },
  18703. enumerable: true,
  18704. configurable: true
  18705. });
  18706. Scene.prototype._switchAudioModeForHeadphones = function () {
  18707. this.mainSoundTrack.switchPanningModelToHRTF();
  18708. for (var i = 0; i < this.soundTracks.length; i++) {
  18709. this.soundTracks[i].switchPanningModelToHRTF();
  18710. }
  18711. };
  18712. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18713. this.mainSoundTrack.switchPanningModelToEqualPower();
  18714. for (var i = 0; i < this.soundTracks.length; i++) {
  18715. this.soundTracks[i].switchPanningModelToEqualPower();
  18716. }
  18717. };
  18718. Scene.prototype.enableDepthRenderer = function () {
  18719. if (this._depthRenderer) {
  18720. return this._depthRenderer;
  18721. }
  18722. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18723. return this._depthRenderer;
  18724. };
  18725. Scene.prototype.disableDepthRenderer = function () {
  18726. if (!this._depthRenderer) {
  18727. return;
  18728. }
  18729. this._depthRenderer.dispose();
  18730. this._depthRenderer = null;
  18731. };
  18732. Scene.prototype.freezeMaterials = function () {
  18733. for (var i = 0; i < this.materials.length; i++) {
  18734. this.materials[i].freeze();
  18735. }
  18736. };
  18737. Scene.prototype.unfreezeMaterials = function () {
  18738. for (var i = 0; i < this.materials.length; i++) {
  18739. this.materials[i].unfreeze();
  18740. }
  18741. };
  18742. Scene.prototype.dispose = function () {
  18743. this.beforeRender = null;
  18744. this.afterRender = null;
  18745. this.skeletons = [];
  18746. this._boundingBoxRenderer.dispose();
  18747. if (this._depthRenderer) {
  18748. this._depthRenderer.dispose();
  18749. }
  18750. // Debug layer
  18751. if (this._debugLayer) {
  18752. this._debugLayer.hide();
  18753. }
  18754. // Events
  18755. this.onDisposeObservable.notifyObservers(this);
  18756. this.onDisposeObservable.clear();
  18757. this.onBeforeRenderObservable.clear();
  18758. this.onAfterRenderObservable.clear();
  18759. this.detachControl();
  18760. // Release sounds & sounds tracks
  18761. if (BABYLON.AudioEngine) {
  18762. this.disposeSounds();
  18763. }
  18764. // Detach cameras
  18765. var canvas = this._engine.getRenderingCanvas();
  18766. var index;
  18767. for (index = 0; index < this.cameras.length; index++) {
  18768. this.cameras[index].detachControl(canvas);
  18769. }
  18770. // Release lights
  18771. while (this.lights.length) {
  18772. this.lights[0].dispose();
  18773. }
  18774. // Release meshes
  18775. while (this.meshes.length) {
  18776. this.meshes[0].dispose(true);
  18777. }
  18778. // Release cameras
  18779. while (this.cameras.length) {
  18780. this.cameras[0].dispose();
  18781. }
  18782. // Release materials
  18783. while (this.materials.length) {
  18784. this.materials[0].dispose();
  18785. }
  18786. // Release particles
  18787. while (this.particleSystems.length) {
  18788. this.particleSystems[0].dispose();
  18789. }
  18790. // Release sprites
  18791. while (this.spriteManagers.length) {
  18792. this.spriteManagers[0].dispose();
  18793. }
  18794. // Release layers
  18795. while (this.layers.length) {
  18796. this.layers[0].dispose();
  18797. }
  18798. while (this.highlightLayers.length) {
  18799. this.highlightLayers[0].dispose();
  18800. }
  18801. // Release textures
  18802. while (this.textures.length) {
  18803. this.textures[0].dispose();
  18804. }
  18805. // Post-processes
  18806. this.postProcessManager.dispose();
  18807. // Physics
  18808. if (this._physicsEngine) {
  18809. this.disablePhysicsEngine();
  18810. }
  18811. // Remove from engine
  18812. index = this._engine.scenes.indexOf(this);
  18813. if (index > -1) {
  18814. this._engine.scenes.splice(index, 1);
  18815. }
  18816. this._engine.wipeCaches();
  18817. };
  18818. // Release sounds & sounds tracks
  18819. Scene.prototype.disposeSounds = function () {
  18820. this.mainSoundTrack.dispose();
  18821. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  18822. this.soundTracks[scIndex].dispose();
  18823. }
  18824. };
  18825. // Octrees
  18826. Scene.prototype.getWorldExtends = function () {
  18827. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  18828. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  18829. for (var index = 0; index < this.meshes.length; index++) {
  18830. var mesh = this.meshes[index];
  18831. mesh.computeWorldMatrix(true);
  18832. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  18833. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  18834. BABYLON.Tools.CheckExtends(minBox, min, max);
  18835. BABYLON.Tools.CheckExtends(maxBox, min, max);
  18836. }
  18837. return {
  18838. min: min,
  18839. max: max
  18840. };
  18841. };
  18842. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  18843. if (maxCapacity === void 0) { maxCapacity = 64; }
  18844. if (maxDepth === void 0) { maxDepth = 2; }
  18845. if (!this._selectionOctree) {
  18846. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  18847. }
  18848. var worldExtends = this.getWorldExtends();
  18849. // Update octree
  18850. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  18851. return this._selectionOctree;
  18852. };
  18853. // Picking
  18854. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  18855. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  18856. var engine = this._engine;
  18857. if (!camera) {
  18858. if (!this.activeCamera)
  18859. throw new Error("Active camera not set");
  18860. camera = this.activeCamera;
  18861. }
  18862. var cameraViewport = camera.viewport;
  18863. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18864. // Moving coordinates to local viewport world
  18865. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18866. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18867. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  18868. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  18869. };
  18870. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  18871. var engine = this._engine;
  18872. if (!camera) {
  18873. if (!this.activeCamera)
  18874. throw new Error("Active camera not set");
  18875. camera = this.activeCamera;
  18876. }
  18877. var cameraViewport = camera.viewport;
  18878. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  18879. var identity = BABYLON.Matrix.Identity();
  18880. // Moving coordinates to local viewport world
  18881. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  18882. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  18883. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  18884. };
  18885. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  18886. var pickingInfo = null;
  18887. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18888. var mesh = this.meshes[meshIndex];
  18889. if (predicate) {
  18890. if (!predicate(mesh)) {
  18891. continue;
  18892. }
  18893. }
  18894. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18895. continue;
  18896. }
  18897. var world = mesh.getWorldMatrix();
  18898. var ray = rayFunction(world);
  18899. var result = mesh.intersects(ray, fastCheck);
  18900. if (!result || !result.hit)
  18901. continue;
  18902. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18903. continue;
  18904. pickingInfo = result;
  18905. if (fastCheck) {
  18906. break;
  18907. }
  18908. }
  18909. return pickingInfo || new BABYLON.PickingInfo();
  18910. };
  18911. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  18912. var pickingInfos = new Array();
  18913. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  18914. var mesh = this.meshes[meshIndex];
  18915. if (predicate) {
  18916. if (!predicate(mesh)) {
  18917. continue;
  18918. }
  18919. }
  18920. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  18921. continue;
  18922. }
  18923. var world = mesh.getWorldMatrix();
  18924. var ray = rayFunction(world);
  18925. var result = mesh.intersects(ray, false);
  18926. if (!result || !result.hit)
  18927. continue;
  18928. pickingInfos.push(result);
  18929. }
  18930. return pickingInfos;
  18931. };
  18932. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  18933. var pickingInfo = null;
  18934. camera = camera || this.activeCamera;
  18935. if (this.spriteManagers.length > 0) {
  18936. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  18937. var spriteManager = this.spriteManagers[spriteIndex];
  18938. if (!spriteManager.isPickable) {
  18939. continue;
  18940. }
  18941. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  18942. if (!result || !result.hit)
  18943. continue;
  18944. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  18945. continue;
  18946. pickingInfo = result;
  18947. if (fastCheck) {
  18948. break;
  18949. }
  18950. }
  18951. }
  18952. return pickingInfo || new BABYLON.PickingInfo();
  18953. };
  18954. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18955. /// <param name="x">X position on screen</param>
  18956. /// <param name="y">Y position on screen</param>
  18957. /// <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>
  18958. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18959. /// <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>
  18960. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  18961. var _this = this;
  18962. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  18963. };
  18964. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18965. /// <param name="x">X position on screen</param>
  18966. /// <param name="y">Y position on screen</param>
  18967. /// <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>
  18968. /// <param name="fastCheck">Launch a fast check only using the bounding boxes. Can be set to null.</param>
  18969. /// <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>
  18970. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  18971. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  18972. };
  18973. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  18974. var _this = this;
  18975. return this._internalPick(function (world) {
  18976. if (!_this._pickWithRayInverseMatrix) {
  18977. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  18978. }
  18979. world.invertToRef(_this._pickWithRayInverseMatrix);
  18980. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  18981. }, predicate, fastCheck);
  18982. };
  18983. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18984. /// <param name="x">X position on screen</param>
  18985. /// <param name="y">Y position on screen</param>
  18986. /// <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>
  18987. /// <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>
  18988. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  18989. var _this = this;
  18990. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  18991. };
  18992. /// <summary>Launch a ray to try to pick a mesh in the scene</summary>
  18993. /// <param name="ray">Ray to use</param>
  18994. /// <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>
  18995. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  18996. var _this = this;
  18997. return this._internalMultiPick(function (world) {
  18998. if (!_this._pickWithRayInverseMatrix) {
  18999. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19000. }
  19001. world.invertToRef(_this._pickWithRayInverseMatrix);
  19002. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19003. }, predicate);
  19004. };
  19005. Scene.prototype.setPointerOverMesh = function (mesh) {
  19006. if (this._pointerOverMesh === mesh) {
  19007. return;
  19008. }
  19009. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19010. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19011. }
  19012. this._pointerOverMesh = mesh;
  19013. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19014. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19015. }
  19016. };
  19017. Scene.prototype.getPointerOverMesh = function () {
  19018. return this._pointerOverMesh;
  19019. };
  19020. Scene.prototype.setPointerOverSprite = function (sprite) {
  19021. if (this._pointerOverSprite === sprite) {
  19022. return;
  19023. }
  19024. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19025. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19026. }
  19027. this._pointerOverSprite = sprite;
  19028. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19029. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19030. }
  19031. };
  19032. Scene.prototype.getPointerOverSprite = function () {
  19033. return this._pointerOverSprite;
  19034. };
  19035. // Physics
  19036. Scene.prototype.getPhysicsEngine = function () {
  19037. return this._physicsEngine;
  19038. };
  19039. /**
  19040. * Enables physics to the current scene
  19041. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19042. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19043. * @return {boolean} was the physics engine initialized
  19044. */
  19045. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19046. if (this._physicsEngine) {
  19047. return true;
  19048. }
  19049. try {
  19050. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19051. return true;
  19052. }
  19053. catch (e) {
  19054. BABYLON.Tools.Error(e.message);
  19055. return false;
  19056. }
  19057. };
  19058. Scene.prototype.disablePhysicsEngine = function () {
  19059. if (!this._physicsEngine) {
  19060. return;
  19061. }
  19062. this._physicsEngine.dispose();
  19063. this._physicsEngine = undefined;
  19064. };
  19065. Scene.prototype.isPhysicsEnabled = function () {
  19066. return this._physicsEngine !== undefined;
  19067. };
  19068. /**
  19069. *
  19070. * Sets the gravity of the physics engine (and NOT of the scene)
  19071. * @param {BABYLON.Vector3} [gravity] - the new gravity to be used
  19072. */
  19073. Scene.prototype.setGravity = function (gravity) {
  19074. BABYLON.Tools.Warn("Deprecated, please use 'scene.getPhysicsEngine().setGravity()'");
  19075. if (!this._physicsEngine) {
  19076. return;
  19077. }
  19078. this._physicsEngine.setGravity(gravity);
  19079. };
  19080. /**
  19081. * Legacy support, using the new API
  19082. * @Deprecated
  19083. */
  19084. Scene.prototype.createCompoundImpostor = function (parts, options) {
  19085. BABYLON.Tools.Warn("Scene.createCompoundImpostor is deprecated. Please use PhysicsImpostor parent/child");
  19086. if (parts.parts) {
  19087. options = parts;
  19088. parts = parts.parts;
  19089. }
  19090. var mainMesh = parts[0].mesh;
  19091. mainMesh.physicsImpostor = new BABYLON.PhysicsImpostor(mainMesh, parts[0].impostor, options, this);
  19092. for (var index = 1; index < parts.length; index++) {
  19093. var mesh = parts[index].mesh;
  19094. if (mesh.parent !== mainMesh) {
  19095. mesh.position = mesh.position.subtract(mainMesh.position);
  19096. mesh.parent = mainMesh;
  19097. }
  19098. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parts[index].impostor, options, this);
  19099. }
  19100. mainMesh.physicsImpostor.forceUpdate();
  19101. };
  19102. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19103. var mesh = compound.parts[0].mesh;
  19104. mesh.physicsImpostor.dispose();
  19105. mesh.physicsImpostor = null;
  19106. };
  19107. // Misc.
  19108. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera) {
  19109. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19110. // Light
  19111. if (this.lights.length === 0) {
  19112. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19113. }
  19114. // Camera
  19115. if (!this.activeCamera) {
  19116. // Compute position
  19117. var worldExtends = this.getWorldExtends();
  19118. var worldCenter = worldExtends.min.add(worldExtends.max.subtract(worldExtends.min).scale(0.5));
  19119. var camera;
  19120. if (createArcRotateCamera) {
  19121. camera = new BABYLON.ArcRotateCamera("default camera", 0, 0, 10, BABYLON.Vector3.Zero(), this);
  19122. camera.setPosition(new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z)));
  19123. camera.setTarget(worldCenter);
  19124. }
  19125. else {
  19126. camera = new BABYLON.FreeCamera("default camera", BABYLON.Vector3.Zero(), this);
  19127. camera.position = new BABYLON.Vector3(worldCenter.x, worldCenter.y, worldExtends.min.z - (worldExtends.max.z - worldExtends.min.z));
  19128. camera.setTarget(worldCenter);
  19129. }
  19130. this.activeCamera = camera;
  19131. }
  19132. };
  19133. // Tags
  19134. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19135. if (tagsQuery === undefined) {
  19136. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19137. return list;
  19138. }
  19139. var listByTags = [];
  19140. forEach = forEach || (function (item) { return; });
  19141. for (var i in list) {
  19142. var item = list[i];
  19143. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19144. listByTags.push(item);
  19145. forEach(item);
  19146. }
  19147. }
  19148. return listByTags;
  19149. };
  19150. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19151. return this._getByTags(this.meshes, tagsQuery, forEach);
  19152. };
  19153. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19154. return this._getByTags(this.cameras, tagsQuery, forEach);
  19155. };
  19156. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19157. return this._getByTags(this.lights, tagsQuery, forEach);
  19158. };
  19159. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19160. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19161. };
  19162. /**
  19163. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19164. * This allowed control for front to back rendering or reversly depending of the special needs.
  19165. *
  19166. * @param renderingGroupId The rendering group id corresponding to its index
  19167. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19168. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19169. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19170. */
  19171. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19172. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19173. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19174. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19175. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19176. };
  19177. /**
  19178. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19179. *
  19180. * @param renderingGroupId The rendering group id corresponding to its index
  19181. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19182. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19183. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19184. */
  19185. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19186. if (depth === void 0) { depth = true; }
  19187. if (stencil === void 0) { stencil = true; }
  19188. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19189. };
  19190. return Scene;
  19191. }());
  19192. // Statics
  19193. Scene._FOGMODE_NONE = 0;
  19194. Scene._FOGMODE_EXP = 1;
  19195. Scene._FOGMODE_EXP2 = 2;
  19196. Scene._FOGMODE_LINEAR = 3;
  19197. Scene.MinDeltaTime = 1.0;
  19198. Scene.MaxDeltaTime = 1000.0;
  19199. BABYLON.Scene = Scene;
  19200. })(BABYLON || (BABYLON = {}));
  19201. //# sourceMappingURL=babylon.scene.js.map
  19202. var BABYLON;
  19203. (function (BABYLON) {
  19204. var Buffer = (function () {
  19205. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19206. if (engine instanceof BABYLON.Mesh) {
  19207. this._engine = engine.getScene().getEngine();
  19208. }
  19209. else {
  19210. this._engine = engine;
  19211. }
  19212. this._updatable = updatable;
  19213. this._data = data;
  19214. this._strideSize = stride;
  19215. if (!postponeInternalCreation) {
  19216. this.create();
  19217. }
  19218. this._instanced = instanced;
  19219. }
  19220. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19221. // a lot of these parameters are ignored as they are overriden by the buffer
  19222. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19223. };
  19224. // Properties
  19225. Buffer.prototype.isUpdatable = function () {
  19226. return this._updatable;
  19227. };
  19228. Buffer.prototype.getData = function () {
  19229. return this._data;
  19230. };
  19231. Buffer.prototype.getBuffer = function () {
  19232. return this._buffer;
  19233. };
  19234. Buffer.prototype.getStrideSize = function () {
  19235. return this._strideSize;
  19236. };
  19237. Buffer.prototype.getIsInstanced = function () {
  19238. return this._instanced;
  19239. };
  19240. // Methods
  19241. Buffer.prototype.create = function (data) {
  19242. if (!data && this._buffer) {
  19243. return; // nothing to do
  19244. }
  19245. data = data || this._data;
  19246. if (!this._buffer) {
  19247. if (this._updatable) {
  19248. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19249. this._data = data;
  19250. }
  19251. else {
  19252. this._buffer = this._engine.createVertexBuffer(data);
  19253. }
  19254. }
  19255. else if (this._updatable) {
  19256. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19257. this._data = data;
  19258. }
  19259. };
  19260. Buffer.prototype.update = function (data) {
  19261. this.create(data);
  19262. };
  19263. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19264. if (!this._buffer) {
  19265. return;
  19266. }
  19267. if (this._updatable) {
  19268. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19269. this._data = null;
  19270. }
  19271. };
  19272. Buffer.prototype.dispose = function () {
  19273. if (!this._buffer) {
  19274. return;
  19275. }
  19276. if (this._engine._releaseBuffer(this._buffer)) {
  19277. this._buffer = null;
  19278. }
  19279. };
  19280. return Buffer;
  19281. }());
  19282. BABYLON.Buffer = Buffer;
  19283. })(BABYLON || (BABYLON = {}));
  19284. //# sourceMappingURL=babylon.buffer.js.map
  19285. var BABYLON;
  19286. (function (BABYLON) {
  19287. var VertexBuffer = (function () {
  19288. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19289. if (!stride) {
  19290. // Deduce stride from kind
  19291. switch (kind) {
  19292. case VertexBuffer.PositionKind:
  19293. stride = 3;
  19294. break;
  19295. case VertexBuffer.NormalKind:
  19296. stride = 3;
  19297. break;
  19298. case VertexBuffer.UVKind:
  19299. case VertexBuffer.UV2Kind:
  19300. case VertexBuffer.UV3Kind:
  19301. case VertexBuffer.UV4Kind:
  19302. case VertexBuffer.UV5Kind:
  19303. case VertexBuffer.UV6Kind:
  19304. stride = 2;
  19305. break;
  19306. case VertexBuffer.ColorKind:
  19307. stride = 4;
  19308. break;
  19309. case VertexBuffer.MatricesIndicesKind:
  19310. case VertexBuffer.MatricesIndicesExtraKind:
  19311. stride = 4;
  19312. break;
  19313. case VertexBuffer.MatricesWeightsKind:
  19314. case VertexBuffer.MatricesWeightsExtraKind:
  19315. stride = 4;
  19316. break;
  19317. }
  19318. }
  19319. if (data instanceof BABYLON.Buffer) {
  19320. if (!stride) {
  19321. stride = data.getStrideSize();
  19322. }
  19323. this._buffer = data;
  19324. this._ownsBuffer = false;
  19325. }
  19326. else {
  19327. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19328. this._ownsBuffer = true;
  19329. }
  19330. this._stride = stride;
  19331. this._offset = offset ? offset : 0;
  19332. this._size = size ? size : stride;
  19333. this._kind = kind;
  19334. }
  19335. VertexBuffer.prototype.getKind = function () {
  19336. return this._kind;
  19337. };
  19338. // Properties
  19339. VertexBuffer.prototype.isUpdatable = function () {
  19340. return this._buffer.isUpdatable();
  19341. };
  19342. VertexBuffer.prototype.getData = function () {
  19343. return this._buffer.getData();
  19344. };
  19345. VertexBuffer.prototype.getBuffer = function () {
  19346. return this._buffer.getBuffer();
  19347. };
  19348. VertexBuffer.prototype.getStrideSize = function () {
  19349. return this._stride;
  19350. };
  19351. VertexBuffer.prototype.getOffset = function () {
  19352. return this._offset;
  19353. };
  19354. VertexBuffer.prototype.getSize = function () {
  19355. return this._size;
  19356. };
  19357. VertexBuffer.prototype.getIsInstanced = function () {
  19358. return this._buffer.getIsInstanced();
  19359. };
  19360. // Methods
  19361. VertexBuffer.prototype.create = function (data) {
  19362. return this._buffer.create(data);
  19363. };
  19364. VertexBuffer.prototype.update = function (data) {
  19365. return this._buffer.update(data);
  19366. };
  19367. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19368. return this._buffer.updateDirectly(data, offset);
  19369. };
  19370. VertexBuffer.prototype.dispose = function () {
  19371. if (this._ownsBuffer) {
  19372. this._buffer.dispose();
  19373. }
  19374. };
  19375. Object.defineProperty(VertexBuffer, "PositionKind", {
  19376. get: function () {
  19377. return VertexBuffer._PositionKind;
  19378. },
  19379. enumerable: true,
  19380. configurable: true
  19381. });
  19382. Object.defineProperty(VertexBuffer, "NormalKind", {
  19383. get: function () {
  19384. return VertexBuffer._NormalKind;
  19385. },
  19386. enumerable: true,
  19387. configurable: true
  19388. });
  19389. Object.defineProperty(VertexBuffer, "UVKind", {
  19390. get: function () {
  19391. return VertexBuffer._UVKind;
  19392. },
  19393. enumerable: true,
  19394. configurable: true
  19395. });
  19396. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19397. get: function () {
  19398. return VertexBuffer._UV2Kind;
  19399. },
  19400. enumerable: true,
  19401. configurable: true
  19402. });
  19403. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19404. get: function () {
  19405. return VertexBuffer._UV3Kind;
  19406. },
  19407. enumerable: true,
  19408. configurable: true
  19409. });
  19410. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19411. get: function () {
  19412. return VertexBuffer._UV4Kind;
  19413. },
  19414. enumerable: true,
  19415. configurable: true
  19416. });
  19417. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19418. get: function () {
  19419. return VertexBuffer._UV5Kind;
  19420. },
  19421. enumerable: true,
  19422. configurable: true
  19423. });
  19424. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19425. get: function () {
  19426. return VertexBuffer._UV6Kind;
  19427. },
  19428. enumerable: true,
  19429. configurable: true
  19430. });
  19431. Object.defineProperty(VertexBuffer, "ColorKind", {
  19432. get: function () {
  19433. return VertexBuffer._ColorKind;
  19434. },
  19435. enumerable: true,
  19436. configurable: true
  19437. });
  19438. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19439. get: function () {
  19440. return VertexBuffer._MatricesIndicesKind;
  19441. },
  19442. enumerable: true,
  19443. configurable: true
  19444. });
  19445. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19446. get: function () {
  19447. return VertexBuffer._MatricesWeightsKind;
  19448. },
  19449. enumerable: true,
  19450. configurable: true
  19451. });
  19452. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19453. get: function () {
  19454. return VertexBuffer._MatricesIndicesExtraKind;
  19455. },
  19456. enumerable: true,
  19457. configurable: true
  19458. });
  19459. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19460. get: function () {
  19461. return VertexBuffer._MatricesWeightsExtraKind;
  19462. },
  19463. enumerable: true,
  19464. configurable: true
  19465. });
  19466. return VertexBuffer;
  19467. }());
  19468. // Enums
  19469. VertexBuffer._PositionKind = "position";
  19470. VertexBuffer._NormalKind = "normal";
  19471. VertexBuffer._UVKind = "uv";
  19472. VertexBuffer._UV2Kind = "uv2";
  19473. VertexBuffer._UV3Kind = "uv3";
  19474. VertexBuffer._UV4Kind = "uv4";
  19475. VertexBuffer._UV5Kind = "uv5";
  19476. VertexBuffer._UV6Kind = "uv6";
  19477. VertexBuffer._ColorKind = "color";
  19478. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19479. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19480. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19481. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19482. BABYLON.VertexBuffer = VertexBuffer;
  19483. })(BABYLON || (BABYLON = {}));
  19484. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19485. var BABYLON;
  19486. (function (BABYLON) {
  19487. /**
  19488. * Creates an instance based on a source mesh.
  19489. */
  19490. var InstancedMesh = (function (_super) {
  19491. __extends(InstancedMesh, _super);
  19492. function InstancedMesh(name, source) {
  19493. var _this = _super.call(this, name, source.getScene()) || this;
  19494. source.instances.push(_this);
  19495. _this._sourceMesh = source;
  19496. _this.position.copyFrom(source.position);
  19497. _this.rotation.copyFrom(source.rotation);
  19498. _this.scaling.copyFrom(source.scaling);
  19499. if (source.rotationQuaternion) {
  19500. _this.rotationQuaternion = source.rotationQuaternion.clone();
  19501. }
  19502. _this.infiniteDistance = source.infiniteDistance;
  19503. _this.setPivotMatrix(source.getPivotMatrix());
  19504. _this.refreshBoundingInfo();
  19505. _this._syncSubMeshes();
  19506. return _this;
  19507. }
  19508. InstancedMesh.prototype.getClassName = function () {
  19509. return "InstancedMesh";
  19510. };
  19511. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  19512. // Methods
  19513. get: function () {
  19514. return this._sourceMesh.receiveShadows;
  19515. },
  19516. enumerable: true,
  19517. configurable: true
  19518. });
  19519. Object.defineProperty(InstancedMesh.prototype, "material", {
  19520. get: function () {
  19521. return this._sourceMesh.material;
  19522. },
  19523. enumerable: true,
  19524. configurable: true
  19525. });
  19526. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  19527. get: function () {
  19528. return this._sourceMesh.visibility;
  19529. },
  19530. enumerable: true,
  19531. configurable: true
  19532. });
  19533. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  19534. get: function () {
  19535. return this._sourceMesh.skeleton;
  19536. },
  19537. enumerable: true,
  19538. configurable: true
  19539. });
  19540. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  19541. get: function () {
  19542. return this._sourceMesh.renderingGroupId;
  19543. },
  19544. enumerable: true,
  19545. configurable: true
  19546. });
  19547. InstancedMesh.prototype.getTotalVertices = function () {
  19548. return this._sourceMesh.getTotalVertices();
  19549. };
  19550. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  19551. get: function () {
  19552. return this._sourceMesh;
  19553. },
  19554. enumerable: true,
  19555. configurable: true
  19556. });
  19557. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19558. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  19559. };
  19560. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  19561. return this._sourceMesh.isVerticesDataPresent(kind);
  19562. };
  19563. InstancedMesh.prototype.getIndices = function () {
  19564. return this._sourceMesh.getIndices();
  19565. };
  19566. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  19567. get: function () {
  19568. return this._sourceMesh._positions;
  19569. },
  19570. enumerable: true,
  19571. configurable: true
  19572. });
  19573. InstancedMesh.prototype.refreshBoundingInfo = function () {
  19574. var meshBB = this._sourceMesh.getBoundingInfo();
  19575. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  19576. this._updateBoundingInfo();
  19577. };
  19578. InstancedMesh.prototype._preActivate = function () {
  19579. if (this._currentLOD) {
  19580. this._currentLOD._preActivate();
  19581. }
  19582. };
  19583. InstancedMesh.prototype._activate = function (renderId) {
  19584. if (this._currentLOD) {
  19585. this._currentLOD._registerInstanceForRenderId(this, renderId);
  19586. }
  19587. };
  19588. InstancedMesh.prototype.getLOD = function (camera) {
  19589. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  19590. if (this._currentLOD === this.sourceMesh) {
  19591. return this;
  19592. }
  19593. return this._currentLOD;
  19594. };
  19595. InstancedMesh.prototype._syncSubMeshes = function () {
  19596. this.releaseSubMeshes();
  19597. if (this._sourceMesh.subMeshes) {
  19598. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  19599. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  19600. }
  19601. }
  19602. };
  19603. InstancedMesh.prototype._generatePointsArray = function () {
  19604. return this._sourceMesh._generatePointsArray();
  19605. };
  19606. // Clone
  19607. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19608. var result = this._sourceMesh.createInstance(name);
  19609. // Deep copy
  19610. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes"], []);
  19611. // Bounding info
  19612. this.refreshBoundingInfo();
  19613. // Parent
  19614. if (newParent) {
  19615. result.parent = newParent;
  19616. }
  19617. if (!doNotCloneChildren) {
  19618. // Children
  19619. for (var index = 0; index < this.getScene().meshes.length; index++) {
  19620. var mesh = this.getScene().meshes[index];
  19621. if (mesh.parent === this) {
  19622. mesh.clone(mesh.name, result);
  19623. }
  19624. }
  19625. }
  19626. result.computeWorldMatrix(true);
  19627. return result;
  19628. };
  19629. // Dispoe
  19630. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  19631. // Remove from mesh
  19632. var index = this._sourceMesh.instances.indexOf(this);
  19633. this._sourceMesh.instances.splice(index, 1);
  19634. _super.prototype.dispose.call(this, doNotRecurse);
  19635. };
  19636. return InstancedMesh;
  19637. }(BABYLON.AbstractMesh));
  19638. BABYLON.InstancedMesh = InstancedMesh;
  19639. })(BABYLON || (BABYLON = {}));
  19640. //# sourceMappingURL=babylon.instancedMesh.js.map
  19641. var BABYLON;
  19642. (function (BABYLON) {
  19643. var _InstancesBatch = (function () {
  19644. function _InstancesBatch() {
  19645. this.mustReturn = false;
  19646. this.visibleInstances = new Array();
  19647. this.renderSelf = new Array();
  19648. }
  19649. return _InstancesBatch;
  19650. }());
  19651. BABYLON._InstancesBatch = _InstancesBatch;
  19652. var Mesh = (function (_super) {
  19653. __extends(Mesh, _super);
  19654. /**
  19655. * @constructor
  19656. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  19657. * @param {Scene} scene The scene to add this mesh to.
  19658. * @param {Node} parent The parent of this mesh, if it has one
  19659. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  19660. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  19661. * When false, achieved by calling a clone(), also passing False.
  19662. * This will make creation of children, recursive.
  19663. */
  19664. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  19665. if (parent === void 0) { parent = null; }
  19666. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  19667. var _this = _super.call(this, name, scene) || this;
  19668. // Events
  19669. /**
  19670. * An event triggered before rendering the mesh
  19671. * @type {BABYLON.Observable}
  19672. */
  19673. _this.onBeforeRenderObservable = new BABYLON.Observable();
  19674. /**
  19675. * An event triggered after rendering the mesh
  19676. * @type {BABYLON.Observable}
  19677. */
  19678. _this.onAfterRenderObservable = new BABYLON.Observable();
  19679. /**
  19680. * An event triggered before drawing the mesh
  19681. * @type {BABYLON.Observable}
  19682. */
  19683. _this.onBeforeDrawObservable = new BABYLON.Observable();
  19684. // Members
  19685. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  19686. _this.instances = new Array();
  19687. _this._LODLevels = new Array();
  19688. _this._visibleInstances = {};
  19689. _this._renderIdForInstances = new Array();
  19690. _this._batchCache = new _InstancesBatch();
  19691. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  19692. _this._sideOrientation = Mesh._DEFAULTSIDE;
  19693. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  19694. if (source) {
  19695. // Geometry
  19696. if (source._geometry) {
  19697. source._geometry.applyToMesh(_this);
  19698. }
  19699. // Deep copy
  19700. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent"], ["_poseMatrix"]);
  19701. // Parent
  19702. _this.parent = source.parent;
  19703. // Pivot
  19704. _this.setPivotMatrix(source.getPivotMatrix());
  19705. _this.id = name + "." + source.id;
  19706. // Material
  19707. _this.material = source.material;
  19708. var index;
  19709. if (!doNotCloneChildren) {
  19710. // Children
  19711. for (index = 0; index < scene.meshes.length; index++) {
  19712. var mesh = scene.meshes[index];
  19713. if (mesh.parent === source) {
  19714. // doNotCloneChildren is always going to be False
  19715. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  19716. }
  19717. }
  19718. }
  19719. // Physics clone
  19720. var physicsEngine = _this.getScene().getPhysicsEngine();
  19721. if (clonePhysicsImpostor && physicsEngine) {
  19722. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  19723. if (impostor) {
  19724. _this.physicsImpostor = impostor.clone(_this);
  19725. }
  19726. }
  19727. // Particles
  19728. for (index = 0; index < scene.particleSystems.length; index++) {
  19729. var system = scene.particleSystems[index];
  19730. if (system.emitter === source) {
  19731. system.clone(system.name, _this);
  19732. }
  19733. }
  19734. _this.computeWorldMatrix(true);
  19735. }
  19736. // Parent
  19737. if (parent !== null) {
  19738. _this.parent = parent;
  19739. }
  19740. return _this;
  19741. }
  19742. Object.defineProperty(Mesh, "FRONTSIDE", {
  19743. /**
  19744. * Mesh side orientation : usually the external or front surface
  19745. */
  19746. get: function () {
  19747. return Mesh._FRONTSIDE;
  19748. },
  19749. enumerable: true,
  19750. configurable: true
  19751. });
  19752. Object.defineProperty(Mesh, "BACKSIDE", {
  19753. /**
  19754. * Mesh side orientation : usually the internal or back surface
  19755. */
  19756. get: function () {
  19757. return Mesh._BACKSIDE;
  19758. },
  19759. enumerable: true,
  19760. configurable: true
  19761. });
  19762. Object.defineProperty(Mesh, "DOUBLESIDE", {
  19763. /**
  19764. * Mesh side orientation : both internal and external or front and back surfaces
  19765. */
  19766. get: function () {
  19767. return Mesh._DOUBLESIDE;
  19768. },
  19769. enumerable: true,
  19770. configurable: true
  19771. });
  19772. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  19773. /**
  19774. * Mesh side orientation : by default, `FRONTSIDE`
  19775. */
  19776. get: function () {
  19777. return Mesh._DEFAULTSIDE;
  19778. },
  19779. enumerable: true,
  19780. configurable: true
  19781. });
  19782. Object.defineProperty(Mesh, "NO_CAP", {
  19783. /**
  19784. * Mesh cap setting : no cap
  19785. */
  19786. get: function () {
  19787. return Mesh._NO_CAP;
  19788. },
  19789. enumerable: true,
  19790. configurable: true
  19791. });
  19792. Object.defineProperty(Mesh, "CAP_START", {
  19793. /**
  19794. * Mesh cap setting : one cap at the beginning of the mesh
  19795. */
  19796. get: function () {
  19797. return Mesh._CAP_START;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(Mesh, "CAP_END", {
  19803. /**
  19804. * Mesh cap setting : one cap at the end of the mesh
  19805. */
  19806. get: function () {
  19807. return Mesh._CAP_END;
  19808. },
  19809. enumerable: true,
  19810. configurable: true
  19811. });
  19812. Object.defineProperty(Mesh, "CAP_ALL", {
  19813. /**
  19814. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  19815. */
  19816. get: function () {
  19817. return Mesh._CAP_ALL;
  19818. },
  19819. enumerable: true,
  19820. configurable: true
  19821. });
  19822. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  19823. set: function (callback) {
  19824. if (this._onBeforeDrawObserver) {
  19825. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  19826. }
  19827. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  19828. },
  19829. enumerable: true,
  19830. configurable: true
  19831. });
  19832. // Methods
  19833. Mesh.prototype.getClassName = function () {
  19834. return "Mesh";
  19835. };
  19836. /**
  19837. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  19838. */
  19839. Mesh.prototype.toString = function (fullDetails) {
  19840. var ret = _super.prototype.toString.call(this, fullDetails);
  19841. ret += ", n vertices: " + this.getTotalVertices();
  19842. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  19843. if (this.animations) {
  19844. for (var i = 0; i < this.animations.length; i++) {
  19845. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  19846. }
  19847. }
  19848. if (fullDetails) {
  19849. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  19850. }
  19851. return ret;
  19852. };
  19853. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  19854. get: function () {
  19855. return this._LODLevels.length > 0;
  19856. },
  19857. enumerable: true,
  19858. configurable: true
  19859. });
  19860. Mesh.prototype._sortLODLevels = function () {
  19861. this._LODLevels.sort(function (a, b) {
  19862. if (a.distance < b.distance) {
  19863. return 1;
  19864. }
  19865. if (a.distance > b.distance) {
  19866. return -1;
  19867. }
  19868. return 0;
  19869. });
  19870. };
  19871. /**
  19872. * Add a mesh as LOD level triggered at the given distance.
  19873. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19874. * @param {number} distance The distance from the center of the object to show this level
  19875. * @param {Mesh} mesh The mesh to be added as LOD level
  19876. * @return {Mesh} This mesh (for chaining)
  19877. */
  19878. Mesh.prototype.addLODLevel = function (distance, mesh) {
  19879. if (mesh && mesh._masterMesh) {
  19880. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  19881. return this;
  19882. }
  19883. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  19884. this._LODLevels.push(level);
  19885. if (mesh) {
  19886. mesh._masterMesh = this;
  19887. }
  19888. this._sortLODLevels();
  19889. return this;
  19890. };
  19891. /**
  19892. * Returns the LOD level mesh at the passed distance or null if not found.
  19893. * It is related to the method `addLODLevel(distance, mesh)`.
  19894. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19895. */
  19896. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  19897. for (var index = 0; index < this._LODLevels.length; index++) {
  19898. var level = this._LODLevels[index];
  19899. if (level.distance === distance) {
  19900. return level.mesh;
  19901. }
  19902. }
  19903. return null;
  19904. };
  19905. /**
  19906. * Remove a mesh from the LOD array
  19907. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19908. * @param {Mesh} mesh The mesh to be removed.
  19909. * @return {Mesh} This mesh (for chaining)
  19910. */
  19911. Mesh.prototype.removeLODLevel = function (mesh) {
  19912. for (var index = 0; index < this._LODLevels.length; index++) {
  19913. if (this._LODLevels[index].mesh === mesh) {
  19914. this._LODLevels.splice(index, 1);
  19915. if (mesh) {
  19916. mesh._masterMesh = null;
  19917. }
  19918. }
  19919. }
  19920. this._sortLODLevels();
  19921. return this;
  19922. };
  19923. /**
  19924. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  19925. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  19926. */
  19927. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  19928. if (!this._LODLevels || this._LODLevels.length === 0) {
  19929. return this;
  19930. }
  19931. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  19932. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  19933. if (this.onLODLevelSelection) {
  19934. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  19935. }
  19936. return this;
  19937. }
  19938. for (var index = 0; index < this._LODLevels.length; index++) {
  19939. var level = this._LODLevels[index];
  19940. if (level.distance < distanceToCamera) {
  19941. if (level.mesh) {
  19942. level.mesh._preActivate();
  19943. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  19944. }
  19945. if (this.onLODLevelSelection) {
  19946. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  19947. }
  19948. return level.mesh;
  19949. }
  19950. }
  19951. if (this.onLODLevelSelection) {
  19952. this.onLODLevelSelection(distanceToCamera, this, this);
  19953. }
  19954. return this;
  19955. };
  19956. Object.defineProperty(Mesh.prototype, "geometry", {
  19957. /**
  19958. * Returns the mesh internal Geometry object.
  19959. */
  19960. get: function () {
  19961. return this._geometry;
  19962. },
  19963. enumerable: true,
  19964. configurable: true
  19965. });
  19966. /**
  19967. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  19968. */
  19969. Mesh.prototype.getTotalVertices = function () {
  19970. if (!this._geometry) {
  19971. return 0;
  19972. }
  19973. return this._geometry.getTotalVertices();
  19974. };
  19975. /**
  19976. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  19977. * If `copywhenShared` is true (default false) and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  19978. * Returns null if the mesh has no geometry or no vertex buffer.
  19979. * Possible `kind` values :
  19980. * - BABYLON.VertexBuffer.PositionKind
  19981. * - BABYLON.VertexBuffer.UVKind
  19982. * - BABYLON.VertexBuffer.UV2Kind
  19983. * - BABYLON.VertexBuffer.UV3Kind
  19984. * - BABYLON.VertexBuffer.UV4Kind
  19985. * - BABYLON.VertexBuffer.UV5Kind
  19986. * - BABYLON.VertexBuffer.UV6Kind
  19987. * - BABYLON.VertexBuffer.ColorKind
  19988. * - BABYLON.VertexBuffer.MatricesIndicesKind
  19989. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  19990. * - BABYLON.VertexBuffer.MatricesWeightsKind
  19991. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  19992. */
  19993. Mesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  19994. if (!this._geometry) {
  19995. return null;
  19996. }
  19997. return this._geometry.getVerticesData(kind, copyWhenShared);
  19998. };
  19999. /**
  20000. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  20001. * Returns `undefined` if the mesh has no geometry.
  20002. * Possible `kind` values :
  20003. * - BABYLON.VertexBuffer.PositionKind
  20004. * - BABYLON.VertexBuffer.UVKind
  20005. * - BABYLON.VertexBuffer.UV2Kind
  20006. * - BABYLON.VertexBuffer.UV3Kind
  20007. * - BABYLON.VertexBuffer.UV4Kind
  20008. * - BABYLON.VertexBuffer.UV5Kind
  20009. * - BABYLON.VertexBuffer.UV6Kind
  20010. * - BABYLON.VertexBuffer.ColorKind
  20011. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20012. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20013. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20014. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20015. */
  20016. Mesh.prototype.getVertexBuffer = function (kind) {
  20017. if (!this._geometry) {
  20018. return undefined;
  20019. }
  20020. return this._geometry.getVertexBuffer(kind);
  20021. };
  20022. /**
  20023. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  20024. * Possible `kind` values :
  20025. * - BABYLON.VertexBuffer.PositionKind
  20026. * - BABYLON.VertexBuffer.UVKind
  20027. * - BABYLON.VertexBuffer.UV2Kind
  20028. * - BABYLON.VertexBuffer.UV3Kind
  20029. * - BABYLON.VertexBuffer.UV4Kind
  20030. * - BABYLON.VertexBuffer.UV5Kind
  20031. * - BABYLON.VertexBuffer.UV6Kind
  20032. * - BABYLON.VertexBuffer.ColorKind
  20033. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20034. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20035. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20036. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20037. */
  20038. Mesh.prototype.isVerticesDataPresent = function (kind) {
  20039. if (!this._geometry) {
  20040. if (this._delayInfo) {
  20041. return this._delayInfo.indexOf(kind) !== -1;
  20042. }
  20043. return false;
  20044. }
  20045. return this._geometry.isVerticesDataPresent(kind);
  20046. };
  20047. /**
  20048. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  20049. * Possible `kind` values :
  20050. * - BABYLON.VertexBuffer.PositionKind
  20051. * - BABYLON.VertexBuffer.UVKind
  20052. * - BABYLON.VertexBuffer.UV2Kind
  20053. * - BABYLON.VertexBuffer.UV3Kind
  20054. * - BABYLON.VertexBuffer.UV4Kind
  20055. * - BABYLON.VertexBuffer.UV5Kind
  20056. * - BABYLON.VertexBuffer.UV6Kind
  20057. * - BABYLON.VertexBuffer.ColorKind
  20058. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20059. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20060. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20061. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20062. */
  20063. Mesh.prototype.getVerticesDataKinds = function () {
  20064. if (!this._geometry) {
  20065. var result = [];
  20066. if (this._delayInfo) {
  20067. this._delayInfo.forEach(function (kind, index, array) {
  20068. result.push(kind);
  20069. });
  20070. }
  20071. return result;
  20072. }
  20073. return this._geometry.getVerticesDataKinds();
  20074. };
  20075. /**
  20076. * Returns a positive integer : the total number of indices in this mesh geometry.
  20077. * Returns zero if the mesh has no geometry.
  20078. */
  20079. Mesh.prototype.getTotalIndices = function () {
  20080. if (!this._geometry) {
  20081. return 0;
  20082. }
  20083. return this._geometry.getTotalIndices();
  20084. };
  20085. /**
  20086. * Returns an array of integers or a Int32Array populated with the mesh indices.
  20087. * If the parameter `copyWhenShared` is true (default false) and and if the mesh geometry is shared among some other meshes, the returned array is a copy of the internal one.
  20088. * Returns an empty array if the mesh has no geometry.
  20089. */
  20090. Mesh.prototype.getIndices = function (copyWhenShared) {
  20091. if (!this._geometry) {
  20092. return [];
  20093. }
  20094. return this._geometry.getIndices(copyWhenShared);
  20095. };
  20096. Object.defineProperty(Mesh.prototype, "isBlocked", {
  20097. get: function () {
  20098. return this._masterMesh !== null && this._masterMesh !== undefined;
  20099. },
  20100. enumerable: true,
  20101. configurable: true
  20102. });
  20103. /**
  20104. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  20105. */
  20106. Mesh.prototype.isReady = function () {
  20107. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20108. return false;
  20109. }
  20110. return _super.prototype.isReady.call(this);
  20111. };
  20112. /**
  20113. * Boolean : true if the mesh has been disposed.
  20114. */
  20115. Mesh.prototype.isDisposed = function () {
  20116. return this._isDisposed;
  20117. };
  20118. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  20119. get: function () {
  20120. return this._sideOrientation;
  20121. },
  20122. /**
  20123. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  20124. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  20125. */
  20126. set: function (sideO) {
  20127. this._sideOrientation = sideO;
  20128. },
  20129. enumerable: true,
  20130. configurable: true
  20131. });
  20132. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  20133. /**
  20134. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  20135. * This property is pertinent only for updatable parametric shapes.
  20136. */
  20137. get: function () {
  20138. return this._areNormalsFrozen;
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. /**
  20144. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20145. * It has no effect at all on other shapes.
  20146. * It prevents the mesh normals from being recomputed on next `positions` array update.
  20147. */
  20148. Mesh.prototype.freezeNormals = function () {
  20149. this._areNormalsFrozen = true;
  20150. };
  20151. /**
  20152. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  20153. * It has no effect at all on other shapes.
  20154. * It reactivates the mesh normals computation if it was previously frozen.
  20155. */
  20156. Mesh.prototype.unfreezeNormals = function () {
  20157. this._areNormalsFrozen = false;
  20158. };
  20159. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  20160. /**
  20161. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  20162. */
  20163. set: function (count) {
  20164. this._overridenInstanceCount = count;
  20165. },
  20166. enumerable: true,
  20167. configurable: true
  20168. });
  20169. // Methods
  20170. Mesh.prototype._preActivate = function () {
  20171. var sceneRenderId = this.getScene().getRenderId();
  20172. if (this._preActivateId === sceneRenderId) {
  20173. return;
  20174. }
  20175. this._preActivateId = sceneRenderId;
  20176. this._visibleInstances = null;
  20177. };
  20178. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20179. if (this._visibleInstances) {
  20180. this._visibleInstances.intermediateDefaultRenderId = renderId;
  20181. }
  20182. };
  20183. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  20184. if (!this._visibleInstances) {
  20185. this._visibleInstances = {};
  20186. this._visibleInstances.defaultRenderId = renderId;
  20187. this._visibleInstances.selfDefaultRenderId = this._renderId;
  20188. }
  20189. if (!this._visibleInstances[renderId]) {
  20190. this._visibleInstances[renderId] = new Array();
  20191. }
  20192. this._visibleInstances[renderId].push(instance);
  20193. };
  20194. /**
  20195. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  20196. * This means the mesh underlying bounding box and sphere are recomputed.
  20197. */
  20198. Mesh.prototype.refreshBoundingInfo = function () {
  20199. if (this._boundingInfo.isLocked) {
  20200. return;
  20201. }
  20202. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20203. if (data) {
  20204. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  20205. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  20206. }
  20207. if (this.subMeshes) {
  20208. for (var index = 0; index < this.subMeshes.length; index++) {
  20209. this.subMeshes[index].refreshBoundingInfo();
  20210. }
  20211. }
  20212. this._updateBoundingInfo();
  20213. };
  20214. Mesh.prototype._createGlobalSubMesh = function () {
  20215. var totalVertices = this.getTotalVertices();
  20216. if (!totalVertices || !this.getIndices()) {
  20217. return null;
  20218. }
  20219. this.releaseSubMeshes();
  20220. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  20221. };
  20222. Mesh.prototype.subdivide = function (count) {
  20223. if (count < 1) {
  20224. return;
  20225. }
  20226. var totalIndices = this.getTotalIndices();
  20227. var subdivisionSize = (totalIndices / count) | 0;
  20228. var offset = 0;
  20229. // Ensure that subdivisionSize is a multiple of 3
  20230. while (subdivisionSize % 3 !== 0) {
  20231. subdivisionSize++;
  20232. }
  20233. this.releaseSubMeshes();
  20234. for (var index = 0; index < count; index++) {
  20235. if (offset >= totalIndices) {
  20236. break;
  20237. }
  20238. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  20239. offset += subdivisionSize;
  20240. }
  20241. this.synchronizeInstances();
  20242. };
  20243. /**
  20244. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20245. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20246. * The `data` are either a numeric array either a Float32Array.
  20247. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  20248. * The parameter `stride` is an optional positive integer, it is usually automatically deducted from the `kind` (3 for positions or normals, 2 for UV, etc).
  20249. * Note that a new underlying VertexBuffer object is created each call.
  20250. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20251. *
  20252. * Possible `kind` values :
  20253. * - BABYLON.VertexBuffer.PositionKind
  20254. * - BABYLON.VertexBuffer.UVKind
  20255. * - BABYLON.VertexBuffer.UV2Kind
  20256. * - BABYLON.VertexBuffer.UV3Kind
  20257. * - BABYLON.VertexBuffer.UV4Kind
  20258. * - BABYLON.VertexBuffer.UV5Kind
  20259. * - BABYLON.VertexBuffer.UV6Kind
  20260. * - BABYLON.VertexBuffer.ColorKind
  20261. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20262. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20263. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20264. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20265. */
  20266. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20267. if (!this._geometry) {
  20268. var vertexData = new BABYLON.VertexData();
  20269. vertexData.set(data, kind);
  20270. var scene = this.getScene();
  20271. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  20272. }
  20273. else {
  20274. this._geometry.setVerticesData(kind, data, updatable, stride);
  20275. }
  20276. };
  20277. Mesh.prototype.setVerticesBuffer = function (buffer) {
  20278. if (!this._geometry) {
  20279. var scene = this.getScene();
  20280. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  20281. }
  20282. this._geometry.setVerticesBuffer(buffer);
  20283. };
  20284. /**
  20285. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20286. * If the mesh has no geometry, it is simply returned as it is.
  20287. * The `data` are either a numeric array either a Float32Array.
  20288. * No new underlying VertexBuffer object is created.
  20289. * If the `kind` is the `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20290. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  20291. *
  20292. * Possible `kind` values :
  20293. * - BABYLON.VertexBuffer.PositionKind
  20294. * - BABYLON.VertexBuffer.UVKind
  20295. * - BABYLON.VertexBuffer.UV2Kind
  20296. * - BABYLON.VertexBuffer.UV3Kind
  20297. * - BABYLON.VertexBuffer.UV4Kind
  20298. * - BABYLON.VertexBuffer.UV5Kind
  20299. * - BABYLON.VertexBuffer.UV6Kind
  20300. * - BABYLON.VertexBuffer.ColorKind
  20301. * - BABYLON.VertexBuffer.MatricesIndicesKind
  20302. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20303. * - BABYLON.VertexBuffer.MatricesWeightsKind
  20304. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20305. */
  20306. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20307. if (!this._geometry) {
  20308. return;
  20309. }
  20310. if (!makeItUnique) {
  20311. this._geometry.updateVerticesData(kind, data, updateExtends);
  20312. }
  20313. else {
  20314. this.makeGeometryUnique();
  20315. this.updateVerticesData(kind, data, updateExtends, false);
  20316. }
  20317. };
  20318. /**
  20319. * Deprecated since BabylonJS v2.3
  20320. */
  20321. Mesh.prototype.updateVerticesDataDirectly = function (kind, data, offset, makeItUnique) {
  20322. BABYLON.Tools.Warn("Mesh.updateVerticesDataDirectly deprecated since 2.3.");
  20323. if (!this._geometry) {
  20324. return;
  20325. }
  20326. if (!makeItUnique) {
  20327. this._geometry.updateVerticesDataDirectly(kind, data, offset);
  20328. }
  20329. else {
  20330. this.makeGeometryUnique();
  20331. this.updateVerticesDataDirectly(kind, data, offset, false);
  20332. }
  20333. };
  20334. /**
  20335. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  20336. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  20337. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  20338. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  20339. */
  20340. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  20341. if (computeNormals === void 0) { computeNormals = true; }
  20342. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20343. positionFunction(positions);
  20344. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  20345. if (computeNormals) {
  20346. var indices = this.getIndices();
  20347. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20348. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  20349. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  20350. }
  20351. };
  20352. Mesh.prototype.makeGeometryUnique = function () {
  20353. if (!this._geometry) {
  20354. return;
  20355. }
  20356. var oldGeometry = this._geometry;
  20357. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  20358. oldGeometry.releaseForMesh(this, true);
  20359. geometry.applyToMesh(this);
  20360. };
  20361. /**
  20362. * Sets the mesh indices.
  20363. * Expects an array populated with integers or a Int32Array.
  20364. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20365. * This method creates a new index buffer each call.
  20366. */
  20367. Mesh.prototype.setIndices = function (indices, totalVertices) {
  20368. if (!this._geometry) {
  20369. var vertexData = new BABYLON.VertexData();
  20370. vertexData.indices = indices;
  20371. var scene = this.getScene();
  20372. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  20373. }
  20374. else {
  20375. this._geometry.setIndices(indices, totalVertices);
  20376. }
  20377. };
  20378. /**
  20379. * Invert the geometry to move from a right handed system to a left handed one.
  20380. */
  20381. Mesh.prototype.toLeftHanded = function () {
  20382. if (!this._geometry) {
  20383. return;
  20384. }
  20385. this._geometry.toLeftHanded();
  20386. };
  20387. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  20388. var engine = this.getScene().getEngine();
  20389. // Wireframe
  20390. var indexToBind;
  20391. if (this._unIndexed) {
  20392. indexToBind = null;
  20393. }
  20394. else {
  20395. switch (fillMode) {
  20396. case BABYLON.Material.PointFillMode:
  20397. indexToBind = null;
  20398. break;
  20399. case BABYLON.Material.WireFrameFillMode:
  20400. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  20401. break;
  20402. default:
  20403. case BABYLON.Material.TriangleFillMode:
  20404. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  20405. break;
  20406. }
  20407. }
  20408. // VBOs
  20409. engine.bindBuffers(this._geometry.getVertexBuffers(), indexToBind, effect);
  20410. };
  20411. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  20412. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20413. return;
  20414. }
  20415. this.onBeforeDrawObservable.notifyObservers(this);
  20416. var engine = this.getScene().getEngine();
  20417. // Draw order
  20418. switch (fillMode) {
  20419. case BABYLON.Material.PointFillMode:
  20420. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20421. break;
  20422. case BABYLON.Material.WireFrameFillMode:
  20423. if (this._unIndexed) {
  20424. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20425. }
  20426. else {
  20427. engine.draw(false, 0, instancesCount > 0 ? subMesh.linesIndexCount / 2 : subMesh.linesIndexCount, instancesCount);
  20428. }
  20429. break;
  20430. default:
  20431. if (this._unIndexed) {
  20432. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  20433. }
  20434. else {
  20435. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  20436. }
  20437. }
  20438. };
  20439. /**
  20440. * Registers for this mesh a javascript function called just before the rendering process.
  20441. * This function is passed the current mesh and doesn't return anything.
  20442. */
  20443. Mesh.prototype.registerBeforeRender = function (func) {
  20444. this.onBeforeRenderObservable.add(func);
  20445. };
  20446. /**
  20447. * Disposes a previously registered javascript function called before the rendering.
  20448. * This function is passed the current mesh and doesn't return anything.
  20449. */
  20450. Mesh.prototype.unregisterBeforeRender = function (func) {
  20451. this.onBeforeRenderObservable.removeCallback(func);
  20452. };
  20453. /**
  20454. * Registers for this mesh a javascript function called just after the rendering is complete.
  20455. * This function is passed the current mesh and doesn't return anything.
  20456. */
  20457. Mesh.prototype.registerAfterRender = function (func) {
  20458. this.onAfterRenderObservable.add(func);
  20459. };
  20460. /**
  20461. * Disposes a previously registered javascript function called after the rendering.
  20462. * This function is passed the current mesh and doesn't return anything.
  20463. */
  20464. Mesh.prototype.unregisterAfterRender = function (func) {
  20465. this.onAfterRenderObservable.removeCallback(func);
  20466. };
  20467. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  20468. var scene = this.getScene();
  20469. this._batchCache.mustReturn = false;
  20470. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  20471. this._batchCache.visibleInstances[subMeshId] = null;
  20472. if (this._visibleInstances) {
  20473. var currentRenderId = scene.getRenderId();
  20474. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  20475. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  20476. var selfRenderId = this._renderId;
  20477. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  20478. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  20479. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  20480. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  20481. }
  20482. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  20483. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  20484. this._batchCache.mustReturn = true;
  20485. return this._batchCache;
  20486. }
  20487. if (currentRenderId !== selfRenderId) {
  20488. this._batchCache.renderSelf[subMeshId] = false;
  20489. }
  20490. }
  20491. this._renderIdForInstances[subMeshId] = currentRenderId;
  20492. }
  20493. return this._batchCache;
  20494. };
  20495. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  20496. var visibleInstances = batch.visibleInstances[subMesh._id];
  20497. var matricesCount = visibleInstances.length + 1;
  20498. var bufferSize = matricesCount * 16 * 4;
  20499. var currentInstancesBufferSize = this._instancesBufferSize;
  20500. var instancesBuffer = this._instancesBuffer;
  20501. while (this._instancesBufferSize < bufferSize) {
  20502. this._instancesBufferSize *= 2;
  20503. }
  20504. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  20505. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  20506. }
  20507. var offset = 0;
  20508. var instancesCount = 0;
  20509. var world = this.getWorldMatrix();
  20510. if (batch.renderSelf[subMesh._id]) {
  20511. world.copyToArray(this._instancesData, offset);
  20512. offset += 16;
  20513. instancesCount++;
  20514. }
  20515. if (visibleInstances) {
  20516. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  20517. var instance = visibleInstances[instanceIndex];
  20518. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  20519. offset += 16;
  20520. instancesCount++;
  20521. }
  20522. }
  20523. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  20524. if (instancesBuffer) {
  20525. instancesBuffer.dispose();
  20526. }
  20527. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  20528. this._instancesBuffer = instancesBuffer;
  20529. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  20530. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  20531. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  20532. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  20533. }
  20534. else {
  20535. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  20536. }
  20537. engine.bindBuffers(this.geometry.getVertexBuffers(), this.geometry.getIndexBuffer(), effect);
  20538. this._draw(subMesh, fillMode, instancesCount);
  20539. engine.unbindInstanceAttributes();
  20540. };
  20541. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  20542. var scene = this.getScene();
  20543. var engine = scene.getEngine();
  20544. if (hardwareInstancedRendering) {
  20545. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  20546. }
  20547. else {
  20548. if (batch.renderSelf[subMesh._id]) {
  20549. // Draw
  20550. if (onBeforeDraw) {
  20551. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  20552. }
  20553. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  20554. }
  20555. if (batch.visibleInstances[subMesh._id]) {
  20556. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  20557. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  20558. // World
  20559. var world = instance.getWorldMatrix();
  20560. if (onBeforeDraw) {
  20561. onBeforeDraw(true, world, effectiveMaterial);
  20562. }
  20563. // Draw
  20564. this._draw(subMesh, fillMode);
  20565. }
  20566. }
  20567. }
  20568. };
  20569. /**
  20570. * Triggers the draw call for the mesh.
  20571. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  20572. */
  20573. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  20574. var scene = this.getScene();
  20575. // Managing instances
  20576. var batch = this._getInstancesRenderList(subMesh._id);
  20577. if (batch.mustReturn) {
  20578. return;
  20579. }
  20580. // Checking geometry state
  20581. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  20582. return;
  20583. }
  20584. var callbackIndex;
  20585. this.onBeforeRenderObservable.notifyObservers(this);
  20586. var engine = scene.getEngine();
  20587. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  20588. // Material
  20589. var effectiveMaterial = subMesh.getMaterial();
  20590. if (!effectiveMaterial || !effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  20591. return;
  20592. }
  20593. // Outline - step 1
  20594. var savedDepthWrite = engine.getDepthWrite();
  20595. if (this.renderOutline) {
  20596. engine.setDepthWrite(false);
  20597. scene.getOutlineRenderer().render(subMesh, batch);
  20598. engine.setDepthWrite(savedDepthWrite);
  20599. }
  20600. effectiveMaterial._preBind();
  20601. var effect = effectiveMaterial.getEffect();
  20602. // Bind
  20603. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  20604. this._bind(subMesh, effect, fillMode);
  20605. var world = this.getWorldMatrix();
  20606. effectiveMaterial.bind(world, this);
  20607. // Alpha mode
  20608. if (enableAlphaMode) {
  20609. engine.setAlphaMode(effectiveMaterial.alphaMode);
  20610. }
  20611. // Draw
  20612. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  20613. // Unbind
  20614. effectiveMaterial.unbind();
  20615. // Outline - step 2
  20616. if (this.renderOutline && savedDepthWrite) {
  20617. engine.setDepthWrite(true);
  20618. engine.setColorWrite(false);
  20619. scene.getOutlineRenderer().render(subMesh, batch);
  20620. engine.setColorWrite(true);
  20621. }
  20622. // Overlay
  20623. if (this.renderOverlay) {
  20624. var currentMode = engine.getAlphaMode();
  20625. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  20626. scene.getOutlineRenderer().render(subMesh, batch, true);
  20627. engine.setAlphaMode(currentMode);
  20628. }
  20629. this.onAfterRenderObservable.notifyObservers(this);
  20630. };
  20631. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  20632. if (isInstance) {
  20633. effectiveMaterial.bindOnlyWorldMatrix(world);
  20634. }
  20635. };
  20636. /**
  20637. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  20638. */
  20639. Mesh.prototype.getEmittedParticleSystems = function () {
  20640. var results = new Array();
  20641. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20642. var particleSystem = this.getScene().particleSystems[index];
  20643. if (particleSystem.emitter === this) {
  20644. results.push(particleSystem);
  20645. }
  20646. }
  20647. return results;
  20648. };
  20649. /**
  20650. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  20651. */
  20652. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  20653. var results = new Array();
  20654. var descendants = this.getDescendants();
  20655. descendants.push(this);
  20656. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  20657. var particleSystem = this.getScene().particleSystems[index];
  20658. if (descendants.indexOf(particleSystem.emitter) !== -1) {
  20659. results.push(particleSystem);
  20660. }
  20661. }
  20662. return results;
  20663. };
  20664. Mesh.prototype._checkDelayState = function () {
  20665. var scene = this.getScene();
  20666. if (this._geometry) {
  20667. this._geometry.load(scene);
  20668. }
  20669. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20670. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  20671. this._queueLoad(this, scene);
  20672. }
  20673. };
  20674. Mesh.prototype._queueLoad = function (mesh, scene) {
  20675. var _this = this;
  20676. scene._addPendingData(mesh);
  20677. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  20678. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  20679. if (data instanceof ArrayBuffer) {
  20680. _this._delayLoadingFunction(data, _this);
  20681. }
  20682. else {
  20683. _this._delayLoadingFunction(JSON.parse(data), _this);
  20684. }
  20685. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20686. scene._removePendingData(_this);
  20687. }, function () { }, scene.database, getBinaryData);
  20688. };
  20689. /**
  20690. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  20691. */
  20692. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  20693. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  20694. return false;
  20695. }
  20696. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  20697. return false;
  20698. }
  20699. this._checkDelayState();
  20700. return true;
  20701. };
  20702. /**
  20703. * Sets the mesh material by the material or multiMaterial `id` property.
  20704. * The material `id` is a string identifying the material or the multiMaterial.
  20705. * This method returns nothing.
  20706. */
  20707. Mesh.prototype.setMaterialByID = function (id) {
  20708. var materials = this.getScene().materials;
  20709. var index;
  20710. for (index = 0; index < materials.length; index++) {
  20711. if (materials[index].id === id) {
  20712. this.material = materials[index];
  20713. return;
  20714. }
  20715. }
  20716. // Multi
  20717. var multiMaterials = this.getScene().multiMaterials;
  20718. for (index = 0; index < multiMaterials.length; index++) {
  20719. if (multiMaterials[index].id === id) {
  20720. this.material = multiMaterials[index];
  20721. return;
  20722. }
  20723. }
  20724. };
  20725. /**
  20726. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  20727. */
  20728. Mesh.prototype.getAnimatables = function () {
  20729. var results = [];
  20730. if (this.material) {
  20731. results.push(this.material);
  20732. }
  20733. if (this.skeleton) {
  20734. results.push(this.skeleton);
  20735. }
  20736. return results;
  20737. };
  20738. /**
  20739. * Modifies the mesh geometry according to the passed transformation matrix.
  20740. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  20741. * The mesh normals are modified accordingly the same transformation.
  20742. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20743. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20744. */
  20745. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  20746. // Position
  20747. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  20748. return;
  20749. }
  20750. var submeshes = this.subMeshes.splice(0);
  20751. this._resetPointsArrayCache();
  20752. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20753. var temp = [];
  20754. var index;
  20755. for (index = 0; index < data.length; index += 3) {
  20756. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  20757. }
  20758. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  20759. // Normals
  20760. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  20761. return;
  20762. }
  20763. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20764. temp = [];
  20765. for (index = 0; index < data.length; index += 3) {
  20766. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  20767. }
  20768. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  20769. // flip faces?
  20770. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  20771. this.flipFaces();
  20772. }
  20773. // Restore submeshes
  20774. this.releaseSubMeshes();
  20775. this.subMeshes = submeshes;
  20776. };
  20777. /**
  20778. * Modifies the mesh geometry according to its own current World Matrix.
  20779. * The mesh World Matrix is then reset.
  20780. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  20781. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  20782. * Note that, under the hood, this method sets a new VertexBuffer each call.
  20783. */
  20784. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  20785. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  20786. this.scaling.copyFromFloats(1, 1, 1);
  20787. this.position.copyFromFloats(0, 0, 0);
  20788. this.rotation.copyFromFloats(0, 0, 0);
  20789. //only if quaternion is already set
  20790. if (this.rotationQuaternion) {
  20791. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  20792. }
  20793. this._worldMatrix = BABYLON.Matrix.Identity();
  20794. };
  20795. // Cache
  20796. Mesh.prototype._resetPointsArrayCache = function () {
  20797. this._positions = null;
  20798. };
  20799. Mesh.prototype._generatePointsArray = function () {
  20800. if (this._positions)
  20801. return true;
  20802. this._positions = [];
  20803. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20804. if (!data) {
  20805. return false;
  20806. }
  20807. for (var index = 0; index < data.length; index += 3) {
  20808. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  20809. }
  20810. return true;
  20811. };
  20812. /**
  20813. * Returns a new Mesh object generated from the current mesh properties.
  20814. * This method must not get confused with createInstance().
  20815. * The parameter `name` is a string, the name given to the new mesh.
  20816. * The optional parameter `newParent` can be any Node object (default `null`).
  20817. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  20818. * The parameter `clonePhysicsImpostor` (default `true`) allows/denies the cloning in the same time of the original mesh `body` used by the physics engine, if any.
  20819. */
  20820. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  20821. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20822. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  20823. };
  20824. /**
  20825. * Disposes the mesh.
  20826. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  20827. */
  20828. Mesh.prototype.dispose = function (doNotRecurse) {
  20829. if (this._geometry) {
  20830. this._geometry.releaseForMesh(this, true);
  20831. }
  20832. // Instances
  20833. if (this._instancesBuffer) {
  20834. this._instancesBuffer.dispose();
  20835. this._instancesBuffer = null;
  20836. }
  20837. while (this.instances.length) {
  20838. this.instances[0].dispose();
  20839. }
  20840. // Highlight layers.
  20841. var highlightLayers = this.getScene().highlightLayers;
  20842. for (var i = 0; i < highlightLayers.length; i++) {
  20843. var highlightLayer = highlightLayers[i];
  20844. if (highlightLayer) {
  20845. highlightLayer.removeMesh(this);
  20846. highlightLayer.removeExcludedMesh(this);
  20847. }
  20848. }
  20849. _super.prototype.dispose.call(this, doNotRecurse);
  20850. };
  20851. /**
  20852. * Modifies the mesh geometry according to a displacement map.
  20853. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  20854. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20855. * This method returns nothing.
  20856. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  20857. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20858. * The parameter `onSuccess` is an optional Javascript function to be called just after the mesh is modified. It is passed the modified mesh and must return nothing.
  20859. */
  20860. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess) {
  20861. var _this = this;
  20862. var scene = this.getScene();
  20863. var onload = function (img) {
  20864. // Getting height map data
  20865. var canvas = document.createElement("canvas");
  20866. var context = canvas.getContext("2d");
  20867. var heightMapWidth = img.width;
  20868. var heightMapHeight = img.height;
  20869. canvas.width = heightMapWidth;
  20870. canvas.height = heightMapHeight;
  20871. context.drawImage(img, 0, 0);
  20872. // Create VertexData from map data
  20873. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  20874. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  20875. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight);
  20876. //execute success callback, if set
  20877. if (onSuccess) {
  20878. onSuccess(_this);
  20879. }
  20880. };
  20881. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  20882. };
  20883. /**
  20884. * Modifies the mesh geometry according to a displacementMap buffer.
  20885. * A displacement map is a colored image. Each pixel color value (actually a gradient computed from red, green, blue values) will give the displacement to apply to each mesh vertex.
  20886. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  20887. * This method returns nothing.
  20888. * The parameter `buffer` is a `Uint8Array` buffer containing series of `Uint8` lower than 255, the red, green, blue and alpha values of each successive pixel.
  20889. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  20890. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  20891. */
  20892. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight) {
  20893. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  20894. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  20895. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  20896. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  20897. return;
  20898. }
  20899. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20900. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20901. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  20902. var position = BABYLON.Vector3.Zero();
  20903. var normal = BABYLON.Vector3.Zero();
  20904. var uv = BABYLON.Vector2.Zero();
  20905. for (var index = 0; index < positions.length; index += 3) {
  20906. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  20907. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  20908. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  20909. // Compute height
  20910. var u = ((Math.abs(uv.x) * heightMapWidth) % heightMapWidth) | 0;
  20911. var v = ((Math.abs(uv.y) * heightMapHeight) % heightMapHeight) | 0;
  20912. var pos = (u + v * heightMapWidth) * 4;
  20913. var r = buffer[pos] / 255.0;
  20914. var g = buffer[pos + 1] / 255.0;
  20915. var b = buffer[pos + 2] / 255.0;
  20916. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  20917. normal.normalize();
  20918. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  20919. position = position.add(normal);
  20920. position.toArray(positions, index);
  20921. }
  20922. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  20923. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  20924. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  20925. };
  20926. /**
  20927. * Modify the mesh to get a flat shading rendering.
  20928. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  20929. * This method returns nothing.
  20930. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  20931. */
  20932. Mesh.prototype.convertToFlatShadedMesh = function () {
  20933. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  20934. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  20935. var kinds = this.getVerticesDataKinds();
  20936. var vbs = [];
  20937. var data = [];
  20938. var newdata = [];
  20939. var updatableNormals = false;
  20940. var kindIndex;
  20941. var kind;
  20942. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20943. kind = kinds[kindIndex];
  20944. var vertexBuffer = this.getVertexBuffer(kind);
  20945. if (kind === BABYLON.VertexBuffer.NormalKind) {
  20946. updatableNormals = vertexBuffer.isUpdatable();
  20947. kinds.splice(kindIndex, 1);
  20948. kindIndex--;
  20949. continue;
  20950. }
  20951. vbs[kind] = vertexBuffer;
  20952. data[kind] = vbs[kind].getData();
  20953. newdata[kind] = [];
  20954. }
  20955. // Save previous submeshes
  20956. var previousSubmeshes = this.subMeshes.slice(0);
  20957. var indices = this.getIndices();
  20958. var totalIndices = this.getTotalIndices();
  20959. // Generating unique vertices per face
  20960. var index;
  20961. for (index = 0; index < totalIndices; index++) {
  20962. var vertexIndex = indices[index];
  20963. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20964. kind = kinds[kindIndex];
  20965. var stride = vbs[kind].getStrideSize();
  20966. for (var offset = 0; offset < stride; offset++) {
  20967. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  20968. }
  20969. }
  20970. }
  20971. // Updating faces & normal
  20972. var normals = [];
  20973. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  20974. for (index = 0; index < totalIndices; index += 3) {
  20975. indices[index] = index;
  20976. indices[index + 1] = index + 1;
  20977. indices[index + 2] = index + 2;
  20978. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  20979. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  20980. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  20981. var p1p2 = p1.subtract(p2);
  20982. var p3p2 = p3.subtract(p2);
  20983. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  20984. // Store same normals for every vertex
  20985. for (var localIndex = 0; localIndex < 3; localIndex++) {
  20986. normals.push(normal.x);
  20987. normals.push(normal.y);
  20988. normals.push(normal.z);
  20989. }
  20990. }
  20991. this.setIndices(indices);
  20992. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  20993. // Updating vertex buffers
  20994. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  20995. kind = kinds[kindIndex];
  20996. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  20997. }
  20998. // Updating submeshes
  20999. this.releaseSubMeshes();
  21000. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21001. var previousOne = previousSubmeshes[submeshIndex];
  21002. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21003. }
  21004. this.synchronizeInstances();
  21005. };
  21006. /**
  21007. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  21008. * In other words, more vertices, no more indices and a single bigger VBO.
  21009. * This method returns nothing.
  21010. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  21011. *
  21012. */
  21013. Mesh.prototype.convertToUnIndexedMesh = function () {
  21014. /// <summary>Remove indices by unfolding faces into buffers</summary>
  21015. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  21016. var kinds = this.getVerticesDataKinds();
  21017. var vbs = [];
  21018. var data = [];
  21019. var newdata = [];
  21020. var updatableNormals = false;
  21021. var kindIndex;
  21022. var kind;
  21023. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21024. kind = kinds[kindIndex];
  21025. var vertexBuffer = this.getVertexBuffer(kind);
  21026. vbs[kind] = vertexBuffer;
  21027. data[kind] = vbs[kind].getData();
  21028. newdata[kind] = [];
  21029. }
  21030. // Save previous submeshes
  21031. var previousSubmeshes = this.subMeshes.slice(0);
  21032. var indices = this.getIndices();
  21033. var totalIndices = this.getTotalIndices();
  21034. // Generating unique vertices per face
  21035. var index;
  21036. for (index = 0; index < totalIndices; index++) {
  21037. var vertexIndex = indices[index];
  21038. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21039. kind = kinds[kindIndex];
  21040. var stride = vbs[kind].getStrideSize();
  21041. for (var offset = 0; offset < stride; offset++) {
  21042. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  21043. }
  21044. }
  21045. }
  21046. // Updating indices
  21047. for (index = 0; index < totalIndices; index += 3) {
  21048. indices[index] = index;
  21049. indices[index + 1] = index + 1;
  21050. indices[index + 2] = index + 2;
  21051. }
  21052. this.setIndices(indices);
  21053. // Updating vertex buffers
  21054. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  21055. kind = kinds[kindIndex];
  21056. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  21057. }
  21058. // Updating submeshes
  21059. this.releaseSubMeshes();
  21060. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  21061. var previousOne = previousSubmeshes[submeshIndex];
  21062. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  21063. }
  21064. this._unIndexed = true;
  21065. this.synchronizeInstances();
  21066. };
  21067. /**
  21068. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  21069. * This method returns nothing.
  21070. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  21071. */
  21072. Mesh.prototype.flipFaces = function (flipNormals) {
  21073. if (flipNormals === void 0) { flipNormals = false; }
  21074. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  21075. var i;
  21076. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21077. for (i = 0; i < vertex_data.normals.length; i++) {
  21078. vertex_data.normals[i] *= -1;
  21079. }
  21080. }
  21081. var temp;
  21082. for (i = 0; i < vertex_data.indices.length; i += 3) {
  21083. // reassign indices
  21084. temp = vertex_data.indices[i + 1];
  21085. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  21086. vertex_data.indices[i + 2] = temp;
  21087. }
  21088. vertex_data.applyToMesh(this);
  21089. };
  21090. // Instances
  21091. /**
  21092. * Creates a new InstancedMesh object from the mesh model.
  21093. * An instance shares the same properties and the same material than its model.
  21094. * Only these properties of each instance can then be set individually :
  21095. * - position
  21096. * - rotation
  21097. * - rotationQuaternion
  21098. * - setPivotMatrix
  21099. * - scaling
  21100. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  21101. * Warning : this method is not supported for Line mesh and LineSystem
  21102. */
  21103. Mesh.prototype.createInstance = function (name) {
  21104. return new BABYLON.InstancedMesh(name, this);
  21105. };
  21106. /**
  21107. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  21108. * After this call, all the mesh instances have the same submeshes than the current mesh.
  21109. * This method returns nothing.
  21110. */
  21111. Mesh.prototype.synchronizeInstances = function () {
  21112. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  21113. var instance = this.instances[instanceIndex];
  21114. instance._syncSubMeshes();
  21115. }
  21116. };
  21117. /**
  21118. * Simplify the mesh according to the given array of settings.
  21119. * Function will return immediately and will simplify async. It returns nothing.
  21120. * @param settings a collection of simplification settings.
  21121. * @param parallelProcessing should all levels calculate parallel or one after the other.
  21122. * @param type the type of simplification to run.
  21123. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  21124. */
  21125. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  21126. if (parallelProcessing === void 0) { parallelProcessing = true; }
  21127. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  21128. this.getScene().simplificationQueue.addTask({
  21129. settings: settings,
  21130. parallelProcessing: parallelProcessing,
  21131. mesh: this,
  21132. simplificationType: simplificationType,
  21133. successCallback: successCallback
  21134. });
  21135. };
  21136. /**
  21137. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  21138. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  21139. * This should be used together with the simplification to avoid disappearing triangles.
  21140. * @param successCallback an optional success callback to be called after the optimization finished.
  21141. */
  21142. Mesh.prototype.optimizeIndices = function (successCallback) {
  21143. var _this = this;
  21144. var indices = this.getIndices();
  21145. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21146. var vectorPositions = [];
  21147. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  21148. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  21149. }
  21150. var dupes = [];
  21151. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  21152. var realPos = vectorPositions.length - 1 - iteration;
  21153. var testedPosition = vectorPositions[realPos];
  21154. for (var j = 0; j < realPos; ++j) {
  21155. var againstPosition = vectorPositions[j];
  21156. if (testedPosition.equals(againstPosition)) {
  21157. dupes[realPos] = j;
  21158. break;
  21159. }
  21160. }
  21161. }, function () {
  21162. for (var i = 0; i < indices.length; ++i) {
  21163. indices[i] = dupes[indices[i]] || indices[i];
  21164. }
  21165. //indices are now reordered
  21166. var originalSubMeshes = _this.subMeshes.slice(0);
  21167. _this.setIndices(indices);
  21168. _this.subMeshes = originalSubMeshes;
  21169. if (successCallback) {
  21170. successCallback(_this);
  21171. }
  21172. });
  21173. };
  21174. // Statics
  21175. /**
  21176. * Returns a new Mesh object what is a deep copy of the passed mesh.
  21177. * The parameter `parsedMesh` is the mesh to be copied.
  21178. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  21179. */
  21180. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  21181. var mesh = new Mesh(parsedMesh.name, scene);
  21182. mesh.id = parsedMesh.id;
  21183. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  21184. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  21185. if (parsedMesh.metadata !== undefined) {
  21186. mesh.metadata = parsedMesh.metadata;
  21187. }
  21188. if (parsedMesh.rotationQuaternion) {
  21189. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  21190. }
  21191. else if (parsedMesh.rotation) {
  21192. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  21193. }
  21194. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  21195. if (parsedMesh.localMatrix) {
  21196. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  21197. }
  21198. else if (parsedMesh.pivotMatrix) {
  21199. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  21200. }
  21201. mesh.setEnabled(parsedMesh.isEnabled);
  21202. mesh.isVisible = parsedMesh.isVisible;
  21203. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  21204. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  21205. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  21206. if (parsedMesh.applyFog !== undefined) {
  21207. mesh.applyFog = parsedMesh.applyFog;
  21208. }
  21209. if (parsedMesh.pickable !== undefined) {
  21210. mesh.isPickable = parsedMesh.pickable;
  21211. }
  21212. if (parsedMesh.alphaIndex !== undefined) {
  21213. mesh.alphaIndex = parsedMesh.alphaIndex;
  21214. }
  21215. mesh.receiveShadows = parsedMesh.receiveShadows;
  21216. mesh.billboardMode = parsedMesh.billboardMode;
  21217. if (parsedMesh.visibility !== undefined) {
  21218. mesh.visibility = parsedMesh.visibility;
  21219. }
  21220. mesh.checkCollisions = parsedMesh.checkCollisions;
  21221. if (parsedMesh.isBlocker !== undefined) {
  21222. mesh.isBlocker = parsedMesh.isBlocker;
  21223. }
  21224. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  21225. // freezeWorldMatrix
  21226. if (parsedMesh.freezeWorldMatrix) {
  21227. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  21228. }
  21229. // Parent
  21230. if (parsedMesh.parentId) {
  21231. mesh._waitingParentId = parsedMesh.parentId;
  21232. }
  21233. // Actions
  21234. if (parsedMesh.actions !== undefined) {
  21235. mesh._waitingActions = parsedMesh.actions;
  21236. }
  21237. // Overlay
  21238. if (parsedMesh.overlayAlpha !== undefined) {
  21239. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  21240. }
  21241. if (parsedMesh.overlayColor !== undefined) {
  21242. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  21243. }
  21244. if (parsedMesh.renderOverlay !== undefined) {
  21245. mesh.renderOverlay = parsedMesh.renderOverlay;
  21246. }
  21247. // Geometry
  21248. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  21249. if (parsedMesh.delayLoadingFile) {
  21250. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  21251. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  21252. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  21253. if (parsedMesh._binaryInfo) {
  21254. mesh._binaryInfo = parsedMesh._binaryInfo;
  21255. }
  21256. mesh._delayInfo = [];
  21257. if (parsedMesh.hasUVs) {
  21258. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  21259. }
  21260. if (parsedMesh.hasUVs2) {
  21261. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  21262. }
  21263. if (parsedMesh.hasUVs3) {
  21264. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  21265. }
  21266. if (parsedMesh.hasUVs4) {
  21267. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  21268. }
  21269. if (parsedMesh.hasUVs5) {
  21270. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  21271. }
  21272. if (parsedMesh.hasUVs6) {
  21273. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  21274. }
  21275. if (parsedMesh.hasColors) {
  21276. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  21277. }
  21278. if (parsedMesh.hasMatricesIndices) {
  21279. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  21280. }
  21281. if (parsedMesh.hasMatricesWeights) {
  21282. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  21283. }
  21284. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  21285. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  21286. mesh._checkDelayState();
  21287. }
  21288. }
  21289. else {
  21290. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  21291. }
  21292. // Material
  21293. if (parsedMesh.materialId) {
  21294. mesh.setMaterialByID(parsedMesh.materialId);
  21295. }
  21296. else {
  21297. mesh.material = null;
  21298. }
  21299. // Skeleton
  21300. if (parsedMesh.skeletonId > -1) {
  21301. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  21302. if (parsedMesh.numBoneInfluencers) {
  21303. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  21304. }
  21305. }
  21306. // Animations
  21307. if (parsedMesh.animations) {
  21308. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21309. var parsedAnimation = parsedMesh.animations[animationIndex];
  21310. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21311. }
  21312. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  21313. }
  21314. if (parsedMesh.autoAnimate) {
  21315. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  21316. }
  21317. // Layer Mask
  21318. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  21319. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  21320. }
  21321. else {
  21322. mesh.layerMask = 0x0FFFFFFF;
  21323. }
  21324. //(Deprecated) physics
  21325. if (parsedMesh.physicsImpostor) {
  21326. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  21327. mass: parsedMesh.physicsMass,
  21328. friction: parsedMesh.physicsFriction,
  21329. restitution: parsedMesh.physicsRestitution
  21330. }, scene);
  21331. }
  21332. // Instances
  21333. if (parsedMesh.instances) {
  21334. for (var index = 0; index < parsedMesh.instances.length; index++) {
  21335. var parsedInstance = parsedMesh.instances[index];
  21336. var instance = mesh.createInstance(parsedInstance.name);
  21337. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  21338. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  21339. if (parsedInstance.parentId) {
  21340. instance._waitingParentId = parsedInstance.parentId;
  21341. }
  21342. if (parsedInstance.rotationQuaternion) {
  21343. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  21344. }
  21345. else if (parsedInstance.rotation) {
  21346. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  21347. }
  21348. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  21349. instance.checkCollisions = mesh.checkCollisions;
  21350. if (parsedMesh.animations) {
  21351. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  21352. parsedAnimation = parsedMesh.animations[animationIndex];
  21353. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21354. }
  21355. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  21356. }
  21357. }
  21358. }
  21359. return mesh;
  21360. };
  21361. /**
  21362. * Creates a ribbon mesh.
  21363. * Please consider using the same method from the MeshBuilder class instead.
  21364. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21365. *
  21366. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  21367. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  21368. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  21369. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  21370. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  21371. * It's the offset to join together the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  21372. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  21373. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21374. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21375. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21376. */
  21377. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  21378. return BABYLON.MeshBuilder.CreateRibbon(name, {
  21379. pathArray: pathArray,
  21380. closeArray: closeArray,
  21381. closePath: closePath,
  21382. offset: offset,
  21383. updatable: updatable,
  21384. sideOrientation: sideOrientation,
  21385. instance: instance
  21386. }, scene);
  21387. };
  21388. /**
  21389. * Creates a plane polygonal mesh. By default, this is a disc.
  21390. * Please consider using the same method from the MeshBuilder class instead.
  21391. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  21392. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  21393. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21394. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21395. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21396. */
  21397. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  21398. var options = {
  21399. radius: radius,
  21400. tessellation: tessellation,
  21401. sideOrientation: sideOrientation,
  21402. updatable: updatable
  21403. };
  21404. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  21405. };
  21406. /**
  21407. * Creates a box mesh.
  21408. * Please consider using the same method from the MeshBuilder class instead.
  21409. * The parameter `size` sets the size (float) of each box side (default 1).
  21410. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21411. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21412. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21413. */
  21414. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  21415. var options = {
  21416. size: size,
  21417. sideOrientation: sideOrientation,
  21418. updatable: updatable
  21419. };
  21420. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  21421. };
  21422. /**
  21423. * Creates a sphere mesh.
  21424. * Please consider using the same method from the MeshBuilder class instead.
  21425. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  21426. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  21427. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21428. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21429. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21430. */
  21431. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  21432. var options = {
  21433. segments: segments,
  21434. diameterX: diameter,
  21435. diameterY: diameter,
  21436. diameterZ: diameter,
  21437. sideOrientation: sideOrientation,
  21438. updatable: updatable
  21439. };
  21440. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  21441. };
  21442. /**
  21443. * Creates a cylinder or a cone mesh.
  21444. * Please consider using the same method from the MeshBuilder class instead.
  21445. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  21446. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  21447. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  21448. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  21449. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  21450. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21451. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21452. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21453. */
  21454. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  21455. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  21456. if (scene !== undefined) {
  21457. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  21458. updatable = scene;
  21459. }
  21460. scene = subdivisions;
  21461. subdivisions = 1;
  21462. }
  21463. var options = {
  21464. height: height,
  21465. diameterTop: diameterTop,
  21466. diameterBottom: diameterBottom,
  21467. tessellation: tessellation,
  21468. subdivisions: subdivisions,
  21469. sideOrientation: sideOrientation,
  21470. updatable: updatable
  21471. };
  21472. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  21473. };
  21474. // Torus (Code from SharpDX.org)
  21475. /**
  21476. * Creates a torus mesh.
  21477. * Please consider using the same method from the MeshBuilder class instead.
  21478. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  21479. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  21480. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  21481. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21482. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21483. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21484. */
  21485. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  21486. var options = {
  21487. diameter: diameter,
  21488. thickness: thickness,
  21489. tessellation: tessellation,
  21490. sideOrientation: sideOrientation,
  21491. updatable: updatable
  21492. };
  21493. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  21494. };
  21495. /**
  21496. * Creates a torus knot mesh.
  21497. * Please consider using the same method from the MeshBuilder class instead.
  21498. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  21499. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  21500. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  21501. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  21502. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21503. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21504. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21505. */
  21506. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  21507. var options = {
  21508. radius: radius,
  21509. tube: tube,
  21510. radialSegments: radialSegments,
  21511. tubularSegments: tubularSegments,
  21512. p: p,
  21513. q: q,
  21514. sideOrientation: sideOrientation,
  21515. updatable: updatable
  21516. };
  21517. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  21518. };
  21519. /**
  21520. * Creates a line mesh.
  21521. * Please consider using the same method from the MeshBuilder class instead.
  21522. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  21523. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21524. * The parameter `points` is an array successive Vector3.
  21525. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  21526. * When updating an instance, remember that only point positions can change, not the number of points.
  21527. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21528. */
  21529. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  21530. var options = {
  21531. points: points,
  21532. updatable: updatable,
  21533. instance: instance
  21534. };
  21535. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  21536. };
  21537. /**
  21538. * Creates a dashed line mesh.
  21539. * Please consider using the same method from the MeshBuilder class instead.
  21540. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  21541. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  21542. * The parameter `points` is an array successive Vector3.
  21543. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  21544. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  21545. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  21546. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  21547. * When updating an instance, remember that only point positions can change, not the number of points.
  21548. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21549. */
  21550. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  21551. var options = {
  21552. points: points,
  21553. dashSize: dashSize,
  21554. gapSize: gapSize,
  21555. dashNb: dashNb,
  21556. updatable: updatable,
  21557. instance: instance
  21558. };
  21559. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  21560. };
  21561. /**
  21562. * Creates an extruded shape mesh.
  21563. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21564. * Please consider using the same method from the MeshBuilder class instead.
  21565. *
  21566. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21567. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  21568. * extruded along the Z axis.
  21569. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21570. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  21571. * The parameter `scale` (float, default 1) is the value to scale the shape.
  21572. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21573. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  21574. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21575. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21576. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21577. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21578. */
  21579. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  21580. var options = {
  21581. shape: shape,
  21582. path: path,
  21583. scale: scale,
  21584. rotation: rotation,
  21585. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21586. sideOrientation: sideOrientation,
  21587. instance: instance,
  21588. updatable: updatable
  21589. };
  21590. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  21591. };
  21592. /**
  21593. * Creates an custom extruded shape mesh.
  21594. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21595. * Please consider using the same method from the MeshBuilder class instead.
  21596. *
  21597. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  21598. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  21599. * extruded along the Z axis.
  21600. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  21601. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  21602. * and the distance of this point from the begining of the path :
  21603. * ```javascript
  21604. * var rotationFunction = function(i, distance) {
  21605. * // do things
  21606. * return rotationValue; }
  21607. * ```
  21608. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  21609. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  21610. * and the distance of this point from the begining of the path :
  21611. * ```javascript
  21612. * var scaleFunction = function(i, distance) {
  21613. * // do things
  21614. * return scaleValue;}
  21615. * ```
  21616. * It must returns a float value that will be the scale value applied to the shape on each path point.
  21617. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  21618. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  21619. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21620. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  21621. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  21622. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21623. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21624. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21625. */
  21626. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  21627. var options = {
  21628. shape: shape,
  21629. path: path,
  21630. scaleFunction: scaleFunction,
  21631. rotationFunction: rotationFunction,
  21632. ribbonCloseArray: ribbonCloseArray,
  21633. ribbonClosePath: ribbonClosePath,
  21634. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  21635. sideOrientation: sideOrientation,
  21636. instance: instance,
  21637. updatable: updatable
  21638. };
  21639. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  21640. };
  21641. /**
  21642. * Creates lathe mesh.
  21643. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  21644. * Please consider using the same method from the MeshBuilder class instead.
  21645. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  21646. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  21647. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  21648. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  21649. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21650. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21651. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21652. */
  21653. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  21654. var options = {
  21655. shape: shape,
  21656. radius: radius,
  21657. tessellation: tessellation,
  21658. sideOrientation: sideOrientation,
  21659. updatable: updatable
  21660. };
  21661. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  21662. };
  21663. /**
  21664. * Creates a plane mesh.
  21665. * Please consider using the same method from the MeshBuilder class instead.
  21666. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  21667. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21668. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21669. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21670. */
  21671. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  21672. var options = {
  21673. size: size,
  21674. width: size,
  21675. height: size,
  21676. sideOrientation: sideOrientation,
  21677. updatable: updatable
  21678. };
  21679. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  21680. };
  21681. /**
  21682. * Creates a ground mesh.
  21683. * Please consider using the same method from the MeshBuilder class instead.
  21684. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  21685. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  21686. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21687. */
  21688. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  21689. var options = {
  21690. width: width,
  21691. height: height,
  21692. subdivisions: subdivisions,
  21693. updatable: updatable
  21694. };
  21695. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  21696. };
  21697. /**
  21698. * Creates a tiled ground mesh.
  21699. * Please consider using the same method from the MeshBuilder class instead.
  21700. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  21701. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  21702. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  21703. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  21704. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  21705. * numbers of subdivisions on the ground width and height of each tile.
  21706. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21707. */
  21708. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  21709. var options = {
  21710. xmin: xmin,
  21711. zmin: zmin,
  21712. xmax: xmax,
  21713. zmax: zmax,
  21714. subdivisions: subdivisions,
  21715. precision: precision,
  21716. updatable: updatable
  21717. };
  21718. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  21719. };
  21720. /**
  21721. * Creates a ground mesh from a height map.
  21722. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  21723. * Please consider using the same method from the MeshBuilder class instead.
  21724. * The parameter `url` sets the URL of the height map image resource.
  21725. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  21726. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  21727. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  21728. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  21729. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  21730. * This function is passed the newly built mesh :
  21731. * ```javascript
  21732. * function(mesh) { // do things
  21733. * return; }
  21734. * ```
  21735. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21736. */
  21737. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  21738. var options = {
  21739. width: width,
  21740. height: height,
  21741. subdivisions: subdivisions,
  21742. minHeight: minHeight,
  21743. maxHeight: maxHeight,
  21744. updatable: updatable,
  21745. onReady: onReady
  21746. };
  21747. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  21748. };
  21749. /**
  21750. * Creates a tube mesh.
  21751. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  21752. * Please consider using the same method from the MeshBuilder class instead.
  21753. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  21754. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  21755. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  21756. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  21757. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  21758. * It must return a radius value (positive float) :
  21759. * ```javascript
  21760. * var radiusFunction = function(i, distance) {
  21761. * // do things
  21762. * return radius; }
  21763. * ```
  21764. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  21765. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  21766. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21767. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21768. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21769. */
  21770. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  21771. var options = {
  21772. path: path,
  21773. radius: radius,
  21774. tessellation: tessellation,
  21775. radiusFunction: radiusFunction,
  21776. arc: 1,
  21777. cap: cap,
  21778. updatable: updatable,
  21779. sideOrientation: sideOrientation,
  21780. instance: instance
  21781. };
  21782. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  21783. };
  21784. /**
  21785. * Creates a polyhedron mesh.
  21786. * Please consider using the same method from the MeshBuilder class instead.
  21787. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  21788. * to choose the wanted type.
  21789. * The parameter `size` (positive float, default 1) sets the polygon size.
  21790. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  21791. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  21792. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  21793. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  21794. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  21795. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  21796. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21797. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21798. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21799. */
  21800. Mesh.CreatePolyhedron = function (name, options, scene) {
  21801. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  21802. };
  21803. /**
  21804. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  21805. * Please consider using the same method from the MeshBuilder class instead.
  21806. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  21807. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  21808. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  21809. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  21810. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  21811. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  21812. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  21813. */
  21814. Mesh.CreateIcoSphere = function (name, options, scene) {
  21815. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  21816. };
  21817. /**
  21818. * Creates a decal mesh.
  21819. * Please consider using the same method from the MeshBuilder class instead.
  21820. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  21821. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  21822. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  21823. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  21824. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  21825. */
  21826. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  21827. var options = {
  21828. position: position,
  21829. normal: normal,
  21830. size: size,
  21831. angle: angle
  21832. };
  21833. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  21834. };
  21835. // Skeletons
  21836. /**
  21837. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21838. */
  21839. Mesh.prototype.setPositionsForCPUSkinning = function () {
  21840. var source;
  21841. if (!this._sourcePositions) {
  21842. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21843. this._sourcePositions = new Float32Array(source);
  21844. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  21845. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  21846. }
  21847. }
  21848. return this._sourcePositions;
  21849. };
  21850. /**
  21851. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  21852. */
  21853. Mesh.prototype.setNormalsForCPUSkinning = function () {
  21854. var source;
  21855. if (!this._sourceNormals) {
  21856. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21857. this._sourceNormals = new Float32Array(source);
  21858. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  21859. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  21860. }
  21861. }
  21862. return this._sourceNormals;
  21863. };
  21864. /**
  21865. * Update the vertex buffers by applying transformation from the bones
  21866. * @param {skeleton} skeleton to apply
  21867. */
  21868. Mesh.prototype.applySkeleton = function (skeleton) {
  21869. if (!this.geometry) {
  21870. return;
  21871. }
  21872. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  21873. return;
  21874. }
  21875. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  21876. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  21877. return this;
  21878. }
  21879. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21880. return this;
  21881. }
  21882. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  21883. return this;
  21884. }
  21885. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  21886. return this;
  21887. }
  21888. if (!this._sourcePositions) {
  21889. var submeshes = this.subMeshes.slice();
  21890. this.setPositionsForCPUSkinning();
  21891. this.subMeshes = submeshes;
  21892. }
  21893. if (!this._sourceNormals) {
  21894. this.setNormalsForCPUSkinning();
  21895. }
  21896. // positionsData checks for not being Float32Array will only pass at most once
  21897. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21898. if (!(positionsData instanceof Float32Array)) {
  21899. positionsData = new Float32Array(positionsData);
  21900. }
  21901. // normalsData checks for not being Float32Array will only pass at most once
  21902. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21903. if (!(normalsData instanceof Float32Array)) {
  21904. normalsData = new Float32Array(normalsData);
  21905. }
  21906. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  21907. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  21908. var needExtras = this.numBoneInfluencers > 4;
  21909. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  21910. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  21911. var skeletonMatrices = skeleton.getTransformMatrices(this);
  21912. var tempVector3 = BABYLON.Vector3.Zero();
  21913. var finalMatrix = new BABYLON.Matrix();
  21914. var tempMatrix = new BABYLON.Matrix();
  21915. var matWeightIdx = 0;
  21916. var inf;
  21917. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  21918. var weight;
  21919. for (inf = 0; inf < 4; inf++) {
  21920. weight = matricesWeightsData[matWeightIdx + inf];
  21921. if (weight > 0) {
  21922. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21923. finalMatrix.addToSelf(tempMatrix);
  21924. }
  21925. else
  21926. break;
  21927. }
  21928. if (needExtras) {
  21929. for (inf = 0; inf < 4; inf++) {
  21930. weight = matricesWeightsExtraData[matWeightIdx + inf];
  21931. if (weight > 0) {
  21932. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  21933. finalMatrix.addToSelf(tempMatrix);
  21934. }
  21935. else
  21936. break;
  21937. }
  21938. }
  21939. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  21940. tempVector3.toArray(positionsData, index);
  21941. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  21942. tempVector3.toArray(normalsData, index);
  21943. finalMatrix.reset();
  21944. }
  21945. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  21946. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  21947. return this;
  21948. };
  21949. // Tools
  21950. /**
  21951. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  21952. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  21953. */
  21954. Mesh.MinMax = function (meshes) {
  21955. var minVector = null;
  21956. var maxVector = null;
  21957. meshes.forEach(function (mesh, index, array) {
  21958. var boundingBox = mesh.getBoundingInfo().boundingBox;
  21959. if (!minVector) {
  21960. minVector = boundingBox.minimumWorld;
  21961. maxVector = boundingBox.maximumWorld;
  21962. }
  21963. else {
  21964. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  21965. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  21966. }
  21967. });
  21968. return {
  21969. min: minVector,
  21970. max: maxVector
  21971. };
  21972. };
  21973. /**
  21974. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  21975. */
  21976. Mesh.Center = function (meshesOrMinMaxVector) {
  21977. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  21978. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  21979. };
  21980. /**
  21981. * Merge the array of meshes into a single mesh for performance reasons.
  21982. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  21983. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  21984. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  21985. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  21986. */
  21987. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass) {
  21988. if (disposeSource === void 0) { disposeSource = true; }
  21989. var index;
  21990. if (!allow32BitsIndices) {
  21991. var totalVertices = 0;
  21992. // Counting vertices
  21993. for (index = 0; index < meshes.length; index++) {
  21994. if (meshes[index]) {
  21995. totalVertices += meshes[index].getTotalVertices();
  21996. if (totalVertices > 65536) {
  21997. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  21998. return null;
  21999. }
  22000. }
  22001. }
  22002. }
  22003. // Merge
  22004. var vertexData;
  22005. var otherVertexData;
  22006. var source;
  22007. for (index = 0; index < meshes.length; index++) {
  22008. if (meshes[index]) {
  22009. meshes[index].computeWorldMatrix(true);
  22010. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  22011. otherVertexData.transform(meshes[index].getWorldMatrix());
  22012. if (vertexData) {
  22013. vertexData.merge(otherVertexData);
  22014. }
  22015. else {
  22016. vertexData = otherVertexData;
  22017. source = meshes[index];
  22018. }
  22019. }
  22020. }
  22021. if (!meshSubclass) {
  22022. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  22023. }
  22024. vertexData.applyToMesh(meshSubclass);
  22025. // Setting properties
  22026. meshSubclass.material = source.material;
  22027. meshSubclass.checkCollisions = source.checkCollisions;
  22028. // Cleaning
  22029. if (disposeSource) {
  22030. for (index = 0; index < meshes.length; index++) {
  22031. if (meshes[index]) {
  22032. meshes[index].dispose();
  22033. }
  22034. }
  22035. }
  22036. return meshSubclass;
  22037. };
  22038. return Mesh;
  22039. }(BABYLON.AbstractMesh));
  22040. // Consts
  22041. Mesh._FRONTSIDE = 0;
  22042. Mesh._BACKSIDE = 1;
  22043. Mesh._DOUBLESIDE = 2;
  22044. Mesh._DEFAULTSIDE = 0;
  22045. Mesh._NO_CAP = 0;
  22046. Mesh._CAP_START = 1;
  22047. Mesh._CAP_END = 2;
  22048. Mesh._CAP_ALL = 3;
  22049. BABYLON.Mesh = Mesh;
  22050. })(BABYLON || (BABYLON = {}));
  22051. //# sourceMappingURL=babylon.mesh.js.map
  22052. var BABYLON;
  22053. (function (BABYLON) {
  22054. var SubMesh = (function () {
  22055. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  22056. if (createBoundingBox === void 0) { createBoundingBox = true; }
  22057. this.materialIndex = materialIndex;
  22058. this.verticesStart = verticesStart;
  22059. this.verticesCount = verticesCount;
  22060. this.indexStart = indexStart;
  22061. this.indexCount = indexCount;
  22062. this._renderId = 0;
  22063. this._mesh = mesh;
  22064. this._renderingMesh = renderingMesh || mesh;
  22065. mesh.subMeshes.push(this);
  22066. this._trianglePlanes = [];
  22067. this._id = mesh.subMeshes.length - 1;
  22068. if (createBoundingBox) {
  22069. this.refreshBoundingInfo();
  22070. mesh.computeWorldMatrix(true);
  22071. }
  22072. }
  22073. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  22074. get: function () {
  22075. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  22076. },
  22077. enumerable: true,
  22078. configurable: true
  22079. });
  22080. SubMesh.prototype.getBoundingInfo = function () {
  22081. if (this.IsGlobal) {
  22082. return this._mesh.getBoundingInfo();
  22083. }
  22084. return this._boundingInfo;
  22085. };
  22086. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  22087. this._boundingInfo = boundingInfo;
  22088. };
  22089. SubMesh.prototype.getMesh = function () {
  22090. return this._mesh;
  22091. };
  22092. SubMesh.prototype.getRenderingMesh = function () {
  22093. return this._renderingMesh;
  22094. };
  22095. SubMesh.prototype.getMaterial = function () {
  22096. var rootMaterial = this._renderingMesh.material;
  22097. if (rootMaterial && rootMaterial instanceof BABYLON.MultiMaterial) {
  22098. var multiMaterial = rootMaterial;
  22099. return multiMaterial.getSubMaterial(this.materialIndex);
  22100. }
  22101. if (!rootMaterial) {
  22102. return this._mesh.getScene().defaultMaterial;
  22103. }
  22104. return rootMaterial;
  22105. };
  22106. // Methods
  22107. SubMesh.prototype.refreshBoundingInfo = function () {
  22108. this._lastColliderWorldVertices = null;
  22109. if (this.IsGlobal) {
  22110. return;
  22111. }
  22112. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22113. if (!data) {
  22114. this._boundingInfo = this._mesh._boundingInfo;
  22115. return;
  22116. }
  22117. var indices = this._renderingMesh.getIndices();
  22118. var extend;
  22119. //is this the only submesh?
  22120. if (this.indexStart === 0 && this.indexCount === indices.length) {
  22121. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  22122. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  22123. }
  22124. else {
  22125. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  22126. }
  22127. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  22128. };
  22129. SubMesh.prototype._checkCollision = function (collider) {
  22130. return this.getBoundingInfo()._checkCollision(collider);
  22131. };
  22132. SubMesh.prototype.updateBoundingInfo = function (world) {
  22133. if (!this.getBoundingInfo()) {
  22134. this.refreshBoundingInfo();
  22135. }
  22136. this.getBoundingInfo().update(world);
  22137. };
  22138. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  22139. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  22140. };
  22141. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  22142. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  22143. };
  22144. SubMesh.prototype.render = function (enableAlphaMode) {
  22145. this._renderingMesh.render(this, enableAlphaMode);
  22146. };
  22147. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  22148. if (!this._linesIndexBuffer) {
  22149. var linesIndices = [];
  22150. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22151. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  22152. }
  22153. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  22154. this.linesIndexCount = linesIndices.length;
  22155. }
  22156. return this._linesIndexBuffer;
  22157. };
  22158. SubMesh.prototype.canIntersects = function (ray) {
  22159. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  22160. };
  22161. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  22162. var intersectInfo = null;
  22163. // LineMesh first as it's also a Mesh...
  22164. if (this._mesh instanceof BABYLON.LinesMesh) {
  22165. var lineMesh = this._mesh;
  22166. // Line test
  22167. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  22168. var p0 = positions[indices[index]];
  22169. var p1 = positions[indices[index + 1]];
  22170. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  22171. if (length < 0) {
  22172. continue;
  22173. }
  22174. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  22175. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  22176. if (fastCheck) {
  22177. break;
  22178. }
  22179. }
  22180. }
  22181. }
  22182. else {
  22183. // Triangles test
  22184. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  22185. var p0 = positions[indices[index]];
  22186. var p1 = positions[indices[index + 1]];
  22187. var p2 = positions[indices[index + 2]];
  22188. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  22189. if (currentIntersectInfo) {
  22190. if (currentIntersectInfo.distance < 0) {
  22191. continue;
  22192. }
  22193. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  22194. intersectInfo = currentIntersectInfo;
  22195. intersectInfo.faceId = index / 3;
  22196. if (fastCheck) {
  22197. break;
  22198. }
  22199. }
  22200. }
  22201. }
  22202. }
  22203. return intersectInfo;
  22204. };
  22205. // Clone
  22206. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  22207. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  22208. if (!this.IsGlobal) {
  22209. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  22210. }
  22211. return result;
  22212. };
  22213. // Dispose
  22214. SubMesh.prototype.dispose = function () {
  22215. if (this._linesIndexBuffer) {
  22216. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  22217. this._linesIndexBuffer = null;
  22218. }
  22219. // Remove from mesh
  22220. var index = this._mesh.subMeshes.indexOf(this);
  22221. this._mesh.subMeshes.splice(index, 1);
  22222. };
  22223. // Statics
  22224. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  22225. var minVertexIndex = Number.MAX_VALUE;
  22226. var maxVertexIndex = -Number.MAX_VALUE;
  22227. renderingMesh = renderingMesh || mesh;
  22228. var indices = renderingMesh.getIndices();
  22229. for (var index = startIndex; index < startIndex + indexCount; index++) {
  22230. var vertexIndex = indices[index];
  22231. if (vertexIndex < minVertexIndex)
  22232. minVertexIndex = vertexIndex;
  22233. if (vertexIndex > maxVertexIndex)
  22234. maxVertexIndex = vertexIndex;
  22235. }
  22236. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  22237. };
  22238. return SubMesh;
  22239. }());
  22240. BABYLON.SubMesh = SubMesh;
  22241. })(BABYLON || (BABYLON = {}));
  22242. //# sourceMappingURL=babylon.subMesh.js.map
  22243. var BABYLON;
  22244. (function (BABYLON) {
  22245. var MeshBuilder = (function () {
  22246. function MeshBuilder() {
  22247. }
  22248. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  22249. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  22250. return BABYLON.Mesh.DOUBLESIDE;
  22251. }
  22252. if (orientation === undefined || orientation === null) {
  22253. return BABYLON.Mesh.FRONTSIDE;
  22254. }
  22255. return orientation;
  22256. };
  22257. /**
  22258. * Creates a box mesh.
  22259. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  22260. * The parameter `size` sets the size (float) of each box side (default 1).
  22261. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  22262. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of 6 Color3 elements) and `faceUV` (an array of 6 Vector4 elements).
  22263. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  22264. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22265. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22266. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22267. */
  22268. MeshBuilder.CreateBox = function (name, options, scene) {
  22269. var box = new BABYLON.Mesh(name, scene);
  22270. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22271. box.sideOrientation = options.sideOrientation;
  22272. var vertexData = BABYLON.VertexData.CreateBox(options);
  22273. vertexData.applyToMesh(box, options.updatable);
  22274. return box;
  22275. };
  22276. /**
  22277. * Creates a sphere mesh.
  22278. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  22279. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22280. * You can set some different sphere dimensions, for instance to build an ellipsoid, by using the parameters `diameterX`, `diameterY` and `diameterZ` (all by default have the same value than `diameter`).
  22281. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22282. * You can create an unclosed sphere with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference (latitude) : 2 x PI x ratio
  22283. * You can create an unclosed sphere on its height with the parameter `slice` (positive float, default1), valued between 0 and 1, what is the height ratio (longitude).
  22284. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22285. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22286. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22287. */
  22288. MeshBuilder.CreateSphere = function (name, options, scene) {
  22289. var sphere = new BABYLON.Mesh(name, scene);
  22290. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22291. sphere.sideOrientation = options.sideOrientation;
  22292. var vertexData = BABYLON.VertexData.CreateSphere(options);
  22293. vertexData.applyToMesh(sphere, options.updatable);
  22294. return sphere;
  22295. };
  22296. /**
  22297. * Creates a plane polygonal mesh. By default, this is a disc.
  22298. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  22299. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22300. * The parameter `tessellation` sets the number of polygon sides (positive integer, default 64). So a tessellation valued to 3 will build a triangle, to 4 a square, etc.
  22301. * You can create an unclosed polygon with the parameter `arc` (positive float, default 1), valued between 0 and 1, what is the ratio of the circumference : 2 x PI x ratio
  22302. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22303. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22304. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22305. */
  22306. MeshBuilder.CreateDisc = function (name, options, scene) {
  22307. var disc = new BABYLON.Mesh(name, scene);
  22308. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22309. disc.sideOrientation = options.sideOrientation;
  22310. var vertexData = BABYLON.VertexData.CreateDisc(options);
  22311. vertexData.applyToMesh(disc, options.updatable);
  22312. return disc;
  22313. };
  22314. /**
  22315. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  22316. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  22317. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  22318. * You can set some different icosphere dimensions, for instance to build an ellipsoid, by using the parameters `radiusX`, `radiusY` and `radiusZ` (all by default have the same value than `radius`).
  22319. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  22320. * The parameter `flat` (boolean, default true) gives each side its own normals. Set it to false to get a smooth continuous light reflection on the surface.
  22321. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22322. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22323. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22324. */
  22325. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  22326. var sphere = new BABYLON.Mesh(name, scene);
  22327. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22328. sphere.sideOrientation = options.sideOrientation;
  22329. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  22330. vertexData.applyToMesh(sphere, options.updatable);
  22331. return sphere;
  22332. };
  22333. ;
  22334. /**
  22335. * Creates a ribbon mesh.
  22336. * The ribbon is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  22337. *
  22338. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22339. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22340. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22341. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22342. * The parameter `offset` (positive integer, default : rounded half size of the pathArray length), is taken in account only if the `pathArray` is containing a single path.
  22343. * It's the offset to join the points from the same path. Ex : offset = 10 means the point 1 is joined to the point 11.
  22344. * The optional parameter `instance` is an instance of an existing Ribbon object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#ribbon
  22345. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22346. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22347. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22348. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22349. */
  22350. MeshBuilder.CreateRibbon = function (name, options, scene) {
  22351. var pathArray = options.pathArray;
  22352. var closeArray = options.closeArray;
  22353. var closePath = options.closePath;
  22354. var offset = options.offset;
  22355. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22356. var instance = options.instance;
  22357. var updatable = options.updatable;
  22358. if (instance) {
  22359. // positionFunction : ribbon case
  22360. // only pathArray and sideOrientation parameters are taken into account for positions update
  22361. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  22362. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  22363. var positionFunction = function (positions) {
  22364. var minlg = pathArray[0].length;
  22365. var i = 0;
  22366. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  22367. for (var si = 1; si <= ns; si++) {
  22368. for (var p = 0; p < pathArray.length; p++) {
  22369. var path = pathArray[p];
  22370. var l = path.length;
  22371. minlg = (minlg < l) ? minlg : l;
  22372. var j = 0;
  22373. while (j < minlg) {
  22374. positions[i] = path[j].x;
  22375. positions[i + 1] = path[j].y;
  22376. positions[i + 2] = path[j].z;
  22377. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  22378. BABYLON.Tmp.Vector3[0].x = path[j].x;
  22379. }
  22380. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  22381. BABYLON.Tmp.Vector3[1].x = path[j].x;
  22382. }
  22383. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  22384. BABYLON.Tmp.Vector3[0].y = path[j].y;
  22385. }
  22386. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  22387. BABYLON.Tmp.Vector3[1].y = path[j].y;
  22388. }
  22389. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  22390. BABYLON.Tmp.Vector3[0].z = path[j].z;
  22391. }
  22392. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  22393. BABYLON.Tmp.Vector3[1].z = path[j].z;
  22394. }
  22395. j++;
  22396. i += 3;
  22397. }
  22398. if (instance._closePath) {
  22399. positions[i] = path[0].x;
  22400. positions[i + 1] = path[0].y;
  22401. positions[i + 2] = path[0].z;
  22402. i += 3;
  22403. }
  22404. }
  22405. }
  22406. };
  22407. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22408. positionFunction(positions);
  22409. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  22410. instance._boundingInfo.update(instance._worldMatrix);
  22411. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  22412. if (!(instance.areNormalsFrozen)) {
  22413. var indices = instance.getIndices();
  22414. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22415. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  22416. if (instance._closePath) {
  22417. var indexFirst = 0;
  22418. var indexLast = 0;
  22419. for (var p = 0; p < pathArray.length; p++) {
  22420. indexFirst = instance._idx[p] * 3;
  22421. if (p + 1 < pathArray.length) {
  22422. indexLast = (instance._idx[p + 1] - 1) * 3;
  22423. }
  22424. else {
  22425. indexLast = normals.length - 3;
  22426. }
  22427. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  22428. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  22429. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  22430. normals[indexLast] = normals[indexFirst];
  22431. normals[indexLast + 1] = normals[indexFirst + 1];
  22432. normals[indexLast + 2] = normals[indexFirst + 2];
  22433. }
  22434. }
  22435. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  22436. }
  22437. return instance;
  22438. }
  22439. else {
  22440. var ribbon = new BABYLON.Mesh(name, scene);
  22441. ribbon.sideOrientation = sideOrientation;
  22442. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  22443. if (closePath) {
  22444. ribbon._idx = vertexData._idx;
  22445. }
  22446. ribbon._closePath = closePath;
  22447. ribbon._closeArray = closeArray;
  22448. vertexData.applyToMesh(ribbon, updatable);
  22449. return ribbon;
  22450. }
  22451. };
  22452. /**
  22453. * Creates a cylinder or a cone mesh.
  22454. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  22455. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22456. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22457. * The parameters `diameterTop` and `diameterBottom` overwrite the parameter `diameter` and set respectively the top cap and bottom cap diameter (floats, default 1). The parameter "diameterBottom" can't be zero.
  22458. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22459. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22460. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  22461. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  22462. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  22463. * You can set different colors and different images to each box side by using the parameters `faceColors` (an array of n Color3 elements) and `faceUV` (an array of n Vector4 elements).
  22464. * The value of n is the number of cylinder faces. If the cylinder has only 1 subdivisions, n equals : top face + cylinder surface + bottom face = 3
  22465. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  22466. * Finally, if the cylinder has 5 independent subdivisions and is enclose, n equals : top face + 5 x (stripe surface + 2 closing faces) + bottom face = 2 + 5 * 3 = 17
  22467. * Each array (color or UVs) is always ordered the same way : the first element is the bottom cap, the last element is the top cap. The other elements are each a ring surface.
  22468. * If `enclose` is false, a ring surface is one element.
  22469. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  22470. * Example how to set colors and textures on a sliced cylinder : http://www.html5gamedevs.com/topic/17945-creating-a-closed-slice-of-a-cylinder/#comment-106379
  22471. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22472. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22473. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22474. */
  22475. MeshBuilder.CreateCylinder = function (name, options, scene) {
  22476. var cylinder = new BABYLON.Mesh(name, scene);
  22477. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22478. cylinder.sideOrientation = options.sideOrientation;
  22479. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  22480. vertexData.applyToMesh(cylinder, options.updatable);
  22481. return cylinder;
  22482. };
  22483. /**
  22484. * Creates a torus mesh.
  22485. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  22486. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22487. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22488. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22489. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22490. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22491. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22492. */
  22493. MeshBuilder.CreateTorus = function (name, options, scene) {
  22494. var torus = new BABYLON.Mesh(name, scene);
  22495. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22496. torus.sideOrientation = options.sideOrientation;
  22497. var vertexData = BABYLON.VertexData.CreateTorus(options);
  22498. vertexData.applyToMesh(torus, options.updatable);
  22499. return torus;
  22500. };
  22501. /**
  22502. * Creates a torus knot mesh.
  22503. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  22504. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  22505. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  22506. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  22507. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  22508. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22509. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22510. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22511. */
  22512. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  22513. var torusKnot = new BABYLON.Mesh(name, scene);
  22514. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22515. torusKnot.sideOrientation = options.sideOrientation;
  22516. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  22517. vertexData.applyToMesh(torusKnot, options.updatable);
  22518. return torusKnot;
  22519. };
  22520. /**
  22521. * Creates a line system mesh.
  22522. * A line system is a pool of many lines gathered in a single mesh.
  22523. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  22524. * A line system mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of lines as an input parameter.
  22525. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  22526. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  22527. * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter. The way to update it is the same than for
  22528. * updating a simple Line mesh, you just need to update every line in the `lines` array : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  22529. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  22530. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22531. */
  22532. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  22533. var instance = options.instance;
  22534. var lines = options.lines;
  22535. if (instance) {
  22536. var positionFunction = function (positions) {
  22537. var i = 0;
  22538. for (var l = 0; l < lines.length; l++) {
  22539. var points = lines[l];
  22540. for (var p = 0; p < points.length; p++) {
  22541. positions[i] = points[p].x;
  22542. positions[i + 1] = points[p].y;
  22543. positions[i + 2] = points[p].z;
  22544. i += 3;
  22545. }
  22546. }
  22547. };
  22548. instance.updateMeshPositions(positionFunction, false);
  22549. return instance;
  22550. }
  22551. // line system creation
  22552. var lineSystem = new BABYLON.LinesMesh(name, scene);
  22553. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  22554. vertexData.applyToMesh(lineSystem, options.updatable);
  22555. return lineSystem;
  22556. };
  22557. /**
  22558. * Creates a line mesh.
  22559. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  22560. * A line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  22561. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22562. * The parameter `points` is an array successive Vector3.
  22563. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  22564. * When updating an instance, remember that only point positions can change, not the number of points.
  22565. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22566. */
  22567. MeshBuilder.CreateLines = function (name, options, scene) {
  22568. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  22569. return lines;
  22570. };
  22571. /**
  22572. * Creates a dashed line mesh.
  22573. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  22574. * A dashed line mesh is considered as a parametric shape since it has no predefined original shape. Its shape is determined by the passed array of points as an input parameter.
  22575. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  22576. * The parameter `points` is an array successive Vector3.
  22577. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  22578. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  22579. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  22580. * The optional parameter `instance` is an instance of an existing LineMesh object to be updated with the passed `points` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#lines-and-dashedlines
  22581. * When updating an instance, remember that only point positions can change, not the number of points.
  22582. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22583. */
  22584. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  22585. var points = options.points;
  22586. var instance = options.instance;
  22587. var gapSize = options.gapSize;
  22588. var dashNb = options.dashNb;
  22589. var dashSize = options.dashSize;
  22590. if (instance) {
  22591. var positionFunction = function (positions) {
  22592. var curvect = BABYLON.Vector3.Zero();
  22593. var nbSeg = positions.length / 6;
  22594. var lg = 0;
  22595. var nb = 0;
  22596. var shft = 0;
  22597. var dashshft = 0;
  22598. var curshft = 0;
  22599. var p = 0;
  22600. var i = 0;
  22601. var j = 0;
  22602. for (i = 0; i < points.length - 1; i++) {
  22603. points[i + 1].subtractToRef(points[i], curvect);
  22604. lg += curvect.length();
  22605. }
  22606. shft = lg / nbSeg;
  22607. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  22608. for (i = 0; i < points.length - 1; i++) {
  22609. points[i + 1].subtractToRef(points[i], curvect);
  22610. nb = Math.floor(curvect.length() / shft);
  22611. curvect.normalize();
  22612. j = 0;
  22613. while (j < nb && p < positions.length) {
  22614. curshft = shft * j;
  22615. positions[p] = points[i].x + curshft * curvect.x;
  22616. positions[p + 1] = points[i].y + curshft * curvect.y;
  22617. positions[p + 2] = points[i].z + curshft * curvect.z;
  22618. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  22619. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  22620. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  22621. p += 6;
  22622. j++;
  22623. }
  22624. }
  22625. while (p < positions.length) {
  22626. positions[p] = points[i].x;
  22627. positions[p + 1] = points[i].y;
  22628. positions[p + 2] = points[i].z;
  22629. p += 3;
  22630. }
  22631. };
  22632. instance.updateMeshPositions(positionFunction, false);
  22633. return instance;
  22634. }
  22635. // dashed lines creation
  22636. var dashedLines = new BABYLON.LinesMesh(name, scene);
  22637. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  22638. vertexData.applyToMesh(dashedLines, options.updatable);
  22639. dashedLines.dashSize = dashSize;
  22640. dashedLines.gapSize = gapSize;
  22641. return dashedLines;
  22642. };
  22643. /**
  22644. * Creates an extruded shape mesh.
  22645. * The extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  22646. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  22647. *
  22648. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22649. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  22650. * extruded along the Z axis.
  22651. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22652. * The parameter `rotation` (float, default 0 radians) is the angle value to rotate the shape each step (each path point), from the former step (so rotation added each step) along the curve.
  22653. * The parameter `scale` (float, default 1) is the value to scale the shape.
  22654. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  22655. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  22656. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22657. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22658. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22659. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22660. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22661. */
  22662. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  22663. var path = options.path;
  22664. var shape = options.shape;
  22665. var scale = options.scale || 1;
  22666. var rotation = options.rotation || 0;
  22667. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22668. var updatable = options.updatable;
  22669. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22670. var instance = options.instance;
  22671. var invertUV = options.invertUV || false;
  22672. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV);
  22673. };
  22674. /**
  22675. * Creates an custom extruded shape mesh.
  22676. * The custom extrusion is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  22677. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  22678. *
  22679. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  22680. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be extruded in its local space : the shape must be designed in the xOy plane and will be
  22681. * extruded along the Z axis.
  22682. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  22683. * The parameter `rotationFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  22684. * and the distance of this point from the begining of the path :
  22685. * ```javascript
  22686. * var rotationFunction = function(i, distance) {
  22687. * // do things
  22688. * return rotationValue; }
  22689. * ```
  22690. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  22691. * The parameter `scaleFunction` (JS function) is a custom Javascript function called on each path point. This function is passed the position i of the point in the path
  22692. * and the distance of this point from the begining of the path :
  22693. * ```javascript
  22694. * var scaleFunction = function(i, distance) {
  22695. * // do things
  22696. * return scaleValue;}
  22697. * ```
  22698. * It must returns a float value that will be the scale value applied to the shape on each path point.
  22699. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  22700. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  22701. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  22702. * The optional parameter `instance` is an instance of an existing ExtrudedShape object to be updated with the passed `shape`, `path`, `scale` or `rotation` parameters : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#extruded-shape
  22703. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  22704. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22705. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22706. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22707. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22708. */
  22709. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  22710. var path = options.path;
  22711. var shape = options.shape;
  22712. var scaleFunction = options.scaleFunction || (function () { return 1; });
  22713. var rotationFunction = options.rotationFunction || (function () { return 0; });
  22714. var ribbonCloseArray = options.ribbonCloseArray || false;
  22715. var ribbonClosePath = options.ribbonClosePath || false;
  22716. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  22717. var updatable = options.updatable;
  22718. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22719. var instance = options.instance;
  22720. var invertUV = options.invertUV || false;
  22721. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV);
  22722. };
  22723. /**
  22724. * Creates lathe mesh.
  22725. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  22726. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  22727. *
  22728. * The parameter `shape` is a required array of successive Vector3. This array depicts the shape to be rotated in its local space : the shape must be designed in the xOy plane and will be
  22729. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  22730. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  22731. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  22732. * The parameter `arc` (positive float, default 1) is the ratio of the lathe. 0.5 builds for instance half a lathe, so an opened shape.
  22733. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  22734. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  22735. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22736. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22737. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22738. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22739. */
  22740. MeshBuilder.CreateLathe = function (name, options, scene) {
  22741. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  22742. var closed = (options.closed === undefined) ? true : options.closed;
  22743. var shape = options.shape;
  22744. var radius = options.radius || 1;
  22745. var tessellation = options.tessellation || 64;
  22746. var updatable = options.updatable;
  22747. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22748. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22749. var pi2 = Math.PI * 2;
  22750. var paths = new Array();
  22751. var invertUV = options.invertUV || false;
  22752. var i = 0;
  22753. var p = 0;
  22754. var step = pi2 / tessellation * arc;
  22755. var rotated;
  22756. var path = new Array();
  22757. ;
  22758. for (i = 0; i <= tessellation; i++) {
  22759. var path = [];
  22760. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  22761. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  22762. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  22763. }
  22764. for (p = 0; p < shape.length; p++) {
  22765. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  22766. path.push(rotated);
  22767. }
  22768. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  22769. 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));
  22770. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  22771. }
  22772. paths.push(path);
  22773. }
  22774. // lathe ribbon
  22775. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV }, scene);
  22776. return lathe;
  22777. };
  22778. /**
  22779. * Creates a plane mesh.
  22780. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22781. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  22782. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  22783. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  22784. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22785. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22786. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22787. */
  22788. MeshBuilder.CreatePlane = function (name, options, scene) {
  22789. var plane = new BABYLON.Mesh(name, scene);
  22790. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22791. plane.sideOrientation = options.sideOrientation;
  22792. var vertexData = BABYLON.VertexData.CreatePlane(options);
  22793. vertexData.applyToMesh(plane, options.updatable);
  22794. if (options.sourcePlane) {
  22795. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  22796. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  22797. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  22798. plane.rotate(vectorProduct, product);
  22799. }
  22800. return plane;
  22801. };
  22802. /**
  22803. * Creates a ground mesh.
  22804. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  22805. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  22806. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  22807. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22808. */
  22809. MeshBuilder.CreateGround = function (name, options, scene) {
  22810. var ground = new BABYLON.GroundMesh(name, scene);
  22811. ground._setReady(false);
  22812. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  22813. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  22814. ground._width = options.width || 1;
  22815. ground._height = options.height || 1;
  22816. ground._maxX = ground._width / 2;
  22817. ground._maxZ = ground._height / 2;
  22818. ground._minX = -ground._maxX;
  22819. ground._minZ = -ground._maxZ;
  22820. var vertexData = BABYLON.VertexData.CreateGround(options);
  22821. vertexData.applyToMesh(ground, options.updatable);
  22822. ground._setReady(true);
  22823. return ground;
  22824. };
  22825. /**
  22826. * Creates a tiled ground mesh.
  22827. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  22828. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  22829. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  22830. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  22831. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  22832. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  22833. * numbers of subdivisions on the ground width and height of each tile.
  22834. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22835. */
  22836. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  22837. var tiledGround = new BABYLON.Mesh(name, scene);
  22838. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  22839. vertexData.applyToMesh(tiledGround, options.updatable);
  22840. return tiledGround;
  22841. };
  22842. /**
  22843. * Creates a ground mesh from a height map.
  22844. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  22845. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  22846. * The parameter `url` sets the URL of the height map image resource.
  22847. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  22848. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  22849. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  22850. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  22851. * The parameter `onReady` is a javascript callback function that will be called once the mesh is just built (the height map download can last some time).
  22852. * This function is passed the newly built mesh :
  22853. * ```javascript
  22854. * function(mesh) { // do things
  22855. * return; }
  22856. * ```
  22857. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22858. */
  22859. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  22860. var width = options.width || 10.0;
  22861. var height = options.height || 10.0;
  22862. var subdivisions = options.subdivisions || 1 | 0;
  22863. var minHeight = options.minHeight || 0.0;
  22864. var maxHeight = options.maxHeight || 10.0;
  22865. var updatable = options.updatable;
  22866. var onReady = options.onReady;
  22867. var ground = new BABYLON.GroundMesh(name, scene);
  22868. ground._subdivisionsX = subdivisions;
  22869. ground._subdivisionsY = subdivisions;
  22870. ground._width = width;
  22871. ground._height = height;
  22872. ground._maxX = ground._width / 2.0;
  22873. ground._maxZ = ground._height / 2.0;
  22874. ground._minX = -ground._maxX;
  22875. ground._minZ = -ground._maxZ;
  22876. ground._setReady(false);
  22877. var onload = function (img) {
  22878. // Getting height map data
  22879. var canvas = document.createElement("canvas");
  22880. var context = canvas.getContext("2d");
  22881. var bufferWidth = img.width;
  22882. var bufferHeight = img.height;
  22883. canvas.width = bufferWidth;
  22884. canvas.height = bufferHeight;
  22885. context.drawImage(img, 0, 0);
  22886. // Create VertexData from map data
  22887. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22888. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  22889. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  22890. width: width, height: height,
  22891. subdivisions: subdivisions,
  22892. minHeight: minHeight, maxHeight: maxHeight,
  22893. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  22894. });
  22895. vertexData.applyToMesh(ground, updatable);
  22896. ground._setReady(true);
  22897. //execute ready callback, if set
  22898. if (onReady) {
  22899. onReady(ground);
  22900. }
  22901. };
  22902. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22903. return ground;
  22904. };
  22905. /**
  22906. * Creates a tube mesh.
  22907. * The tube is a parametric shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes. It has no predefined shape. Its final shape will depend on the input parameters.
  22908. *
  22909. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  22910. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  22911. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  22912. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  22913. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  22914. * This function is called on each point of the tube path and is passed the index `i` of the i-th point and the distance of this point from the first point of the path.
  22915. * It must return a radius value (positive float) :
  22916. * ```javascript
  22917. * var radiusFunction = function(i, distance) {
  22918. * // do things
  22919. * return radius; }
  22920. * ```
  22921. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  22922. * The parameter `cap` sets the way the extruded shape is capped. Possible values : BABYLON.Mesh.NO_CAP (default), BABYLON.Mesh.CAP_START, BABYLON.Mesh.CAP_END, BABYLON.Mesh.CAP_ALL
  22923. * The optional parameter `instance` is an instance of an existing Tube object to be updated with the passed `pathArray` parameter : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#tube
  22924. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22925. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22926. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  22927. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22928. */
  22929. MeshBuilder.CreateTube = function (name, options, scene) {
  22930. var path = options.path;
  22931. var radius = options.radius || 1.0;
  22932. var tessellation = options.tessellation || 64 | 0;
  22933. var radiusFunction = options.radiusFunction;
  22934. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  22935. var invertUV = options.invertUV || false;
  22936. var updatable = options.updatable;
  22937. var sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  22938. var instance = options.instance;
  22939. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  22940. // tube geometry
  22941. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  22942. var tangents = path3D.getTangents();
  22943. var normals = path3D.getNormals();
  22944. var distances = path3D.getDistances();
  22945. var pi2 = Math.PI * 2;
  22946. var step = pi2 / tessellation * arc;
  22947. var returnRadius = function () { return radius; };
  22948. var radiusFunctionFinal = radiusFunction || returnRadius;
  22949. var circlePath;
  22950. var rad;
  22951. var normal;
  22952. var rotated;
  22953. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  22954. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  22955. for (var i = 0; i < path.length; i++) {
  22956. rad = radiusFunctionFinal(i, distances[i]); // current radius
  22957. circlePath = Array(); // current circle array
  22958. normal = normals[i]; // current normal
  22959. for (var t = 0; t < tessellation; t++) {
  22960. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  22961. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  22962. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  22963. rotated.scaleInPlace(rad).addInPlace(path[i]);
  22964. circlePath[t] = rotated;
  22965. }
  22966. circlePaths[index] = circlePath;
  22967. index++;
  22968. }
  22969. // cap
  22970. var capPath = function (nbPoints, pathIndex) {
  22971. var pointCap = Array();
  22972. for (var i = 0; i < nbPoints; i++) {
  22973. pointCap.push(path[pathIndex]);
  22974. }
  22975. return pointCap;
  22976. };
  22977. switch (cap) {
  22978. case BABYLON.Mesh.NO_CAP:
  22979. break;
  22980. case BABYLON.Mesh.CAP_START:
  22981. circlePaths[0] = capPath(tessellation, 0);
  22982. circlePaths[1] = circlePaths[2].slice(0);
  22983. break;
  22984. case BABYLON.Mesh.CAP_END:
  22985. circlePaths[index] = circlePaths[index - 1].slice(0);
  22986. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22987. break;
  22988. case BABYLON.Mesh.CAP_ALL:
  22989. circlePaths[0] = capPath(tessellation, 0);
  22990. circlePaths[1] = circlePaths[2].slice(0);
  22991. circlePaths[index] = circlePaths[index - 1].slice(0);
  22992. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  22993. break;
  22994. default:
  22995. break;
  22996. }
  22997. return circlePaths;
  22998. };
  22999. var path3D;
  23000. var pathArray;
  23001. if (instance) {
  23002. var arc = options.arc || instance.arc;
  23003. path3D = (instance.path3D).update(path);
  23004. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  23005. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  23006. instance.path3D = path3D;
  23007. instance.pathArray = pathArray;
  23008. instance.arc = arc;
  23009. return instance;
  23010. }
  23011. // tube creation
  23012. path3D = new BABYLON.Path3D(path);
  23013. var newPathArray = new Array();
  23014. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23015. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  23016. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV }, scene);
  23017. tube.pathArray = pathArray;
  23018. tube.path3D = path3D;
  23019. tube.tessellation = tessellation;
  23020. tube.cap = cap;
  23021. tube.arc = options.arc;
  23022. return tube;
  23023. };
  23024. /**
  23025. * Creates a polyhedron mesh.
  23026. *
  23027. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  23028. * The parameter `type` (positive integer, max 14, default 0) sets the polyhedron type to build among the 15 embbeded types. Please refer to the type sheet in the tutorial
  23029. * to choose the wanted type.
  23030. * The parameter `size` (positive float, default 1) sets the polygon size.
  23031. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23032. * You can build other polyhedron types than the 15 embbeded ones by setting the parameter `custom` (`polyhedronObject`, default null). If you set the parameter `custom`, this overwrittes the parameter `type`.
  23033. * A `polyhedronObject` is a formatted javascript object. You'll find a full file with pre-set polyhedra here : https://github.com/BabylonJS/Extensions/tree/master/Polyhedron
  23034. * You can set the color and the UV of each side of the polyhedron with the parameters `faceColors` (Color4, default `(1, 1, 1, 1)`) and faceUV (Vector4, default `(0, 0, 1, 1)`).
  23035. * To understand how to set `faceUV` or `faceColors`, please read this by considering the right number of faces of your polyhedron, instead of only 6 for the box : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  23036. * The parameter `flat` (boolean, default true). If set to false, it gives the polyhedron a single global face, so less vertices and shared normals. In this case, `faceColors` and `faceUV` are ignored.
  23037. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23038. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23039. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23040. */
  23041. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  23042. var polyhedron = new BABYLON.Mesh(name, scene);
  23043. options.sideOrientation = this.updateSideOrientation(options.sideOrientation, scene);
  23044. polyhedron.sideOrientation = options.sideOrientation;
  23045. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  23046. vertexData.applyToMesh(polyhedron, options.updatable);
  23047. return polyhedron;
  23048. };
  23049. /**
  23050. * Creates a decal mesh.
  23051. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  23052. * A decal is a mesh usually applied as a model onto the surface of another mesh. So don't forget the parameter `sourceMesh` depicting the decal.
  23053. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23054. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23055. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23056. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23057. */
  23058. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  23059. var indices = sourceMesh.getIndices();
  23060. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23061. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23062. var position = options.position || BABYLON.Vector3.Zero();
  23063. var normal = options.normal || BABYLON.Vector3.Up();
  23064. var size = options.size || new BABYLON.Vector3(1, 1, 1);
  23065. var angle = options.angle || 0;
  23066. // Getting correct rotation
  23067. if (!normal) {
  23068. var target = new BABYLON.Vector3(0, 0, 1);
  23069. var camera = sourceMesh.getScene().activeCamera;
  23070. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  23071. normal = camera.globalPosition.subtract(cameraWorldTarget);
  23072. }
  23073. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  23074. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  23075. var pitch = Math.atan2(normal.y, len);
  23076. // Matrix
  23077. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  23078. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  23079. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  23080. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  23081. var vertexData = new BABYLON.VertexData();
  23082. vertexData.indices = [];
  23083. vertexData.positions = [];
  23084. vertexData.normals = [];
  23085. vertexData.uvs = [];
  23086. var currentVertexDataIndex = 0;
  23087. var extractDecalVector3 = function (indexId) {
  23088. var vertexId = indices[indexId];
  23089. var result = new BABYLON.PositionNormalVertex();
  23090. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  23091. // Send vector to decal local world
  23092. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  23093. // Get normal
  23094. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  23095. return result;
  23096. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  23097. var clip = function (vertices, axis) {
  23098. if (vertices.length === 0) {
  23099. return vertices;
  23100. }
  23101. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  23102. var clipVertices = function (v0, v1) {
  23103. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  23104. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  23105. };
  23106. var result = new Array();
  23107. for (var index = 0; index < vertices.length; index += 3) {
  23108. var v1Out;
  23109. var v2Out;
  23110. var v3Out;
  23111. var total = 0;
  23112. var nV1, nV2, nV3, nV4;
  23113. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  23114. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  23115. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  23116. v1Out = d1 > 0;
  23117. v2Out = d2 > 0;
  23118. v3Out = d3 > 0;
  23119. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  23120. switch (total) {
  23121. case 0:
  23122. result.push(vertices[index]);
  23123. result.push(vertices[index + 1]);
  23124. result.push(vertices[index + 2]);
  23125. break;
  23126. case 1:
  23127. if (v1Out) {
  23128. nV1 = vertices[index + 1];
  23129. nV2 = vertices[index + 2];
  23130. nV3 = clipVertices(vertices[index], nV1);
  23131. nV4 = clipVertices(vertices[index], nV2);
  23132. }
  23133. if (v2Out) {
  23134. nV1 = vertices[index];
  23135. nV2 = vertices[index + 2];
  23136. nV3 = clipVertices(vertices[index + 1], nV1);
  23137. nV4 = clipVertices(vertices[index + 1], nV2);
  23138. result.push(nV3);
  23139. result.push(nV2.clone());
  23140. result.push(nV1.clone());
  23141. result.push(nV2.clone());
  23142. result.push(nV3.clone());
  23143. result.push(nV4);
  23144. break;
  23145. }
  23146. if (v3Out) {
  23147. nV1 = vertices[index];
  23148. nV2 = vertices[index + 1];
  23149. nV3 = clipVertices(vertices[index + 2], nV1);
  23150. nV4 = clipVertices(vertices[index + 2], nV2);
  23151. }
  23152. result.push(nV1.clone());
  23153. result.push(nV2.clone());
  23154. result.push(nV3);
  23155. result.push(nV4);
  23156. result.push(nV3.clone());
  23157. result.push(nV2.clone());
  23158. break;
  23159. case 2:
  23160. if (!v1Out) {
  23161. nV1 = vertices[index].clone();
  23162. nV2 = clipVertices(nV1, vertices[index + 1]);
  23163. nV3 = clipVertices(nV1, vertices[index + 2]);
  23164. result.push(nV1);
  23165. result.push(nV2);
  23166. result.push(nV3);
  23167. }
  23168. if (!v2Out) {
  23169. nV1 = vertices[index + 1].clone();
  23170. nV2 = clipVertices(nV1, vertices[index + 2]);
  23171. nV3 = clipVertices(nV1, vertices[index]);
  23172. result.push(nV1);
  23173. result.push(nV2);
  23174. result.push(nV3);
  23175. }
  23176. if (!v3Out) {
  23177. nV1 = vertices[index + 2].clone();
  23178. nV2 = clipVertices(nV1, vertices[index]);
  23179. nV3 = clipVertices(nV1, vertices[index + 1]);
  23180. result.push(nV1);
  23181. result.push(nV2);
  23182. result.push(nV3);
  23183. }
  23184. break;
  23185. case 3:
  23186. break;
  23187. }
  23188. }
  23189. return result;
  23190. };
  23191. for (var index = 0; index < indices.length; index += 3) {
  23192. var faceVertices = new Array();
  23193. faceVertices.push(extractDecalVector3(index));
  23194. faceVertices.push(extractDecalVector3(index + 1));
  23195. faceVertices.push(extractDecalVector3(index + 2));
  23196. // Clip
  23197. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  23198. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  23199. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  23200. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  23201. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  23202. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  23203. if (faceVertices.length === 0) {
  23204. continue;
  23205. }
  23206. // Add UVs and get back to world
  23207. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  23208. var vertex = faceVertices[vIndex];
  23209. //TODO check for Int32Array
  23210. vertexData.indices.push(currentVertexDataIndex);
  23211. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  23212. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  23213. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  23214. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  23215. currentVertexDataIndex++;
  23216. }
  23217. }
  23218. // Return mesh
  23219. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  23220. vertexData.applyToMesh(decal);
  23221. decal.position = position.clone();
  23222. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  23223. return decal;
  23224. };
  23225. // Privates
  23226. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV) {
  23227. // extrusion geometry
  23228. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  23229. var tangents = path3D.getTangents();
  23230. var normals = path3D.getNormals();
  23231. var binormals = path3D.getBinormals();
  23232. var distances = path3D.getDistances();
  23233. var angle = 0;
  23234. var returnScale = function () { return scale; };
  23235. var returnRotation = function () { return rotation; };
  23236. var rotate = custom ? rotateFunction : returnRotation;
  23237. var scl = custom ? scaleFunction : returnScale;
  23238. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  23239. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  23240. for (var i = 0; i < curve.length; i++) {
  23241. var shapePath = new Array();
  23242. var angleStep = rotate(i, distances[i]);
  23243. var scaleRatio = scl(i, distances[i]);
  23244. for (var p = 0; p < shape.length; p++) {
  23245. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  23246. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  23247. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  23248. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  23249. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  23250. shapePath[p] = rotated;
  23251. }
  23252. shapePaths[index] = shapePath;
  23253. angle += angleStep;
  23254. index++;
  23255. }
  23256. // cap
  23257. var capPath = function (shapePath) {
  23258. var pointCap = Array();
  23259. var barycenter = BABYLON.Vector3.Zero();
  23260. var i;
  23261. for (i = 0; i < shapePath.length; i++) {
  23262. barycenter.addInPlace(shapePath[i]);
  23263. }
  23264. barycenter.scaleInPlace(1 / shapePath.length);
  23265. for (i = 0; i < shapePath.length; i++) {
  23266. pointCap.push(barycenter);
  23267. }
  23268. return pointCap;
  23269. };
  23270. switch (cap) {
  23271. case BABYLON.Mesh.NO_CAP:
  23272. break;
  23273. case BABYLON.Mesh.CAP_START:
  23274. shapePaths[0] = capPath(shapePaths[2]);
  23275. shapePaths[1] = shapePaths[2].slice(0);
  23276. break;
  23277. case BABYLON.Mesh.CAP_END:
  23278. shapePaths[index] = shapePaths[index - 1];
  23279. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23280. break;
  23281. case BABYLON.Mesh.CAP_ALL:
  23282. shapePaths[0] = capPath(shapePaths[2]);
  23283. shapePaths[1] = shapePaths[2].slice(0);
  23284. shapePaths[index] = shapePaths[index - 1];
  23285. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  23286. break;
  23287. default:
  23288. break;
  23289. }
  23290. return shapePaths;
  23291. };
  23292. var path3D;
  23293. var pathArray;
  23294. if (instance) {
  23295. path3D = (instance.path3D).update(curve);
  23296. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  23297. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  23298. return instance;
  23299. }
  23300. // extruded shape creation
  23301. path3D = new BABYLON.Path3D(curve);
  23302. var newShapePaths = new Array();
  23303. cap = (cap < 0 || cap > 3) ? 0 : cap;
  23304. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  23305. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV }, scene);
  23306. extrudedGeneric.pathArray = pathArray;
  23307. extrudedGeneric.path3D = path3D;
  23308. extrudedGeneric.cap = cap;
  23309. return extrudedGeneric;
  23310. };
  23311. return MeshBuilder;
  23312. }());
  23313. BABYLON.MeshBuilder = MeshBuilder;
  23314. })(BABYLON || (BABYLON = {}));
  23315. //# sourceMappingURL=babylon.meshBuilder.js.map
  23316. var BABYLON;
  23317. (function (BABYLON) {
  23318. var BaseTexture = (function () {
  23319. function BaseTexture(scene) {
  23320. this.hasAlpha = false;
  23321. this.getAlphaFromRGB = false;
  23322. this.level = 1;
  23323. this.coordinatesIndex = 0;
  23324. this.coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  23325. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  23326. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  23327. this.anisotropicFilteringLevel = 4;
  23328. this.isCube = false;
  23329. this.isRenderTarget = false;
  23330. this.animations = new Array();
  23331. /**
  23332. * An event triggered when the texture is disposed.
  23333. * @type {BABYLON.Observable}
  23334. */
  23335. this.onDisposeObservable = new BABYLON.Observable();
  23336. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  23337. this._scene = scene;
  23338. this._scene.textures.push(this);
  23339. this._uid = null;
  23340. }
  23341. Object.defineProperty(BaseTexture.prototype, "uid", {
  23342. get: function () {
  23343. if (!this._uid) {
  23344. this._uid = BABYLON.Tools.RandomId();
  23345. }
  23346. return this._uid;
  23347. },
  23348. enumerable: true,
  23349. configurable: true
  23350. });
  23351. BaseTexture.prototype.toString = function () {
  23352. return this.name;
  23353. };
  23354. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  23355. set: function (callback) {
  23356. if (this._onDisposeObserver) {
  23357. this.onDisposeObservable.remove(this._onDisposeObserver);
  23358. }
  23359. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  23360. },
  23361. enumerable: true,
  23362. configurable: true
  23363. });
  23364. BaseTexture.prototype.getScene = function () {
  23365. return this._scene;
  23366. };
  23367. BaseTexture.prototype.getTextureMatrix = function () {
  23368. return null;
  23369. };
  23370. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  23371. return null;
  23372. };
  23373. BaseTexture.prototype.getInternalTexture = function () {
  23374. return this._texture;
  23375. };
  23376. BaseTexture.prototype.isReady = function () {
  23377. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23378. return true;
  23379. }
  23380. if (this._texture) {
  23381. return this._texture.isReady;
  23382. }
  23383. return false;
  23384. };
  23385. BaseTexture.prototype.getSize = function () {
  23386. if (this._texture._width) {
  23387. return new BABYLON.Size(this._texture._width, this._texture._height);
  23388. }
  23389. if (this._texture._size) {
  23390. return new BABYLON.Size(this._texture._size, this._texture._size);
  23391. }
  23392. return BABYLON.Size.Zero();
  23393. };
  23394. BaseTexture.prototype.getBaseSize = function () {
  23395. if (!this.isReady() || !this._texture)
  23396. return BABYLON.Size.Zero();
  23397. if (this._texture._size) {
  23398. return new BABYLON.Size(this._texture._size, this._texture._size);
  23399. }
  23400. return new BABYLON.Size(this._texture._baseWidth, this._texture._baseHeight);
  23401. };
  23402. BaseTexture.prototype.scale = function (ratio) {
  23403. };
  23404. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  23405. get: function () {
  23406. return false;
  23407. },
  23408. enumerable: true,
  23409. configurable: true
  23410. });
  23411. BaseTexture.prototype._removeFromCache = function (url, noMipmap) {
  23412. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23413. for (var index = 0; index < texturesCache.length; index++) {
  23414. var texturesCacheEntry = texturesCache[index];
  23415. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23416. texturesCache.splice(index, 1);
  23417. return;
  23418. }
  23419. }
  23420. };
  23421. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  23422. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  23423. for (var index = 0; index < texturesCache.length; index++) {
  23424. var texturesCacheEntry = texturesCache[index];
  23425. if (texturesCacheEntry.url === url && texturesCacheEntry.noMipmap === noMipmap) {
  23426. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  23427. texturesCacheEntry.references++;
  23428. return texturesCacheEntry;
  23429. }
  23430. }
  23431. }
  23432. return null;
  23433. };
  23434. BaseTexture.prototype.delayLoad = function () {
  23435. };
  23436. BaseTexture.prototype.clone = function () {
  23437. return null;
  23438. };
  23439. BaseTexture.prototype.releaseInternalTexture = function () {
  23440. if (this._texture) {
  23441. this._scene.getEngine().releaseInternalTexture(this._texture);
  23442. delete this._texture;
  23443. }
  23444. };
  23445. BaseTexture.prototype.dispose = function () {
  23446. // Animations
  23447. this.getScene().stopAnimation(this);
  23448. // Remove from scene
  23449. var index = this._scene.textures.indexOf(this);
  23450. if (index >= 0) {
  23451. this._scene.textures.splice(index, 1);
  23452. }
  23453. if (this._texture === undefined) {
  23454. return;
  23455. }
  23456. // Release
  23457. this.releaseInternalTexture();
  23458. // Callback
  23459. this.onDisposeObservable.notifyObservers(this);
  23460. this.onDisposeObservable.clear();
  23461. };
  23462. BaseTexture.prototype.serialize = function () {
  23463. if (!this.name) {
  23464. return null;
  23465. }
  23466. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23467. // Animations
  23468. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23469. return serializationObject;
  23470. };
  23471. return BaseTexture;
  23472. }());
  23473. __decorate([
  23474. BABYLON.serialize()
  23475. ], BaseTexture.prototype, "name", void 0);
  23476. __decorate([
  23477. BABYLON.serialize()
  23478. ], BaseTexture.prototype, "hasAlpha", void 0);
  23479. __decorate([
  23480. BABYLON.serialize()
  23481. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  23482. __decorate([
  23483. BABYLON.serialize()
  23484. ], BaseTexture.prototype, "level", void 0);
  23485. __decorate([
  23486. BABYLON.serialize()
  23487. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  23488. __decorate([
  23489. BABYLON.serialize()
  23490. ], BaseTexture.prototype, "coordinatesMode", void 0);
  23491. __decorate([
  23492. BABYLON.serialize()
  23493. ], BaseTexture.prototype, "wrapU", void 0);
  23494. __decorate([
  23495. BABYLON.serialize()
  23496. ], BaseTexture.prototype, "wrapV", void 0);
  23497. __decorate([
  23498. BABYLON.serialize()
  23499. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  23500. __decorate([
  23501. BABYLON.serialize()
  23502. ], BaseTexture.prototype, "isCube", void 0);
  23503. __decorate([
  23504. BABYLON.serialize()
  23505. ], BaseTexture.prototype, "isRenderTarget", void 0);
  23506. BABYLON.BaseTexture = BaseTexture;
  23507. })(BABYLON || (BABYLON = {}));
  23508. //# sourceMappingURL=babylon.baseTexture.js.map
  23509. var BABYLON;
  23510. (function (BABYLON) {
  23511. var Texture = (function (_super) {
  23512. __extends(Texture, _super);
  23513. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer) {
  23514. if (noMipmap === void 0) { noMipmap = false; }
  23515. if (invertY === void 0) { invertY = true; }
  23516. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23517. if (onLoad === void 0) { onLoad = null; }
  23518. if (onError === void 0) { onError = null; }
  23519. if (buffer === void 0) { buffer = null; }
  23520. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23521. var _this = _super.call(this, scene) || this;
  23522. _this.uOffset = 0;
  23523. _this.vOffset = 0;
  23524. _this.uScale = 1.0;
  23525. _this.vScale = 1.0;
  23526. _this.uAng = 0;
  23527. _this.vAng = 0;
  23528. _this.wAng = 0;
  23529. _this.name = url;
  23530. _this.url = url;
  23531. _this._noMipmap = noMipmap;
  23532. _this._invertY = invertY;
  23533. _this._samplingMode = samplingMode;
  23534. _this._buffer = buffer;
  23535. _this._deleteBuffer = deleteBuffer;
  23536. if (!url) {
  23537. return _this;
  23538. }
  23539. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  23540. var load = function () {
  23541. if (_this._onLoadObservarble && _this._onLoadObservarble.hasObservers()) {
  23542. _this.onLoadObservable.notifyObservers(true);
  23543. }
  23544. if (onLoad) {
  23545. onLoad();
  23546. }
  23547. };
  23548. if (!_this._texture) {
  23549. if (!scene.useDelayedTextureLoading) {
  23550. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer);
  23551. if (deleteBuffer) {
  23552. delete _this._buffer;
  23553. }
  23554. }
  23555. else {
  23556. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23557. _this._delayedOnLoad = load;
  23558. _this._delayedOnError = onError;
  23559. }
  23560. }
  23561. else {
  23562. if (_this._texture.isReady) {
  23563. BABYLON.Tools.SetImmediate(function () { return load(); });
  23564. }
  23565. else {
  23566. _this._texture.onLoadedCallbacks.push(load);
  23567. }
  23568. }
  23569. return _this;
  23570. }
  23571. Object.defineProperty(Texture.prototype, "noMipmap", {
  23572. get: function () {
  23573. return this._noMipmap;
  23574. },
  23575. enumerable: true,
  23576. configurable: true
  23577. });
  23578. Texture.prototype.delayLoad = function () {
  23579. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23580. return;
  23581. }
  23582. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23583. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  23584. if (!this._texture) {
  23585. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer);
  23586. if (this._deleteBuffer) {
  23587. delete this._buffer;
  23588. }
  23589. }
  23590. };
  23591. Texture.prototype.updateSamplingMode = function (samplingMode) {
  23592. if (!this._texture) {
  23593. return;
  23594. }
  23595. this._samplingMode = samplingMode;
  23596. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  23597. };
  23598. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  23599. x *= this.uScale;
  23600. y *= this.vScale;
  23601. x -= 0.5 * this.uScale;
  23602. y -= 0.5 * this.vScale;
  23603. z -= 0.5;
  23604. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  23605. t.x += 0.5 * this.uScale + this.uOffset;
  23606. t.y += 0.5 * this.vScale + this.vOffset;
  23607. t.z += 0.5;
  23608. };
  23609. Texture.prototype.getTextureMatrix = function () {
  23610. if (this.uOffset === this._cachedUOffset &&
  23611. this.vOffset === this._cachedVOffset &&
  23612. this.uScale === this._cachedUScale &&
  23613. this.vScale === this._cachedVScale &&
  23614. this.uAng === this._cachedUAng &&
  23615. this.vAng === this._cachedVAng &&
  23616. this.wAng === this._cachedWAng) {
  23617. return this._cachedTextureMatrix;
  23618. }
  23619. this._cachedUOffset = this.uOffset;
  23620. this._cachedVOffset = this.vOffset;
  23621. this._cachedUScale = this.uScale;
  23622. this._cachedVScale = this.vScale;
  23623. this._cachedUAng = this.uAng;
  23624. this._cachedVAng = this.vAng;
  23625. this._cachedWAng = this.wAng;
  23626. if (!this._cachedTextureMatrix) {
  23627. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23628. this._rowGenerationMatrix = new BABYLON.Matrix();
  23629. this._t0 = BABYLON.Vector3.Zero();
  23630. this._t1 = BABYLON.Vector3.Zero();
  23631. this._t2 = BABYLON.Vector3.Zero();
  23632. }
  23633. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  23634. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  23635. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  23636. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  23637. this._t1.subtractInPlace(this._t0);
  23638. this._t2.subtractInPlace(this._t0);
  23639. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23640. this._cachedTextureMatrix.m[0] = this._t1.x;
  23641. this._cachedTextureMatrix.m[1] = this._t1.y;
  23642. this._cachedTextureMatrix.m[2] = this._t1.z;
  23643. this._cachedTextureMatrix.m[4] = this._t2.x;
  23644. this._cachedTextureMatrix.m[5] = this._t2.y;
  23645. this._cachedTextureMatrix.m[6] = this._t2.z;
  23646. this._cachedTextureMatrix.m[8] = this._t0.x;
  23647. this._cachedTextureMatrix.m[9] = this._t0.y;
  23648. this._cachedTextureMatrix.m[10] = this._t0.z;
  23649. return this._cachedTextureMatrix;
  23650. };
  23651. Texture.prototype.getReflectionTextureMatrix = function () {
  23652. if (this.uOffset === this._cachedUOffset &&
  23653. this.vOffset === this._cachedVOffset &&
  23654. this.uScale === this._cachedUScale &&
  23655. this.vScale === this._cachedVScale &&
  23656. this.coordinatesMode === this._cachedCoordinatesMode) {
  23657. return this._cachedTextureMatrix;
  23658. }
  23659. if (!this._cachedTextureMatrix) {
  23660. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  23661. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  23662. }
  23663. this._cachedCoordinatesMode = this.coordinatesMode;
  23664. switch (this.coordinatesMode) {
  23665. case Texture.PLANAR_MODE:
  23666. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23667. this._cachedTextureMatrix[0] = this.uScale;
  23668. this._cachedTextureMatrix[5] = this.vScale;
  23669. this._cachedTextureMatrix[12] = this.uOffset;
  23670. this._cachedTextureMatrix[13] = this.vOffset;
  23671. break;
  23672. case Texture.PROJECTION_MODE:
  23673. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  23674. this._projectionModeMatrix.m[0] = 0.5;
  23675. this._projectionModeMatrix.m[5] = -0.5;
  23676. this._projectionModeMatrix.m[10] = 0.0;
  23677. this._projectionModeMatrix.m[12] = 0.5;
  23678. this._projectionModeMatrix.m[13] = 0.5;
  23679. this._projectionModeMatrix.m[14] = 1.0;
  23680. this._projectionModeMatrix.m[15] = 1.0;
  23681. this.getScene().getProjectionMatrix().multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  23682. break;
  23683. default:
  23684. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  23685. break;
  23686. }
  23687. return this._cachedTextureMatrix;
  23688. };
  23689. Texture.prototype.clone = function () {
  23690. var _this = this;
  23691. return BABYLON.SerializationHelper.Clone(function () {
  23692. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  23693. }, this);
  23694. };
  23695. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  23696. get: function () {
  23697. if (!this._onLoadObservarble) {
  23698. this._onLoadObservarble = new BABYLON.Observable();
  23699. }
  23700. return this._onLoadObservarble;
  23701. },
  23702. enumerable: true,
  23703. configurable: true
  23704. });
  23705. // Statics
  23706. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError) {
  23707. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23708. if (onLoad === void 0) { onLoad = null; }
  23709. if (onError === void 0) { onError = null; }
  23710. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data);
  23711. };
  23712. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  23713. if (parsedTexture.customType) {
  23714. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  23715. return customTexture.Parse(parsedTexture, scene, rootUrl);
  23716. }
  23717. if (parsedTexture.isCube) {
  23718. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  23719. }
  23720. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  23721. return null;
  23722. }
  23723. var texture = BABYLON.SerializationHelper.Parse(function () {
  23724. if (parsedTexture.mirrorPlane) {
  23725. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23726. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  23727. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  23728. return mirrorTexture;
  23729. }
  23730. else if (parsedTexture.isRenderTarget) {
  23731. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  23732. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  23733. return renderTargetTexture;
  23734. }
  23735. else {
  23736. var texture;
  23737. if (parsedTexture.base64String) {
  23738. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  23739. }
  23740. else {
  23741. texture = new Texture(rootUrl + parsedTexture.name, scene);
  23742. }
  23743. return texture;
  23744. }
  23745. }, parsedTexture, scene);
  23746. // Animations
  23747. if (parsedTexture.animations) {
  23748. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23749. var parsedAnimation = parsedTexture.animations[animationIndex];
  23750. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23751. }
  23752. }
  23753. return texture;
  23754. };
  23755. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError) {
  23756. if (deleteBuffer === void 0) { deleteBuffer = false; }
  23757. if (noMipmap === void 0) { noMipmap = false; }
  23758. if (invertY === void 0) { invertY = true; }
  23759. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  23760. if (onLoad === void 0) { onLoad = null; }
  23761. if (onError === void 0) { onError = null; }
  23762. if (name.substr(0, 5) !== "data:") {
  23763. name = "data:" + name;
  23764. }
  23765. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer);
  23766. };
  23767. return Texture;
  23768. }(BABYLON.BaseTexture));
  23769. // Constants
  23770. Texture.NEAREST_SAMPLINGMODE = 1;
  23771. Texture.BILINEAR_SAMPLINGMODE = 2;
  23772. Texture.TRILINEAR_SAMPLINGMODE = 3;
  23773. Texture.EXPLICIT_MODE = 0;
  23774. Texture.SPHERICAL_MODE = 1;
  23775. Texture.PLANAR_MODE = 2;
  23776. Texture.CUBIC_MODE = 3;
  23777. Texture.PROJECTION_MODE = 4;
  23778. Texture.SKYBOX_MODE = 5;
  23779. Texture.INVCUBIC_MODE = 6;
  23780. Texture.EQUIRECTANGULAR_MODE = 7;
  23781. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  23782. Texture.CLAMP_ADDRESSMODE = 0;
  23783. Texture.WRAP_ADDRESSMODE = 1;
  23784. Texture.MIRROR_ADDRESSMODE = 2;
  23785. __decorate([
  23786. BABYLON.serialize()
  23787. ], Texture.prototype, "url", void 0);
  23788. __decorate([
  23789. BABYLON.serialize()
  23790. ], Texture.prototype, "uOffset", void 0);
  23791. __decorate([
  23792. BABYLON.serialize()
  23793. ], Texture.prototype, "vOffset", void 0);
  23794. __decorate([
  23795. BABYLON.serialize()
  23796. ], Texture.prototype, "uScale", void 0);
  23797. __decorate([
  23798. BABYLON.serialize()
  23799. ], Texture.prototype, "vScale", void 0);
  23800. __decorate([
  23801. BABYLON.serialize()
  23802. ], Texture.prototype, "uAng", void 0);
  23803. __decorate([
  23804. BABYLON.serialize()
  23805. ], Texture.prototype, "vAng", void 0);
  23806. __decorate([
  23807. BABYLON.serialize()
  23808. ], Texture.prototype, "wAng", void 0);
  23809. BABYLON.Texture = Texture;
  23810. })(BABYLON || (BABYLON = {}));
  23811. //# sourceMappingURL=babylon.texture.js.map
  23812. var BABYLON;
  23813. (function (BABYLON) {
  23814. var CubeTexture = (function (_super) {
  23815. __extends(CubeTexture, _super);
  23816. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError) {
  23817. if (onLoad === void 0) { onLoad = null; }
  23818. if (onError === void 0) { onError = null; }
  23819. var _this = _super.call(this, scene) || this;
  23820. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  23821. _this.name = rootUrl;
  23822. _this.url = rootUrl;
  23823. _this._noMipmap = noMipmap;
  23824. _this.hasAlpha = false;
  23825. if (!rootUrl && !files) {
  23826. return _this;
  23827. }
  23828. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  23829. if (!files) {
  23830. if (!extensions) {
  23831. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  23832. }
  23833. files = [];
  23834. for (var index = 0; index < extensions.length; index++) {
  23835. files.push(rootUrl + extensions[index]);
  23836. }
  23837. _this._extensions = extensions;
  23838. }
  23839. _this._files = files;
  23840. if (!_this._texture) {
  23841. if (!scene.useDelayedTextureLoading) {
  23842. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError);
  23843. }
  23844. else {
  23845. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  23846. }
  23847. }
  23848. else if (onLoad) {
  23849. if (_this._texture.isReady) {
  23850. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  23851. }
  23852. else {
  23853. _this._texture.onLoadedCallbacks.push(onLoad);
  23854. }
  23855. }
  23856. _this.isCube = true;
  23857. _this._textureMatrix = BABYLON.Matrix.Identity();
  23858. return _this;
  23859. }
  23860. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  23861. return new CubeTexture("", scene, null, noMipmap, files);
  23862. };
  23863. // Methods
  23864. CubeTexture.prototype.delayLoad = function () {
  23865. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  23866. return;
  23867. }
  23868. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  23869. this._texture = this._getFromCache(this.url, this._noMipmap);
  23870. if (!this._texture) {
  23871. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap);
  23872. }
  23873. };
  23874. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  23875. return this._textureMatrix;
  23876. };
  23877. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  23878. var texture = BABYLON.SerializationHelper.Parse(function () {
  23879. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  23880. }, parsedTexture, scene);
  23881. // Animations
  23882. if (parsedTexture.animations) {
  23883. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  23884. var parsedAnimation = parsedTexture.animations[animationIndex];
  23885. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23886. }
  23887. }
  23888. return texture;
  23889. };
  23890. CubeTexture.prototype.clone = function () {
  23891. var _this = this;
  23892. return BABYLON.SerializationHelper.Clone(function () {
  23893. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  23894. }, this);
  23895. };
  23896. return CubeTexture;
  23897. }(BABYLON.BaseTexture));
  23898. BABYLON.CubeTexture = CubeTexture;
  23899. })(BABYLON || (BABYLON = {}));
  23900. //# sourceMappingURL=babylon.cubeTexture.js.map
  23901. var BABYLON;
  23902. (function (BABYLON) {
  23903. var RenderTargetTexture = (function (_super) {
  23904. __extends(RenderTargetTexture, _super);
  23905. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer) {
  23906. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  23907. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  23908. if (isCube === void 0) { isCube = false; }
  23909. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  23910. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  23911. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  23912. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  23913. _this.isCube = isCube;
  23914. /**
  23915. * Use this list to define the list of mesh you want to render.
  23916. */
  23917. _this.renderList = new Array();
  23918. _this.renderParticles = true;
  23919. _this.renderSprites = false;
  23920. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  23921. // Events
  23922. /**
  23923. * An event triggered when the texture is unbind.
  23924. * @type {BABYLON.Observable}
  23925. */
  23926. _this.onAfterUnbindObservable = new BABYLON.Observable();
  23927. /**
  23928. * An event triggered before rendering the texture
  23929. * @type {BABYLON.Observable}
  23930. */
  23931. _this.onBeforeRenderObservable = new BABYLON.Observable();
  23932. /**
  23933. * An event triggered after rendering the texture
  23934. * @type {BABYLON.Observable}
  23935. */
  23936. _this.onAfterRenderObservable = new BABYLON.Observable();
  23937. /**
  23938. * An event triggered after the texture clear
  23939. * @type {BABYLON.Observable}
  23940. */
  23941. _this.onClearObservable = new BABYLON.Observable();
  23942. _this._currentRefreshId = -1;
  23943. _this._refreshRate = 1;
  23944. _this.name = name;
  23945. _this.isRenderTarget = true;
  23946. _this._size = size;
  23947. _this._generateMipMaps = generateMipMaps;
  23948. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  23949. _this._renderTargetOptions = {
  23950. generateMipMaps: generateMipMaps,
  23951. type: type,
  23952. samplingMode: samplingMode,
  23953. generateDepthBuffer: generateDepthBuffer,
  23954. generateStencilBuffer: generateStencilBuffer
  23955. };
  23956. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  23957. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23958. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  23959. }
  23960. if (isCube) {
  23961. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  23962. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  23963. _this._textureMatrix = BABYLON.Matrix.Identity();
  23964. }
  23965. else {
  23966. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  23967. }
  23968. // Rendering groups
  23969. _this._renderingManager = new BABYLON.RenderingManager(scene);
  23970. return _this;
  23971. }
  23972. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  23973. get: function () {
  23974. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  23975. },
  23976. enumerable: true,
  23977. configurable: true
  23978. });
  23979. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  23980. get: function () {
  23981. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  23982. },
  23983. enumerable: true,
  23984. configurable: true
  23985. });
  23986. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  23987. get: function () {
  23988. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  23989. },
  23990. enumerable: true,
  23991. configurable: true
  23992. });
  23993. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  23994. set: function (callback) {
  23995. if (this._onAfterUnbindObserver) {
  23996. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  23997. }
  23998. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  23999. },
  24000. enumerable: true,
  24001. configurable: true
  24002. });
  24003. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  24004. set: function (callback) {
  24005. if (this._onBeforeRenderObserver) {
  24006. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24007. }
  24008. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24009. },
  24010. enumerable: true,
  24011. configurable: true
  24012. });
  24013. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  24014. set: function (callback) {
  24015. if (this._onAfterRenderObserver) {
  24016. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24017. }
  24018. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24019. },
  24020. enumerable: true,
  24021. configurable: true
  24022. });
  24023. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  24024. set: function (callback) {
  24025. if (this._onClearObserver) {
  24026. this.onClearObservable.remove(this._onClearObserver);
  24027. }
  24028. this._onClearObserver = this.onClearObservable.add(callback);
  24029. },
  24030. enumerable: true,
  24031. configurable: true
  24032. });
  24033. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  24034. this._currentRefreshId = -1;
  24035. };
  24036. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  24037. get: function () {
  24038. return this._refreshRate;
  24039. },
  24040. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24041. set: function (value) {
  24042. this._refreshRate = value;
  24043. this.resetRefreshCounter();
  24044. },
  24045. enumerable: true,
  24046. configurable: true
  24047. });
  24048. RenderTargetTexture.prototype._shouldRender = function () {
  24049. if (this._currentRefreshId === -1) {
  24050. this._currentRefreshId = 1;
  24051. return true;
  24052. }
  24053. if (this.refreshRate === this._currentRefreshId) {
  24054. this._currentRefreshId = 1;
  24055. return true;
  24056. }
  24057. this._currentRefreshId++;
  24058. return false;
  24059. };
  24060. RenderTargetTexture.prototype.isReady = function () {
  24061. if (!this.getScene().renderTargetsEnabled) {
  24062. return false;
  24063. }
  24064. return _super.prototype.isReady.call(this);
  24065. };
  24066. RenderTargetTexture.prototype.getRenderSize = function () {
  24067. return this._size;
  24068. };
  24069. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  24070. get: function () {
  24071. return true;
  24072. },
  24073. enumerable: true,
  24074. configurable: true
  24075. });
  24076. RenderTargetTexture.prototype.scale = function (ratio) {
  24077. var newSize = this._size * ratio;
  24078. this.resize(newSize);
  24079. };
  24080. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  24081. if (this.isCube) {
  24082. return this._textureMatrix;
  24083. }
  24084. return _super.prototype.getReflectionTextureMatrix.call(this);
  24085. };
  24086. RenderTargetTexture.prototype.resize = function (size) {
  24087. this.releaseInternalTexture();
  24088. if (this.isCube) {
  24089. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  24090. }
  24091. else {
  24092. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  24093. }
  24094. };
  24095. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  24096. var scene = this.getScene();
  24097. var engine = scene.getEngine();
  24098. if (this.useCameraPostProcesses !== undefined) {
  24099. useCameraPostProcess = this.useCameraPostProcesses;
  24100. }
  24101. if (this._waitingRenderList) {
  24102. this.renderList = [];
  24103. for (var index = 0; index < this._waitingRenderList.length; index++) {
  24104. var id = this._waitingRenderList[index];
  24105. this.renderList.push(scene.getMeshByID(id));
  24106. }
  24107. delete this._waitingRenderList;
  24108. }
  24109. // Is predicate defined?
  24110. if (this.renderListPredicate) {
  24111. this.renderList.splice(0); // Clear previous renderList
  24112. var sceneMeshes = this.getScene().meshes;
  24113. for (var index = 0; index < sceneMeshes.length; index++) {
  24114. var mesh = sceneMeshes[index];
  24115. if (this.renderListPredicate(mesh)) {
  24116. this.renderList.push(mesh);
  24117. }
  24118. }
  24119. }
  24120. if (this.renderList && this.renderList.length === 0) {
  24121. return;
  24122. }
  24123. // Set custom projection.
  24124. // Needs to be before binding to prevent changing the aspect ratio.
  24125. if (this.activeCamera) {
  24126. engine.setViewport(this.activeCamera.viewport);
  24127. if (this.activeCamera !== scene.activeCamera) {
  24128. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  24129. }
  24130. }
  24131. else {
  24132. engine.setViewport(scene.activeCamera.viewport);
  24133. }
  24134. // Prepare renderingManager
  24135. this._renderingManager.reset();
  24136. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  24137. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  24138. var sceneRenderId = scene.getRenderId();
  24139. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  24140. var mesh = currentRenderList[meshIndex];
  24141. if (mesh) {
  24142. if (!mesh.isReady()) {
  24143. // Reset _currentRefreshId
  24144. this.resetRefreshCounter();
  24145. continue;
  24146. }
  24147. mesh._preActivateForIntermediateRendering(sceneRenderId);
  24148. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && ((mesh.layerMask & scene.activeCamera.layerMask) !== 0)) {
  24149. mesh._activate(sceneRenderId);
  24150. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  24151. var subMesh = mesh.subMeshes[subIndex];
  24152. scene._activeIndices.addCount(subMesh.indexCount, false);
  24153. this._renderingManager.dispatch(subMesh);
  24154. }
  24155. }
  24156. }
  24157. }
  24158. if (this.isCube) {
  24159. for (var face = 0; face < 6; face++) {
  24160. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24161. scene.incrementRenderId();
  24162. scene.resetCachedMaterial();
  24163. }
  24164. }
  24165. else {
  24166. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  24167. }
  24168. this.onAfterUnbindObservable.notifyObservers(this);
  24169. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  24170. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  24171. }
  24172. engine.setViewport(scene.activeCamera.viewport);
  24173. scene.resetCachedMaterial();
  24174. };
  24175. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  24176. var scene = this.getScene();
  24177. var engine = scene.getEngine();
  24178. // Bind
  24179. if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  24180. if (this.isCube) {
  24181. engine.bindFramebuffer(this._texture, faceIndex);
  24182. }
  24183. else {
  24184. engine.bindFramebuffer(this._texture);
  24185. }
  24186. }
  24187. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  24188. // Clear
  24189. if (this.onClearObservable.hasObservers()) {
  24190. this.onClearObservable.notifyObservers(engine);
  24191. }
  24192. else {
  24193. engine.clear(scene.clearColor, true, true, true);
  24194. }
  24195. if (!this._doNotChangeAspectRatio) {
  24196. scene.updateTransformMatrix(true);
  24197. }
  24198. // Render
  24199. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  24200. if (useCameraPostProcess) {
  24201. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  24202. }
  24203. if (!this._doNotChangeAspectRatio) {
  24204. scene.updateTransformMatrix(true);
  24205. }
  24206. this.onAfterRenderObservable.notifyObservers(faceIndex);
  24207. // Dump ?
  24208. if (dumpForDebug) {
  24209. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  24210. }
  24211. // Unbind
  24212. if (!this.isCube || faceIndex === 5) {
  24213. if (this.isCube) {
  24214. if (faceIndex === 5) {
  24215. engine.generateMipMapsForCubemap(this._texture);
  24216. }
  24217. }
  24218. engine.unBindFramebuffer(this._texture, this.isCube);
  24219. }
  24220. };
  24221. /**
  24222. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  24223. * This allowed control for front to back rendering or reversly depending of the special needs.
  24224. *
  24225. * @param renderingGroupId The rendering group id corresponding to its index
  24226. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  24227. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  24228. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  24229. */
  24230. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  24231. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  24232. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  24233. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  24234. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  24235. };
  24236. /**
  24237. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  24238. *
  24239. * @param renderingGroupId The rendering group id corresponding to its index
  24240. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  24241. */
  24242. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  24243. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  24244. };
  24245. RenderTargetTexture.prototype.clone = function () {
  24246. var textureSize = this.getSize();
  24247. var newTexture = new RenderTargetTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._doNotChangeAspectRatio, this._renderTargetOptions.type, this.isCube, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer, this._renderTargetOptions.generateStencilBuffer);
  24248. // Base texture
  24249. newTexture.hasAlpha = this.hasAlpha;
  24250. newTexture.level = this.level;
  24251. // RenderTarget Texture
  24252. newTexture.coordinatesMode = this.coordinatesMode;
  24253. newTexture.renderList = this.renderList.slice(0);
  24254. return newTexture;
  24255. };
  24256. RenderTargetTexture.prototype.serialize = function () {
  24257. if (!this.name) {
  24258. return null;
  24259. }
  24260. var serializationObject = _super.prototype.serialize.call(this);
  24261. serializationObject.renderTargetSize = this.getRenderSize();
  24262. serializationObject.renderList = [];
  24263. for (var index = 0; index < this.renderList.length; index++) {
  24264. serializationObject.renderList.push(this.renderList[index].id);
  24265. }
  24266. return serializationObject;
  24267. };
  24268. return RenderTargetTexture;
  24269. }(BABYLON.Texture));
  24270. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  24271. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  24272. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  24273. BABYLON.RenderTargetTexture = RenderTargetTexture;
  24274. })(BABYLON || (BABYLON = {}));
  24275. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  24276. var BABYLON;
  24277. (function (BABYLON) {
  24278. var ProceduralTexture = (function (_super) {
  24279. __extends(ProceduralTexture, _super);
  24280. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  24281. if (generateMipMaps === void 0) { generateMipMaps = true; }
  24282. if (isCube === void 0) { isCube = false; }
  24283. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24284. _this.isCube = isCube;
  24285. _this.isEnabled = true;
  24286. _this._currentRefreshId = -1;
  24287. _this._refreshRate = 1;
  24288. _this._vertexBuffers = {};
  24289. _this._uniforms = new Array();
  24290. _this._samplers = new Array();
  24291. _this._textures = new Array();
  24292. _this._floats = new Array();
  24293. _this._floatsArrays = {};
  24294. _this._colors3 = new Array();
  24295. _this._colors4 = new Array();
  24296. _this._vectors2 = new Array();
  24297. _this._vectors3 = new Array();
  24298. _this._matrices = new Array();
  24299. _this._fallbackTextureUsed = false;
  24300. scene._proceduralTextures.push(_this);
  24301. _this.name = name;
  24302. _this.isRenderTarget = true;
  24303. _this._size = size;
  24304. _this._generateMipMaps = generateMipMaps;
  24305. _this.setFragment(fragment);
  24306. _this._fallbackTexture = fallbackTexture;
  24307. var engine = scene.getEngine();
  24308. if (isCube) {
  24309. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  24310. _this.setFloat("face", 0);
  24311. }
  24312. else {
  24313. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  24314. }
  24315. // VBO
  24316. var vertices = [];
  24317. vertices.push(1, 1);
  24318. vertices.push(-1, 1);
  24319. vertices.push(-1, -1);
  24320. vertices.push(1, -1);
  24321. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  24322. // Indices
  24323. var indices = [];
  24324. indices.push(0);
  24325. indices.push(1);
  24326. indices.push(2);
  24327. indices.push(0);
  24328. indices.push(2);
  24329. indices.push(3);
  24330. _this._indexBuffer = engine.createIndexBuffer(indices);
  24331. return _this;
  24332. }
  24333. ProceduralTexture.prototype.reset = function () {
  24334. if (this._effect === undefined) {
  24335. return;
  24336. }
  24337. var engine = this.getScene().getEngine();
  24338. engine._releaseEffect(this._effect);
  24339. };
  24340. ProceduralTexture.prototype.isReady = function () {
  24341. var _this = this;
  24342. var engine = this.getScene().getEngine();
  24343. var shaders;
  24344. if (!this._fragment) {
  24345. return false;
  24346. }
  24347. if (this._fallbackTextureUsed) {
  24348. return true;
  24349. }
  24350. if (this._fragment.fragmentElement !== undefined) {
  24351. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  24352. }
  24353. else {
  24354. shaders = { vertex: "procedural", fragment: this._fragment };
  24355. }
  24356. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  24357. _this.releaseInternalTexture();
  24358. if (_this._fallbackTexture) {
  24359. _this._texture = _this._fallbackTexture._texture;
  24360. _this._texture.references++;
  24361. }
  24362. _this._fallbackTextureUsed = true;
  24363. });
  24364. return this._effect.isReady();
  24365. };
  24366. ProceduralTexture.prototype.resetRefreshCounter = function () {
  24367. this._currentRefreshId = -1;
  24368. };
  24369. ProceduralTexture.prototype.setFragment = function (fragment) {
  24370. this._fragment = fragment;
  24371. };
  24372. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  24373. get: function () {
  24374. return this._refreshRate;
  24375. },
  24376. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  24377. set: function (value) {
  24378. this._refreshRate = value;
  24379. this.resetRefreshCounter();
  24380. },
  24381. enumerable: true,
  24382. configurable: true
  24383. });
  24384. ProceduralTexture.prototype._shouldRender = function () {
  24385. if (!this.isEnabled || !this.isReady() || !this._texture) {
  24386. return false;
  24387. }
  24388. if (this._fallbackTextureUsed) {
  24389. return false;
  24390. }
  24391. if (this._currentRefreshId === -1) {
  24392. this._currentRefreshId = 1;
  24393. return true;
  24394. }
  24395. if (this.refreshRate === this._currentRefreshId) {
  24396. this._currentRefreshId = 1;
  24397. return true;
  24398. }
  24399. this._currentRefreshId++;
  24400. return false;
  24401. };
  24402. ProceduralTexture.prototype.getRenderSize = function () {
  24403. return this._size;
  24404. };
  24405. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  24406. if (this._fallbackTextureUsed) {
  24407. return;
  24408. }
  24409. this.releaseInternalTexture();
  24410. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  24411. };
  24412. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  24413. if (this._uniforms.indexOf(uniformName) === -1) {
  24414. this._uniforms.push(uniformName);
  24415. }
  24416. };
  24417. ProceduralTexture.prototype.setTexture = function (name, texture) {
  24418. if (this._samplers.indexOf(name) === -1) {
  24419. this._samplers.push(name);
  24420. }
  24421. this._textures[name] = texture;
  24422. return this;
  24423. };
  24424. ProceduralTexture.prototype.setFloat = function (name, value) {
  24425. this._checkUniform(name);
  24426. this._floats[name] = value;
  24427. return this;
  24428. };
  24429. ProceduralTexture.prototype.setFloats = function (name, value) {
  24430. this._checkUniform(name);
  24431. this._floatsArrays[name] = value;
  24432. return this;
  24433. };
  24434. ProceduralTexture.prototype.setColor3 = function (name, value) {
  24435. this._checkUniform(name);
  24436. this._colors3[name] = value;
  24437. return this;
  24438. };
  24439. ProceduralTexture.prototype.setColor4 = function (name, value) {
  24440. this._checkUniform(name);
  24441. this._colors4[name] = value;
  24442. return this;
  24443. };
  24444. ProceduralTexture.prototype.setVector2 = function (name, value) {
  24445. this._checkUniform(name);
  24446. this._vectors2[name] = value;
  24447. return this;
  24448. };
  24449. ProceduralTexture.prototype.setVector3 = function (name, value) {
  24450. this._checkUniform(name);
  24451. this._vectors3[name] = value;
  24452. return this;
  24453. };
  24454. ProceduralTexture.prototype.setMatrix = function (name, value) {
  24455. this._checkUniform(name);
  24456. this._matrices[name] = value;
  24457. return this;
  24458. };
  24459. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24460. var scene = this.getScene();
  24461. var engine = scene.getEngine();
  24462. // Render
  24463. engine.enableEffect(this._effect);
  24464. engine.setState(false);
  24465. // Texture
  24466. for (var name in this._textures) {
  24467. this._effect.setTexture(name, this._textures[name]);
  24468. }
  24469. // Float
  24470. for (name in this._floats) {
  24471. this._effect.setFloat(name, this._floats[name]);
  24472. }
  24473. // Floats
  24474. for (name in this._floatsArrays) {
  24475. this._effect.setArray(name, this._floatsArrays[name]);
  24476. }
  24477. // Color3
  24478. for (name in this._colors3) {
  24479. this._effect.setColor3(name, this._colors3[name]);
  24480. }
  24481. // Color4
  24482. for (name in this._colors4) {
  24483. var color = this._colors4[name];
  24484. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  24485. }
  24486. // Vector2
  24487. for (name in this._vectors2) {
  24488. this._effect.setVector2(name, this._vectors2[name]);
  24489. }
  24490. // Vector3
  24491. for (name in this._vectors3) {
  24492. this._effect.setVector3(name, this._vectors3[name]);
  24493. }
  24494. // Matrix
  24495. for (name in this._matrices) {
  24496. this._effect.setMatrix(name, this._matrices[name]);
  24497. }
  24498. // VBOs
  24499. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  24500. if (this.isCube) {
  24501. for (var face = 0; face < 6; face++) {
  24502. engine.bindFramebuffer(this._texture, face);
  24503. this._effect.setFloat("face", face);
  24504. // Clear
  24505. engine.clear(scene.clearColor, true, true, true);
  24506. // Draw order
  24507. engine.draw(true, 0, 6);
  24508. // Mipmaps
  24509. if (face === 5) {
  24510. engine.generateMipMapsForCubemap(this._texture);
  24511. }
  24512. }
  24513. }
  24514. else {
  24515. engine.bindFramebuffer(this._texture);
  24516. // Clear
  24517. engine.clear(scene.clearColor, true, true, true);
  24518. // Draw order
  24519. engine.draw(true, 0, 6);
  24520. }
  24521. // Unbind
  24522. engine.unBindFramebuffer(this._texture, this.isCube);
  24523. if (this.onGenerated) {
  24524. this.onGenerated();
  24525. }
  24526. };
  24527. ProceduralTexture.prototype.clone = function () {
  24528. var textureSize = this.getSize();
  24529. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  24530. // Base texture
  24531. newTexture.hasAlpha = this.hasAlpha;
  24532. newTexture.level = this.level;
  24533. // RenderTarget Texture
  24534. newTexture.coordinatesMode = this.coordinatesMode;
  24535. return newTexture;
  24536. };
  24537. ProceduralTexture.prototype.dispose = function () {
  24538. var index = this.getScene()._proceduralTextures.indexOf(this);
  24539. if (index >= 0) {
  24540. this.getScene()._proceduralTextures.splice(index, 1);
  24541. }
  24542. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  24543. if (vertexBuffer) {
  24544. vertexBuffer.dispose();
  24545. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  24546. }
  24547. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  24548. this._indexBuffer = null;
  24549. }
  24550. _super.prototype.dispose.call(this);
  24551. };
  24552. return ProceduralTexture;
  24553. }(BABYLON.Texture));
  24554. BABYLON.ProceduralTexture = ProceduralTexture;
  24555. })(BABYLON || (BABYLON = {}));
  24556. //# sourceMappingURL=babylon.proceduralTexture.js.map
  24557. var BABYLON;
  24558. (function (BABYLON) {
  24559. var MirrorTexture = (function (_super) {
  24560. __extends(MirrorTexture, _super);
  24561. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  24562. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  24563. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  24564. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  24565. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  24566. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  24567. _this._transformMatrix = BABYLON.Matrix.Zero();
  24568. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  24569. _this.onBeforeRenderObservable.add(function () {
  24570. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  24571. _this._savedViewMatrix = scene.getViewMatrix();
  24572. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  24573. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  24574. scene.clipPlane = _this.mirrorPlane;
  24575. scene.getEngine().cullBackFaces = false;
  24576. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.position, _this._mirrorMatrix);
  24577. });
  24578. _this.onAfterRenderObservable.add(function () {
  24579. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  24580. scene.getEngine().cullBackFaces = true;
  24581. scene._mirroredCameraPosition = null;
  24582. delete scene.clipPlane;
  24583. });
  24584. return _this;
  24585. }
  24586. MirrorTexture.prototype.clone = function () {
  24587. var textureSize = this.getSize();
  24588. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  24589. // Base texture
  24590. newTexture.hasAlpha = this.hasAlpha;
  24591. newTexture.level = this.level;
  24592. // Mirror Texture
  24593. newTexture.mirrorPlane = this.mirrorPlane.clone();
  24594. newTexture.renderList = this.renderList.slice(0);
  24595. return newTexture;
  24596. };
  24597. MirrorTexture.prototype.serialize = function () {
  24598. if (!this.name) {
  24599. return null;
  24600. }
  24601. var serializationObject = _super.prototype.serialize.call(this);
  24602. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  24603. return serializationObject;
  24604. };
  24605. return MirrorTexture;
  24606. }(BABYLON.RenderTargetTexture));
  24607. BABYLON.MirrorTexture = MirrorTexture;
  24608. })(BABYLON || (BABYLON = {}));
  24609. //# sourceMappingURL=babylon.mirrorTexture.js.map
  24610. var BABYLON;
  24611. (function (BABYLON) {
  24612. /**
  24613. * Creates a refraction texture used by refraction channel of the standard material.
  24614. * @param name the texture name
  24615. * @param size size of the underlying texture
  24616. * @param scene root scene
  24617. */
  24618. var RefractionTexture = (function (_super) {
  24619. __extends(RefractionTexture, _super);
  24620. function RefractionTexture(name, size, scene, generateMipMaps) {
  24621. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  24622. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  24623. _this.depth = 2.0;
  24624. _this.onBeforeRenderObservable.add(function () {
  24625. scene.clipPlane = _this.refractionPlane;
  24626. });
  24627. _this.onAfterRenderObservable.add(function () {
  24628. delete scene.clipPlane;
  24629. });
  24630. return _this;
  24631. }
  24632. RefractionTexture.prototype.clone = function () {
  24633. var textureSize = this.getSize();
  24634. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  24635. // Base texture
  24636. newTexture.hasAlpha = this.hasAlpha;
  24637. newTexture.level = this.level;
  24638. // Refraction Texture
  24639. newTexture.refractionPlane = this.refractionPlane.clone();
  24640. newTexture.renderList = this.renderList.slice(0);
  24641. newTexture.depth = this.depth;
  24642. return newTexture;
  24643. };
  24644. RefractionTexture.prototype.serialize = function () {
  24645. if (!this.name) {
  24646. return null;
  24647. }
  24648. var serializationObject = _super.prototype.serialize.call(this);
  24649. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  24650. serializationObject.depth = this.depth;
  24651. return serializationObject;
  24652. };
  24653. return RefractionTexture;
  24654. }(BABYLON.RenderTargetTexture));
  24655. BABYLON.RefractionTexture = RefractionTexture;
  24656. })(BABYLON || (BABYLON = {}));
  24657. //# sourceMappingURL=babylon.refractionTexture.js.map
  24658. var BABYLON;
  24659. (function (BABYLON) {
  24660. var DynamicTexture = (function (_super) {
  24661. __extends(DynamicTexture, _super);
  24662. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode) {
  24663. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24664. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  24665. _this.name = name;
  24666. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24667. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24668. _this._generateMipMaps = generateMipMaps;
  24669. if (options.getContext) {
  24670. _this._canvas = options;
  24671. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24672. }
  24673. else {
  24674. _this._canvas = document.createElement("canvas");
  24675. if (options.width) {
  24676. _this._texture = scene.getEngine().createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  24677. }
  24678. else {
  24679. _this._texture = scene.getEngine().createDynamicTexture(options, options, generateMipMaps, samplingMode);
  24680. }
  24681. }
  24682. var textureSize = _this.getSize();
  24683. _this._canvas.width = textureSize.width;
  24684. _this._canvas.height = textureSize.height;
  24685. _this._context = _this._canvas.getContext("2d");
  24686. return _this;
  24687. }
  24688. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  24689. get: function () {
  24690. return true;
  24691. },
  24692. enumerable: true,
  24693. configurable: true
  24694. });
  24695. DynamicTexture.prototype.scale = function (ratio) {
  24696. var textureSize = this.getSize();
  24697. textureSize.width *= ratio;
  24698. textureSize.height *= ratio;
  24699. this._canvas.width = textureSize.width;
  24700. this._canvas.height = textureSize.height;
  24701. this.releaseInternalTexture();
  24702. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  24703. };
  24704. DynamicTexture.prototype.getContext = function () {
  24705. return this._context;
  24706. };
  24707. DynamicTexture.prototype.clear = function () {
  24708. var size = this.getSize();
  24709. this._context.fillRect(0, 0, size.width, size.height);
  24710. };
  24711. DynamicTexture.prototype.update = function (invertY) {
  24712. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY);
  24713. };
  24714. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  24715. if (update === void 0) { update = true; }
  24716. var size = this.getSize();
  24717. if (clearColor) {
  24718. this._context.fillStyle = clearColor;
  24719. this._context.fillRect(0, 0, size.width, size.height);
  24720. }
  24721. this._context.font = font;
  24722. if (x === null) {
  24723. var textSize = this._context.measureText(text);
  24724. x = (size.width - textSize.width) / 2;
  24725. }
  24726. this._context.fillStyle = color;
  24727. this._context.fillText(text, x, y);
  24728. if (update) {
  24729. this.update(invertY);
  24730. }
  24731. };
  24732. DynamicTexture.prototype.clone = function () {
  24733. var textureSize = this.getSize();
  24734. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  24735. // Base texture
  24736. newTexture.hasAlpha = this.hasAlpha;
  24737. newTexture.level = this.level;
  24738. // Dynamic Texture
  24739. newTexture.wrapU = this.wrapU;
  24740. newTexture.wrapV = this.wrapV;
  24741. return newTexture;
  24742. };
  24743. return DynamicTexture;
  24744. }(BABYLON.Texture));
  24745. BABYLON.DynamicTexture = DynamicTexture;
  24746. })(BABYLON || (BABYLON = {}));
  24747. //# sourceMappingURL=babylon.dynamicTexture.js.map
  24748. var BABYLON;
  24749. (function (BABYLON) {
  24750. var VideoTexture = (function (_super) {
  24751. __extends(VideoTexture, _super);
  24752. /**
  24753. * Creates a video texture.
  24754. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  24755. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  24756. * @param {BABYLON.Scene} scene is obviously the current scene.
  24757. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  24758. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  24759. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  24760. */
  24761. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  24762. if (generateMipMaps === void 0) { generateMipMaps = false; }
  24763. if (invertY === void 0) { invertY = false; }
  24764. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  24765. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  24766. _this._autoLaunch = true;
  24767. var urls;
  24768. _this.name = name;
  24769. if (urlsOrVideo instanceof HTMLVideoElement) {
  24770. _this.video = urlsOrVideo;
  24771. }
  24772. else {
  24773. urls = urlsOrVideo;
  24774. _this.video = document.createElement("video");
  24775. _this.video.autoplay = false;
  24776. _this.video.loop = true;
  24777. }
  24778. _this._generateMipMaps = generateMipMaps;
  24779. _this._samplingMode = samplingMode;
  24780. if (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight)) {
  24781. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  24782. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  24783. }
  24784. else {
  24785. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24786. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  24787. _this._generateMipMaps = false;
  24788. }
  24789. if (urls) {
  24790. _this.video.addEventListener("canplaythrough", function () {
  24791. _this._createTexture();
  24792. });
  24793. urls.forEach(function (url) {
  24794. var source = document.createElement("source");
  24795. source.src = url;
  24796. _this.video.appendChild(source);
  24797. });
  24798. }
  24799. else {
  24800. _this._createTexture();
  24801. }
  24802. _this._lastUpdate = BABYLON.Tools.Now;
  24803. return _this;
  24804. }
  24805. VideoTexture.prototype._createTexture = function () {
  24806. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  24807. this._texture.isReady = true;
  24808. };
  24809. VideoTexture.prototype.update = function () {
  24810. if (this._autoLaunch) {
  24811. this._autoLaunch = false;
  24812. this.video.play();
  24813. }
  24814. var now = BABYLON.Tools.Now;
  24815. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  24816. return false;
  24817. }
  24818. this._lastUpdate = now;
  24819. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  24820. return true;
  24821. };
  24822. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  24823. var video = document.createElement("video");
  24824. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  24825. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  24826. if (navigator.getUserMedia) {
  24827. navigator.getUserMedia({
  24828. video: {
  24829. width: {
  24830. min: (constraints && constraints.minWidth) || 256,
  24831. max: (constraints && constraints.maxWidth) || 640
  24832. },
  24833. height: {
  24834. min: (constraints && constraints.minHeight) || 256,
  24835. max: (constraints && constraints.maxHeight) || 480
  24836. }
  24837. }
  24838. }, function (stream) {
  24839. if (video.mozSrcObject !== undefined) {
  24840. video.mozSrcObject = stream;
  24841. }
  24842. else {
  24843. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  24844. }
  24845. video.play();
  24846. if (onReady) {
  24847. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  24848. }
  24849. }, function (e) {
  24850. BABYLON.Tools.Error(e.name);
  24851. });
  24852. }
  24853. };
  24854. return VideoTexture;
  24855. }(BABYLON.Texture));
  24856. BABYLON.VideoTexture = VideoTexture;
  24857. })(BABYLON || (BABYLON = {}));
  24858. //# sourceMappingURL=babylon.videoTexture.js.map
  24859. var BABYLON;
  24860. (function (BABYLON) {
  24861. var CustomProceduralTexture = (function (_super) {
  24862. __extends(CustomProceduralTexture, _super);
  24863. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  24864. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  24865. _this._animate = true;
  24866. _this._time = 0;
  24867. _this._texturePath = texturePath;
  24868. //Try to load json
  24869. _this.loadJson(texturePath);
  24870. _this.refreshRate = 1;
  24871. return _this;
  24872. }
  24873. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  24874. var _this = this;
  24875. var that = this;
  24876. function noConfigFile() {
  24877. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  24878. try {
  24879. that.setFragment(that._texturePath);
  24880. }
  24881. catch (ex) {
  24882. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  24883. }
  24884. }
  24885. var configFileUrl = jsonUrl + "/config.json";
  24886. var xhr = new XMLHttpRequest();
  24887. xhr.open("GET", configFileUrl, true);
  24888. xhr.addEventListener("load", function () {
  24889. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  24890. try {
  24891. _this._config = JSON.parse(xhr.response);
  24892. _this.updateShaderUniforms();
  24893. _this.updateTextures();
  24894. _this.setFragment(_this._texturePath + "/custom");
  24895. _this._animate = _this._config.animate;
  24896. _this.refreshRate = _this._config.refreshrate;
  24897. }
  24898. catch (ex) {
  24899. noConfigFile();
  24900. }
  24901. }
  24902. else {
  24903. noConfigFile();
  24904. }
  24905. }, false);
  24906. xhr.addEventListener("error", function () {
  24907. noConfigFile();
  24908. }, false);
  24909. try {
  24910. xhr.send();
  24911. }
  24912. catch (ex) {
  24913. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  24914. }
  24915. };
  24916. CustomProceduralTexture.prototype.isReady = function () {
  24917. if (!_super.prototype.isReady.call(this)) {
  24918. return false;
  24919. }
  24920. for (var name in this._textures) {
  24921. var texture = this._textures[name];
  24922. if (!texture.isReady()) {
  24923. return false;
  24924. }
  24925. }
  24926. return true;
  24927. };
  24928. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  24929. if (this._animate) {
  24930. this._time += this.getScene().getAnimationRatio() * 0.03;
  24931. this.updateShaderUniforms();
  24932. }
  24933. _super.prototype.render.call(this, useCameraPostProcess);
  24934. };
  24935. CustomProceduralTexture.prototype.updateTextures = function () {
  24936. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  24937. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  24938. }
  24939. };
  24940. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  24941. if (this._config) {
  24942. for (var j = 0; j < this._config.uniforms.length; j++) {
  24943. var uniform = this._config.uniforms[j];
  24944. switch (uniform.type) {
  24945. case "float":
  24946. this.setFloat(uniform.name, uniform.value);
  24947. break;
  24948. case "color3":
  24949. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  24950. break;
  24951. case "color4":
  24952. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  24953. break;
  24954. case "vector2":
  24955. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  24956. break;
  24957. case "vector3":
  24958. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  24959. break;
  24960. }
  24961. }
  24962. }
  24963. this.setFloat("time", this._time);
  24964. };
  24965. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  24966. get: function () {
  24967. return this._animate;
  24968. },
  24969. set: function (value) {
  24970. this._animate = value;
  24971. },
  24972. enumerable: true,
  24973. configurable: true
  24974. });
  24975. return CustomProceduralTexture;
  24976. }(BABYLON.ProceduralTexture));
  24977. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  24978. })(BABYLON || (BABYLON = {}));
  24979. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  24980. var BABYLON;
  24981. (function (BABYLON) {
  24982. var EffectFallbacks = (function () {
  24983. function EffectFallbacks() {
  24984. this._defines = {};
  24985. this._currentRank = 32;
  24986. this._maxRank = -1;
  24987. }
  24988. EffectFallbacks.prototype.addFallback = function (rank, define) {
  24989. if (!this._defines[rank]) {
  24990. if (rank < this._currentRank) {
  24991. this._currentRank = rank;
  24992. }
  24993. if (rank > this._maxRank) {
  24994. this._maxRank = rank;
  24995. }
  24996. this._defines[rank] = new Array();
  24997. }
  24998. this._defines[rank].push(define);
  24999. };
  25000. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  25001. this._meshRank = rank;
  25002. this._mesh = mesh;
  25003. if (rank > this._maxRank) {
  25004. this._maxRank = rank;
  25005. }
  25006. };
  25007. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  25008. get: function () {
  25009. return this._currentRank <= this._maxRank;
  25010. },
  25011. enumerable: true,
  25012. configurable: true
  25013. });
  25014. EffectFallbacks.prototype.reduce = function (currentDefines) {
  25015. var currentFallbacks = this._defines[this._currentRank];
  25016. for (var index = 0; index < currentFallbacks.length; index++) {
  25017. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  25018. }
  25019. if (this._mesh && this._currentRank === this._meshRank) {
  25020. this._mesh.computeBonesUsingShaders = false;
  25021. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  25022. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  25023. }
  25024. this._currentRank++;
  25025. return currentDefines;
  25026. };
  25027. return EffectFallbacks;
  25028. }());
  25029. BABYLON.EffectFallbacks = EffectFallbacks;
  25030. var Effect = (function () {
  25031. function Effect(baseName, attributesNames, uniformsNames, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  25032. var _this = this;
  25033. this._isReady = false;
  25034. this._compilationError = "";
  25035. this._valueCache = {};
  25036. this._engine = engine;
  25037. this.name = baseName;
  25038. this.defines = defines;
  25039. this._uniformsNames = uniformsNames.concat(samplers);
  25040. this._samplers = samplers;
  25041. this._attributesNames = attributesNames;
  25042. this.onError = onError;
  25043. this.onCompiled = onCompiled;
  25044. this._indexParameters = indexParameters;
  25045. var vertexSource;
  25046. var fragmentSource;
  25047. if (baseName.vertexElement) {
  25048. vertexSource = document.getElementById(baseName.vertexElement);
  25049. if (!vertexSource) {
  25050. vertexSource = baseName.vertexElement;
  25051. }
  25052. }
  25053. else {
  25054. vertexSource = baseName.vertex || baseName;
  25055. }
  25056. if (baseName.fragmentElement) {
  25057. fragmentSource = document.getElementById(baseName.fragmentElement);
  25058. if (!fragmentSource) {
  25059. fragmentSource = baseName.fragmentElement;
  25060. }
  25061. }
  25062. else {
  25063. fragmentSource = baseName.fragment || baseName;
  25064. }
  25065. this._loadVertexShader(vertexSource, function (vertexCode) {
  25066. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  25067. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  25068. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  25069. _this._prepareEffect(vertexCodeWithIncludes, fragmentCodeWithIncludes, attributesNames, defines, fallbacks);
  25070. });
  25071. });
  25072. });
  25073. });
  25074. }
  25075. // Properties
  25076. Effect.prototype.isReady = function () {
  25077. return this._isReady;
  25078. };
  25079. Effect.prototype.getProgram = function () {
  25080. return this._program;
  25081. };
  25082. Effect.prototype.getAttributesNames = function () {
  25083. return this._attributesNames;
  25084. };
  25085. Effect.prototype.getAttributeLocation = function (index) {
  25086. return this._attributes[index];
  25087. };
  25088. Effect.prototype.getAttributeLocationByName = function (name) {
  25089. var index = this._attributesNames.indexOf(name);
  25090. return this._attributes[index];
  25091. };
  25092. Effect.prototype.getAttributesCount = function () {
  25093. return this._attributes.length;
  25094. };
  25095. Effect.prototype.getUniformIndex = function (uniformName) {
  25096. return this._uniformsNames.indexOf(uniformName);
  25097. };
  25098. Effect.prototype.getUniform = function (uniformName) {
  25099. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  25100. };
  25101. Effect.prototype.getSamplers = function () {
  25102. return this._samplers;
  25103. };
  25104. Effect.prototype.getCompilationError = function () {
  25105. return this._compilationError;
  25106. };
  25107. Effect.prototype.getVertexShaderSource = function () {
  25108. return this._evaluateDefinesOnString(this._engine.getVertexShaderSource(this._program));
  25109. };
  25110. Effect.prototype.getFragmentShaderSource = function () {
  25111. return this._evaluateDefinesOnString(this._engine.getFragmentShaderSource(this._program));
  25112. };
  25113. // Methods
  25114. Effect.prototype._loadVertexShader = function (vertex, callback) {
  25115. // DOM element ?
  25116. if (vertex instanceof HTMLElement) {
  25117. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  25118. callback(vertexCode);
  25119. return;
  25120. }
  25121. // Base64 encoded ?
  25122. if (vertex.substr(0, 7) === "base64:") {
  25123. var vertexBinary = window.atob(vertex.substr(7));
  25124. callback(vertexBinary);
  25125. return;
  25126. }
  25127. // Is in local store ?
  25128. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  25129. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  25130. return;
  25131. }
  25132. var vertexShaderUrl;
  25133. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  25134. vertexShaderUrl = vertex;
  25135. }
  25136. else {
  25137. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  25138. }
  25139. // Vertex shader
  25140. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  25141. };
  25142. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  25143. // DOM element ?
  25144. if (fragment instanceof HTMLElement) {
  25145. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  25146. callback(fragmentCode);
  25147. return;
  25148. }
  25149. // Base64 encoded ?
  25150. if (fragment.substr(0, 7) === "base64:") {
  25151. var fragmentBinary = window.atob(fragment.substr(7));
  25152. callback(fragmentBinary);
  25153. return;
  25154. }
  25155. // Is in local store ?
  25156. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  25157. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  25158. return;
  25159. }
  25160. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  25161. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  25162. return;
  25163. }
  25164. var fragmentShaderUrl;
  25165. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  25166. fragmentShaderUrl = fragment;
  25167. }
  25168. else {
  25169. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  25170. }
  25171. // Fragment shader
  25172. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  25173. };
  25174. Effect.prototype._dumpShadersName = function () {
  25175. if (this.name.vertexElement) {
  25176. BABYLON.Tools.Error("Vertex shader:" + this.name.vertexElement);
  25177. BABYLON.Tools.Error("Fragment shader:" + this.name.fragmentElement);
  25178. }
  25179. else if (this.name.vertex) {
  25180. BABYLON.Tools.Error("Vertex shader:" + this.name.vertex);
  25181. BABYLON.Tools.Error("Fragment shader:" + this.name.fragment);
  25182. }
  25183. else {
  25184. BABYLON.Tools.Error("Vertex shader:" + this.name);
  25185. BABYLON.Tools.Error("Fragment shader:" + this.name);
  25186. }
  25187. };
  25188. Effect.prototype._processIncludes = function (sourceCode, callback) {
  25189. var _this = this;
  25190. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  25191. var match = regex.exec(sourceCode);
  25192. var returnValue = new String(sourceCode);
  25193. while (match != null) {
  25194. var includeFile = match[1];
  25195. if (Effect.IncludesShadersStore[includeFile]) {
  25196. // Substitution
  25197. var includeContent = Effect.IncludesShadersStore[includeFile];
  25198. if (match[2]) {
  25199. var splits = match[3].split(",");
  25200. for (var index = 0; index < splits.length; index += 2) {
  25201. var source = new RegExp(splits[index], "g");
  25202. var dest = splits[index + 1];
  25203. includeContent = includeContent.replace(source, dest);
  25204. }
  25205. }
  25206. if (match[4]) {
  25207. var indexString = match[5];
  25208. if (indexString.indexOf("..") !== -1) {
  25209. var indexSplits = indexString.split("..");
  25210. var minIndex = parseInt(indexSplits[0]);
  25211. var maxIndex = parseInt(indexSplits[1]);
  25212. var sourceIncludeContent = includeContent.slice(0);
  25213. includeContent = "";
  25214. if (isNaN(maxIndex)) {
  25215. maxIndex = this._indexParameters[indexSplits[1]];
  25216. }
  25217. for (var i = minIndex; i <= maxIndex; i++) {
  25218. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  25219. }
  25220. }
  25221. else {
  25222. includeContent = includeContent.replace(/\{X\}/g, indexString);
  25223. }
  25224. }
  25225. // Replace
  25226. returnValue = returnValue.replace(match[0], includeContent);
  25227. }
  25228. else {
  25229. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  25230. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  25231. Effect.IncludesShadersStore[includeFile] = fileContent;
  25232. _this._processIncludes(returnValue, callback);
  25233. });
  25234. return;
  25235. }
  25236. match = regex.exec(sourceCode);
  25237. }
  25238. callback(returnValue);
  25239. };
  25240. Effect.prototype._processPrecision = function (source) {
  25241. if (source.indexOf("precision highp float") === -1) {
  25242. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25243. source = "precision mediump float;\n" + source;
  25244. }
  25245. else {
  25246. source = "precision highp float;\n" + source;
  25247. }
  25248. }
  25249. else {
  25250. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  25251. source = source.replace("precision highp float", "precision mediump float");
  25252. }
  25253. }
  25254. return source;
  25255. };
  25256. Effect.prototype._prepareEffect = function (vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks) {
  25257. try {
  25258. var engine = this._engine;
  25259. // Precision
  25260. vertexSourceCode = this._processPrecision(vertexSourceCode);
  25261. fragmentSourceCode = this._processPrecision(fragmentSourceCode);
  25262. this._program = engine.createShaderProgram(vertexSourceCode, fragmentSourceCode, defines);
  25263. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  25264. this._attributes = engine.getAttributes(this._program, attributesNames);
  25265. var index;
  25266. for (index = 0; index < this._samplers.length; index++) {
  25267. var sampler = this.getUniform(this._samplers[index]);
  25268. if (sampler == null) {
  25269. this._samplers.splice(index, 1);
  25270. index--;
  25271. }
  25272. }
  25273. engine.bindSamplers(this);
  25274. this._compilationError = "";
  25275. this._isReady = true;
  25276. if (this.onCompiled) {
  25277. this.onCompiled(this);
  25278. }
  25279. }
  25280. catch (e) {
  25281. this._compilationError = e.message;
  25282. // Let's go through fallbacks then
  25283. BABYLON.Tools.Error("Unable to compile effect: ");
  25284. BABYLON.Tools.Error("Defines: " + defines);
  25285. BABYLON.Tools.Error("Error: " + this._compilationError);
  25286. this._dumpShadersName();
  25287. if (fallbacks && fallbacks.isMoreFallbacks) {
  25288. BABYLON.Tools.Error("Trying next fallback.");
  25289. defines = fallbacks.reduce(defines);
  25290. this._prepareEffect(vertexSourceCode, fragmentSourceCode, attributesNames, defines, fallbacks);
  25291. }
  25292. else {
  25293. if (this.onError) {
  25294. this.onError(this, this._compilationError);
  25295. }
  25296. }
  25297. }
  25298. };
  25299. Object.defineProperty(Effect.prototype, "isSupported", {
  25300. get: function () {
  25301. return this._compilationError === "";
  25302. },
  25303. enumerable: true,
  25304. configurable: true
  25305. });
  25306. Effect.prototype._bindTexture = function (channel, texture) {
  25307. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  25308. };
  25309. Effect.prototype.setTexture = function (channel, texture) {
  25310. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  25311. };
  25312. Effect.prototype.setTextureArray = function (channel, textures) {
  25313. if (this._samplers.indexOf(channel + "Ex") === -1) {
  25314. var initialPos = this._samplers.indexOf(channel);
  25315. for (var index = 1; index < textures.length; index++) {
  25316. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  25317. }
  25318. }
  25319. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  25320. };
  25321. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  25322. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  25323. };
  25324. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  25325. var changed = false;
  25326. var cache = this._valueCache[uniformName];
  25327. if (!cache || !(cache instanceof BABYLON.Matrix)) {
  25328. changed = true;
  25329. cache = new BABYLON.Matrix();
  25330. }
  25331. var tm = cache.m;
  25332. var om = matrix.m;
  25333. for (var index = 0; index < 16; index++) {
  25334. if (tm[index] !== om[index]) {
  25335. tm[index] = om[index];
  25336. changed = true;
  25337. }
  25338. }
  25339. this._valueCache[uniformName] = cache;
  25340. return changed;
  25341. };
  25342. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  25343. var cache = this._valueCache[uniformName];
  25344. if (!cache) {
  25345. cache = [x, y];
  25346. this._valueCache[uniformName] = cache;
  25347. return true;
  25348. }
  25349. var changed = false;
  25350. if (cache[0] !== x) {
  25351. cache[0] = x;
  25352. changed = true;
  25353. }
  25354. if (cache[1] !== y) {
  25355. cache[1] = y;
  25356. changed = true;
  25357. }
  25358. return changed;
  25359. };
  25360. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  25361. var cache = this._valueCache[uniformName];
  25362. if (!cache) {
  25363. cache = [x, y, z];
  25364. this._valueCache[uniformName] = cache;
  25365. return true;
  25366. }
  25367. var changed = false;
  25368. if (cache[0] !== x) {
  25369. cache[0] = x;
  25370. changed = true;
  25371. }
  25372. if (cache[1] !== y) {
  25373. cache[1] = y;
  25374. changed = true;
  25375. }
  25376. if (cache[2] !== z) {
  25377. cache[2] = z;
  25378. changed = true;
  25379. }
  25380. return changed;
  25381. };
  25382. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  25383. var cache = this._valueCache[uniformName];
  25384. if (!cache) {
  25385. cache = [x, y, z, w];
  25386. this._valueCache[uniformName] = cache;
  25387. return true;
  25388. }
  25389. var changed = false;
  25390. if (cache[0] !== x) {
  25391. cache[0] = x;
  25392. changed = true;
  25393. }
  25394. if (cache[1] !== y) {
  25395. cache[1] = y;
  25396. changed = true;
  25397. }
  25398. if (cache[2] !== z) {
  25399. cache[2] = z;
  25400. changed = true;
  25401. }
  25402. if (cache[3] !== w) {
  25403. cache[3] = w;
  25404. changed = true;
  25405. }
  25406. return changed;
  25407. };
  25408. Effect.prototype.setIntArray = function (uniformName, array) {
  25409. this._valueCache[uniformName] = null;
  25410. this._engine.setIntArray(this.getUniform(uniformName), array);
  25411. return this;
  25412. };
  25413. Effect.prototype.setIntArray2 = function (uniformName, array) {
  25414. this._valueCache[uniformName] = null;
  25415. this._engine.setIntArray2(this.getUniform(uniformName), array);
  25416. return this;
  25417. };
  25418. Effect.prototype.setIntArray3 = function (uniformName, array) {
  25419. this._valueCache[uniformName] = null;
  25420. this._engine.setIntArray3(this.getUniform(uniformName), array);
  25421. return this;
  25422. };
  25423. Effect.prototype.setIntArray4 = function (uniformName, array) {
  25424. this._valueCache[uniformName] = null;
  25425. this._engine.setIntArray4(this.getUniform(uniformName), array);
  25426. return this;
  25427. };
  25428. Effect.prototype.setFloatArray = function (uniformName, array) {
  25429. this._valueCache[uniformName] = null;
  25430. this._engine.setFloatArray(this.getUniform(uniformName), array);
  25431. return this;
  25432. };
  25433. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  25434. this._valueCache[uniformName] = null;
  25435. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  25436. return this;
  25437. };
  25438. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  25439. this._valueCache[uniformName] = null;
  25440. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  25441. return this;
  25442. };
  25443. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  25444. this._valueCache[uniformName] = null;
  25445. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  25446. return this;
  25447. };
  25448. Effect.prototype.setArray = function (uniformName, array) {
  25449. this._valueCache[uniformName] = null;
  25450. this._engine.setArray(this.getUniform(uniformName), array);
  25451. return this;
  25452. };
  25453. Effect.prototype.setArray2 = function (uniformName, array) {
  25454. this._valueCache[uniformName] = null;
  25455. this._engine.setArray2(this.getUniform(uniformName), array);
  25456. return this;
  25457. };
  25458. Effect.prototype.setArray3 = function (uniformName, array) {
  25459. this._valueCache[uniformName] = null;
  25460. this._engine.setArray3(this.getUniform(uniformName), array);
  25461. return this;
  25462. };
  25463. Effect.prototype.setArray4 = function (uniformName, array) {
  25464. this._valueCache[uniformName] = null;
  25465. this._engine.setArray4(this.getUniform(uniformName), array);
  25466. return this;
  25467. };
  25468. Effect.prototype.setMatrices = function (uniformName, matrices) {
  25469. this._valueCache[uniformName] = null;
  25470. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  25471. return this;
  25472. };
  25473. Effect.prototype.setMatrix = function (uniformName, matrix) {
  25474. if (this._cacheMatrix(uniformName, matrix)) {
  25475. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  25476. }
  25477. return this;
  25478. };
  25479. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  25480. this._valueCache[uniformName] = null;
  25481. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  25482. return this;
  25483. };
  25484. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  25485. this._valueCache[uniformName] = null;
  25486. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  25487. return this;
  25488. };
  25489. Effect.prototype.setFloat = function (uniformName, value) {
  25490. var cache = this._valueCache[uniformName];
  25491. if (cache !== undefined && cache === value)
  25492. return this;
  25493. this._valueCache[uniformName] = value;
  25494. this._engine.setFloat(this.getUniform(uniformName), value);
  25495. return this;
  25496. };
  25497. Effect.prototype.setBool = function (uniformName, bool) {
  25498. var cache = this._valueCache[uniformName];
  25499. if (cache !== undefined && cache === bool)
  25500. return this;
  25501. this._valueCache[uniformName] = bool;
  25502. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  25503. return this;
  25504. };
  25505. Effect.prototype.setVector2 = function (uniformName, vector2) {
  25506. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  25507. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  25508. }
  25509. return this;
  25510. };
  25511. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  25512. if (this._cacheFloat2(uniformName, x, y)) {
  25513. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  25514. }
  25515. return this;
  25516. };
  25517. Effect.prototype.setVector3 = function (uniformName, vector3) {
  25518. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  25519. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  25520. }
  25521. return this;
  25522. };
  25523. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  25524. if (this._cacheFloat3(uniformName, x, y, z)) {
  25525. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  25526. }
  25527. return this;
  25528. };
  25529. Effect.prototype.setVector4 = function (uniformName, vector4) {
  25530. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  25531. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  25532. }
  25533. return this;
  25534. };
  25535. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  25536. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  25537. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  25538. }
  25539. return this;
  25540. };
  25541. Effect.prototype.setColor3 = function (uniformName, color3) {
  25542. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  25543. this._engine.setColor3(this.getUniform(uniformName), color3);
  25544. }
  25545. return this;
  25546. };
  25547. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  25548. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  25549. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  25550. }
  25551. return this;
  25552. };
  25553. Effect.prototype._recombineShader = function (node) {
  25554. if (node.define) {
  25555. if (node.condition) {
  25556. var defineIndex = this.defines.indexOf("#define " + node.define);
  25557. if (defineIndex === -1) {
  25558. return null;
  25559. }
  25560. var nextComma = this.defines.indexOf("\n", defineIndex);
  25561. var defineValue = this.defines.substr(defineIndex + 7, nextComma - defineIndex - 7).replace(node.define, "").trim();
  25562. var condition = defineValue + node.condition;
  25563. if (!eval(condition)) {
  25564. return null;
  25565. }
  25566. }
  25567. else if (node.ndef) {
  25568. if (this.defines.indexOf("#define " + node.define) !== -1) {
  25569. return null;
  25570. }
  25571. }
  25572. else if (this.defines.indexOf("#define " + node.define) === -1) {
  25573. return null;
  25574. }
  25575. }
  25576. var result = "";
  25577. for (var index = 0; index < node.children.length; index++) {
  25578. var line = node.children[index];
  25579. if (line.children) {
  25580. var combined = this._recombineShader(line);
  25581. if (combined !== null) {
  25582. result += combined + "\r\n";
  25583. }
  25584. continue;
  25585. }
  25586. if (line.length > 0) {
  25587. result += line + "\r\n";
  25588. }
  25589. }
  25590. return result;
  25591. };
  25592. Effect.prototype._evaluateDefinesOnString = function (shaderString) {
  25593. var root = {
  25594. children: []
  25595. };
  25596. var currentNode = root;
  25597. var lines = shaderString.split("\n");
  25598. for (var index = 0; index < lines.length; index++) {
  25599. var line = lines[index].trim();
  25600. // #ifdef
  25601. var pos = line.indexOf("#ifdef ");
  25602. if (pos !== -1) {
  25603. var define = line.substr(pos + 7);
  25604. var newNode = {
  25605. condition: null,
  25606. ndef: false,
  25607. define: define,
  25608. children: [],
  25609. parent: currentNode
  25610. };
  25611. currentNode.children.push(newNode);
  25612. currentNode = newNode;
  25613. continue;
  25614. }
  25615. // #ifndef
  25616. var pos = line.indexOf("#ifndef ");
  25617. if (pos !== -1) {
  25618. var define = line.substr(pos + 8);
  25619. newNode = {
  25620. condition: null,
  25621. define: define,
  25622. ndef: true,
  25623. children: [],
  25624. parent: currentNode
  25625. };
  25626. currentNode.children.push(newNode);
  25627. currentNode = newNode;
  25628. continue;
  25629. }
  25630. // #if
  25631. var pos = line.indexOf("#if ");
  25632. if (pos !== -1) {
  25633. var define = line.substr(pos + 4).trim();
  25634. var conditionPos = define.indexOf(" ");
  25635. newNode = {
  25636. condition: define.substr(conditionPos + 1),
  25637. define: define.substr(0, conditionPos),
  25638. ndef: false,
  25639. children: [],
  25640. parent: currentNode
  25641. };
  25642. currentNode.children.push(newNode);
  25643. currentNode = newNode;
  25644. continue;
  25645. }
  25646. // #endif
  25647. pos = line.indexOf("#endif");
  25648. if (pos !== -1) {
  25649. currentNode = currentNode.parent;
  25650. continue;
  25651. }
  25652. currentNode.children.push(line);
  25653. }
  25654. // Recombine
  25655. return this._recombineShader(root);
  25656. };
  25657. return Effect;
  25658. }());
  25659. // Statics
  25660. Effect.ShadersStore = {};
  25661. Effect.IncludesShadersStore = {};
  25662. BABYLON.Effect = Effect;
  25663. })(BABYLON || (BABYLON = {}));
  25664. //# sourceMappingURL=babylon.effect.js.map
  25665. var BABYLON;
  25666. (function (BABYLON) {
  25667. var MaterialHelper = (function () {
  25668. function MaterialHelper() {
  25669. }
  25670. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, maxSimultaneousLights) {
  25671. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25672. var lightIndex = 0;
  25673. var needNormals = false;
  25674. var needRebuild = false;
  25675. var needShadows = false;
  25676. var lightmapMode = false;
  25677. for (var index = 0; index < scene.lights.length; index++) {
  25678. var light = scene.lights[index];
  25679. if (!light.isEnabled()) {
  25680. continue;
  25681. }
  25682. // Excluded check
  25683. if (light._excludedMeshesIds.length > 0) {
  25684. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  25685. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  25686. if (excludedMesh) {
  25687. light.excludedMeshes.push(excludedMesh);
  25688. }
  25689. }
  25690. light._excludedMeshesIds = [];
  25691. }
  25692. // Included check
  25693. if (light._includedOnlyMeshesIds.length > 0) {
  25694. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  25695. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  25696. if (includedOnlyMesh) {
  25697. light.includedOnlyMeshes.push(includedOnlyMesh);
  25698. }
  25699. }
  25700. light._includedOnlyMeshesIds = [];
  25701. }
  25702. if (!light.canAffectMesh(mesh)) {
  25703. continue;
  25704. }
  25705. needNormals = true;
  25706. if (defines["LIGHT" + lightIndex] === undefined) {
  25707. needRebuild = true;
  25708. }
  25709. defines["LIGHT" + lightIndex] = true;
  25710. var type;
  25711. if (light instanceof BABYLON.SpotLight) {
  25712. type = "SPOTLIGHT" + lightIndex;
  25713. }
  25714. else if (light instanceof BABYLON.HemisphericLight) {
  25715. type = "HEMILIGHT" + lightIndex;
  25716. }
  25717. else if (light instanceof BABYLON.PointLight) {
  25718. type = "POINTLIGHT" + lightIndex;
  25719. }
  25720. else {
  25721. type = "DIRLIGHT" + lightIndex;
  25722. }
  25723. if (defines[type] === undefined) {
  25724. needRebuild = true;
  25725. }
  25726. defines[type] = true;
  25727. // Specular
  25728. if (!light.specular.equalsFloats(0, 0, 0) && defines["SPECULARTERM"] !== undefined) {
  25729. defines["SPECULARTERM"] = true;
  25730. }
  25731. // Shadows
  25732. if (scene.shadowsEnabled) {
  25733. var shadowGenerator = light.getShadowGenerator();
  25734. if (mesh && mesh.receiveShadows && shadowGenerator) {
  25735. if (defines["SHADOW" + lightIndex] === undefined) {
  25736. needRebuild = true;
  25737. }
  25738. defines["SHADOW" + lightIndex] = true;
  25739. defines["SHADOWS"] = true;
  25740. if (shadowGenerator.useVarianceShadowMap || shadowGenerator.useBlurVarianceShadowMap) {
  25741. if (defines["SHADOWVSM" + lightIndex] === undefined) {
  25742. needRebuild = true;
  25743. }
  25744. defines["SHADOWVSM" + lightIndex] = true;
  25745. }
  25746. if (shadowGenerator.usePoissonSampling) {
  25747. if (defines["SHADOWPCF" + lightIndex] === undefined) {
  25748. needRebuild = true;
  25749. }
  25750. defines["SHADOWPCF" + lightIndex] = true;
  25751. }
  25752. needShadows = true;
  25753. }
  25754. }
  25755. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  25756. lightmapMode = true;
  25757. if (defines["LIGHTMAPEXCLUDED" + lightIndex] === undefined) {
  25758. needRebuild = true;
  25759. }
  25760. if (defines["LIGHTMAPNOSPECULAR" + lightIndex] === undefined) {
  25761. needRebuild = true;
  25762. }
  25763. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  25764. if (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY) {
  25765. defines["LIGHTMAPNOSPECULAR" + lightIndex] = true;
  25766. }
  25767. }
  25768. lightIndex++;
  25769. if (lightIndex === maxSimultaneousLights)
  25770. break;
  25771. }
  25772. var caps = scene.getEngine().getCaps();
  25773. if (needShadows && caps.textureFloat && caps.textureFloatLinearFiltering && caps.textureFloatRender) {
  25774. if (defines["SHADOWFULLFLOAT"] === undefined) {
  25775. needRebuild = true;
  25776. }
  25777. defines["SHADOWFULLFLOAT"] = true;
  25778. }
  25779. if (defines["LIGHTMAPEXCLUDED"] === undefined) {
  25780. needRebuild = true;
  25781. }
  25782. if (lightmapMode) {
  25783. defines["LIGHTMAPEXCLUDED"] = true;
  25784. }
  25785. if (needRebuild) {
  25786. defines.rebuild();
  25787. }
  25788. return needNormals;
  25789. };
  25790. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsList, samplersList, defines, maxSimultaneousLights) {
  25791. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25792. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25793. if (!defines["LIGHT" + lightIndex]) {
  25794. break;
  25795. }
  25796. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex);
  25797. samplersList.push("shadowSampler" + lightIndex);
  25798. }
  25799. };
  25800. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  25801. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25802. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  25803. if (!defines["LIGHT" + lightIndex]) {
  25804. break;
  25805. }
  25806. if (lightIndex > 0) {
  25807. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  25808. }
  25809. if (defines["SHADOW" + lightIndex]) {
  25810. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  25811. }
  25812. if (defines["SHADOWPCF" + lightIndex]) {
  25813. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  25814. }
  25815. if (defines["SHADOWVSM" + lightIndex]) {
  25816. fallbacks.addFallback(0, "SHADOWVSM" + lightIndex);
  25817. }
  25818. }
  25819. };
  25820. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  25821. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  25822. fallbacks.addCPUSkinningFallback(0, mesh);
  25823. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  25824. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  25825. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  25826. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  25827. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  25828. }
  25829. }
  25830. };
  25831. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  25832. if (defines["INSTANCES"]) {
  25833. attribs.push("world0");
  25834. attribs.push("world1");
  25835. attribs.push("world2");
  25836. attribs.push("world3");
  25837. }
  25838. };
  25839. // Bindings
  25840. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect, depthValuesAlreadySet) {
  25841. var shadowGenerator = light.getShadowGenerator();
  25842. if (mesh.receiveShadows && shadowGenerator) {
  25843. if (!light.needCube()) {
  25844. effect.setMatrix("lightMatrix" + lightIndex, shadowGenerator.getTransformMatrix());
  25845. }
  25846. else {
  25847. if (!depthValuesAlreadySet) {
  25848. depthValuesAlreadySet = true;
  25849. effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.maxZ);
  25850. }
  25851. }
  25852. effect.setTexture("shadowSampler" + lightIndex, shadowGenerator.getShadowMapForRendering());
  25853. effect.setFloat3("shadowsInfo" + lightIndex, shadowGenerator.getDarkness(), shadowGenerator.blurScale / shadowGenerator.getShadowMap().getSize().width, shadowGenerator.bias);
  25854. }
  25855. return depthValuesAlreadySet;
  25856. };
  25857. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  25858. if (light instanceof BABYLON.PointLight) {
  25859. // Point Light
  25860. light.transferToEffect(effect, "vLightData" + lightIndex);
  25861. }
  25862. else if (light instanceof BABYLON.DirectionalLight) {
  25863. // Directional Light
  25864. light.transferToEffect(effect, "vLightData" + lightIndex);
  25865. }
  25866. else if (light instanceof BABYLON.SpotLight) {
  25867. // Spot Light
  25868. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightDirection" + lightIndex);
  25869. }
  25870. else if (light instanceof BABYLON.HemisphericLight) {
  25871. // Hemispheric Light
  25872. light.transferToEffect(effect, "vLightData" + lightIndex, "vLightGround" + lightIndex);
  25873. }
  25874. };
  25875. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights) {
  25876. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  25877. var lightIndex = 0;
  25878. var depthValuesAlreadySet = false;
  25879. for (var index = 0; index < scene.lights.length; index++) {
  25880. var light = scene.lights[index];
  25881. if (!light.isEnabled()) {
  25882. continue;
  25883. }
  25884. if (!light.canAffectMesh(mesh)) {
  25885. continue;
  25886. }
  25887. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  25888. light.diffuse.scaleToRef(light.intensity, BABYLON.Tmp.Color3[0]);
  25889. effect.setColor4("vLightDiffuse" + lightIndex, BABYLON.Tmp.Color3[0], light.range);
  25890. if (defines["SPECULARTERM"]) {
  25891. light.specular.scaleToRef(light.intensity, BABYLON.Tmp.Color3[1]);
  25892. effect.setColor3("vLightSpecular" + lightIndex, BABYLON.Tmp.Color3[1]);
  25893. }
  25894. // Shadows
  25895. if (scene.shadowsEnabled) {
  25896. depthValuesAlreadySet = this.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  25897. }
  25898. lightIndex++;
  25899. if (lightIndex === maxSimultaneousLights)
  25900. break;
  25901. }
  25902. };
  25903. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  25904. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  25905. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  25906. effect.setColor3("vFogColor", scene.fogColor);
  25907. }
  25908. };
  25909. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  25910. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  25911. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  25912. if (matrices) {
  25913. effect.setMatrices("mBones", matrices);
  25914. }
  25915. }
  25916. };
  25917. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25918. if (defines["LOGARITHMICDEPTH"]) {
  25919. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25920. }
  25921. };
  25922. MaterialHelper.BindClipPlane = function (effect, scene) {
  25923. if (scene.clipPlane) {
  25924. var clipPlane = scene.clipPlane;
  25925. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25926. }
  25927. };
  25928. return MaterialHelper;
  25929. }());
  25930. BABYLON.MaterialHelper = MaterialHelper;
  25931. })(BABYLON || (BABYLON = {}));
  25932. //# sourceMappingURL=babylon.materialHelper.js.map
  25933. var BABYLON;
  25934. (function (BABYLON) {
  25935. var FresnelParameters = (function () {
  25936. function FresnelParameters() {
  25937. this.isEnabled = true;
  25938. this.leftColor = BABYLON.Color3.White();
  25939. this.rightColor = BABYLON.Color3.Black();
  25940. this.bias = 0;
  25941. this.power = 1;
  25942. }
  25943. FresnelParameters.prototype.clone = function () {
  25944. var newFresnelParameters = new FresnelParameters();
  25945. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  25946. return newFresnelParameters;
  25947. };
  25948. FresnelParameters.prototype.serialize = function () {
  25949. var serializationObject = {};
  25950. serializationObject.isEnabled = this.isEnabled;
  25951. serializationObject.leftColor = this.leftColor;
  25952. serializationObject.rightColor = this.rightColor;
  25953. serializationObject.bias = this.bias;
  25954. serializationObject.power = this.power;
  25955. return serializationObject;
  25956. };
  25957. FresnelParameters.Parse = function (parsedFresnelParameters) {
  25958. var fresnelParameters = new FresnelParameters();
  25959. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  25960. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  25961. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  25962. fresnelParameters.bias = parsedFresnelParameters.bias;
  25963. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  25964. return fresnelParameters;
  25965. };
  25966. return FresnelParameters;
  25967. }());
  25968. BABYLON.FresnelParameters = FresnelParameters;
  25969. })(BABYLON || (BABYLON = {}));
  25970. //# sourceMappingURL=babylon.fresnelParameters.js.map
  25971. var BABYLON;
  25972. (function (BABYLON) {
  25973. var MaterialDefines = (function () {
  25974. function MaterialDefines() {
  25975. }
  25976. MaterialDefines.prototype.rebuild = function () {
  25977. if (this._keys) {
  25978. delete this._keys;
  25979. }
  25980. this._keys = Object.keys(this);
  25981. };
  25982. MaterialDefines.prototype.isEqual = function (other) {
  25983. if (this._keys.length !== other._keys.length) {
  25984. return false;
  25985. }
  25986. for (var index = 0; index < this._keys.length; index++) {
  25987. var prop = this._keys[index];
  25988. if (this[prop] !== other[prop]) {
  25989. return false;
  25990. }
  25991. }
  25992. return true;
  25993. };
  25994. MaterialDefines.prototype.cloneTo = function (other) {
  25995. if (this._keys.length !== other._keys.length) {
  25996. other._keys = this._keys.slice(0);
  25997. }
  25998. for (var index = 0; index < this._keys.length; index++) {
  25999. var prop = this._keys[index];
  26000. other[prop] = this[prop];
  26001. }
  26002. };
  26003. MaterialDefines.prototype.reset = function () {
  26004. for (var index = 0; index < this._keys.length; index++) {
  26005. var prop = this._keys[index];
  26006. if (typeof (this[prop]) === "number") {
  26007. this[prop] = 0;
  26008. }
  26009. else {
  26010. this[prop] = false;
  26011. }
  26012. }
  26013. };
  26014. MaterialDefines.prototype.toString = function () {
  26015. var result = "";
  26016. for (var index = 0; index < this._keys.length; index++) {
  26017. var prop = this._keys[index];
  26018. if (typeof (this[prop]) === "number") {
  26019. result += "#define " + prop + " " + this[prop] + "\n";
  26020. }
  26021. else if (this[prop]) {
  26022. result += "#define " + prop + "\n";
  26023. }
  26024. }
  26025. return result;
  26026. };
  26027. return MaterialDefines;
  26028. }());
  26029. BABYLON.MaterialDefines = MaterialDefines;
  26030. var Material = (function () {
  26031. function Material(name, scene, doNotAdd) {
  26032. this.checkReadyOnEveryCall = false;
  26033. this.checkReadyOnlyOnce = false;
  26034. this.state = "";
  26035. this.alpha = 1.0;
  26036. this.backFaceCulling = true;
  26037. this.doNotSerialize = false;
  26038. /**
  26039. * An event triggered when the material is disposed.
  26040. * @type {BABYLON.Observable}
  26041. */
  26042. this.onDisposeObservable = new BABYLON.Observable();
  26043. /**
  26044. * An event triggered when the material is bound.
  26045. * @type {BABYLON.Observable}
  26046. */
  26047. this.onBindObservable = new BABYLON.Observable();
  26048. /**
  26049. * An event triggered when the material is unbound.
  26050. * @type {BABYLON.Observable}
  26051. */
  26052. this.onUnBindObservable = new BABYLON.Observable();
  26053. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  26054. this.disableDepthWrite = false;
  26055. this.fogEnabled = true;
  26056. this.pointSize = 1.0;
  26057. this.zOffset = 0;
  26058. this._wasPreviouslyReady = false;
  26059. this._fillMode = Material.TriangleFillMode;
  26060. this.name = name;
  26061. this.id = name;
  26062. this._scene = scene;
  26063. if (scene.useRightHandedSystem) {
  26064. this.sideOrientation = Material.ClockWiseSideOrientation;
  26065. }
  26066. else {
  26067. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  26068. }
  26069. if (!doNotAdd) {
  26070. scene.materials.push(this);
  26071. }
  26072. }
  26073. Object.defineProperty(Material, "TriangleFillMode", {
  26074. get: function () {
  26075. return Material._TriangleFillMode;
  26076. },
  26077. enumerable: true,
  26078. configurable: true
  26079. });
  26080. Object.defineProperty(Material, "WireFrameFillMode", {
  26081. get: function () {
  26082. return Material._WireFrameFillMode;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. Object.defineProperty(Material, "PointFillMode", {
  26088. get: function () {
  26089. return Material._PointFillMode;
  26090. },
  26091. enumerable: true,
  26092. configurable: true
  26093. });
  26094. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  26095. get: function () {
  26096. return Material._ClockWiseSideOrientation;
  26097. },
  26098. enumerable: true,
  26099. configurable: true
  26100. });
  26101. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  26102. get: function () {
  26103. return Material._CounterClockWiseSideOrientation;
  26104. },
  26105. enumerable: true,
  26106. configurable: true
  26107. });
  26108. Object.defineProperty(Material.prototype, "onDispose", {
  26109. set: function (callback) {
  26110. if (this._onDisposeObserver) {
  26111. this.onDisposeObservable.remove(this._onDisposeObserver);
  26112. }
  26113. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  26114. },
  26115. enumerable: true,
  26116. configurable: true
  26117. });
  26118. Object.defineProperty(Material.prototype, "onBind", {
  26119. set: function (callback) {
  26120. if (this._onBindObserver) {
  26121. this.onBindObservable.remove(this._onBindObserver);
  26122. }
  26123. this._onBindObserver = this.onBindObservable.add(callback);
  26124. },
  26125. enumerable: true,
  26126. configurable: true
  26127. });
  26128. Object.defineProperty(Material.prototype, "wireframe", {
  26129. get: function () {
  26130. return this._fillMode === Material.WireFrameFillMode;
  26131. },
  26132. set: function (value) {
  26133. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  26134. },
  26135. enumerable: true,
  26136. configurable: true
  26137. });
  26138. Object.defineProperty(Material.prototype, "pointsCloud", {
  26139. get: function () {
  26140. return this._fillMode === Material.PointFillMode;
  26141. },
  26142. set: function (value) {
  26143. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  26144. },
  26145. enumerable: true,
  26146. configurable: true
  26147. });
  26148. Object.defineProperty(Material.prototype, "fillMode", {
  26149. get: function () {
  26150. return this._fillMode;
  26151. },
  26152. set: function (value) {
  26153. this._fillMode = value;
  26154. },
  26155. enumerable: true,
  26156. configurable: true
  26157. });
  26158. /**
  26159. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  26160. * subclasses should override adding information pertainent to themselves
  26161. */
  26162. Material.prototype.toString = function (fullDetails) {
  26163. var ret = "Name: " + this.name;
  26164. if (fullDetails) {
  26165. }
  26166. return ret;
  26167. };
  26168. Material.prototype.getClassName = function () {
  26169. return "Material";
  26170. };
  26171. Object.defineProperty(Material.prototype, "isFrozen", {
  26172. get: function () {
  26173. return this.checkReadyOnlyOnce;
  26174. },
  26175. enumerable: true,
  26176. configurable: true
  26177. });
  26178. Material.prototype.freeze = function () {
  26179. this.checkReadyOnlyOnce = true;
  26180. };
  26181. Material.prototype.unfreeze = function () {
  26182. this.checkReadyOnlyOnce = false;
  26183. };
  26184. Material.prototype.isReady = function (mesh, useInstances) {
  26185. return true;
  26186. };
  26187. Material.prototype.getEffect = function () {
  26188. return this._effect;
  26189. };
  26190. Material.prototype.getScene = function () {
  26191. return this._scene;
  26192. };
  26193. Material.prototype.needAlphaBlending = function () {
  26194. return (this.alpha < 1.0);
  26195. };
  26196. Material.prototype.needAlphaTesting = function () {
  26197. return false;
  26198. };
  26199. Material.prototype.getAlphaTestTexture = function () {
  26200. return null;
  26201. };
  26202. Material.prototype.markDirty = function () {
  26203. this._wasPreviouslyReady = false;
  26204. };
  26205. Material.prototype._preBind = function () {
  26206. var engine = this._scene.getEngine();
  26207. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  26208. engine.enableEffect(this._effect);
  26209. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  26210. };
  26211. Material.prototype.bind = function (world, mesh) {
  26212. this._scene._cachedMaterial = this;
  26213. this.onBindObservable.notifyObservers(mesh);
  26214. if (this.disableDepthWrite) {
  26215. var engine = this._scene.getEngine();
  26216. this._cachedDepthWriteState = engine.getDepthWrite();
  26217. engine.setDepthWrite(false);
  26218. }
  26219. };
  26220. Material.prototype.bindOnlyWorldMatrix = function (world) {
  26221. };
  26222. Material.prototype.unbind = function () {
  26223. this.onUnBindObservable.notifyObservers(this);
  26224. if (this.disableDepthWrite) {
  26225. var engine = this._scene.getEngine();
  26226. engine.setDepthWrite(this._cachedDepthWriteState);
  26227. }
  26228. };
  26229. Material.prototype.clone = function (name) {
  26230. return null;
  26231. };
  26232. Material.prototype.getBindedMeshes = function () {
  26233. var result = new Array();
  26234. for (var index = 0; index < this._scene.meshes.length; index++) {
  26235. var mesh = this._scene.meshes[index];
  26236. if (mesh.material === this) {
  26237. result.push(mesh);
  26238. }
  26239. }
  26240. return result;
  26241. };
  26242. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  26243. // Animations
  26244. this.getScene().stopAnimation(this);
  26245. // Remove from scene
  26246. var index = this._scene.materials.indexOf(this);
  26247. if (index >= 0) {
  26248. this._scene.materials.splice(index, 1);
  26249. }
  26250. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  26251. if (forceDisposeEffect && this._effect) {
  26252. this._scene.getEngine()._releaseEffect(this._effect);
  26253. this._effect = null;
  26254. }
  26255. // Remove from meshes
  26256. for (index = 0; index < this._scene.meshes.length; index++) {
  26257. var mesh = this._scene.meshes[index];
  26258. if (mesh.material === this) {
  26259. mesh.material = null;
  26260. }
  26261. }
  26262. // Callback
  26263. this.onDisposeObservable.notifyObservers(this);
  26264. this.onDisposeObservable.clear();
  26265. this.onBindObservable.clear();
  26266. this.onUnBindObservable.clear();
  26267. };
  26268. Material.prototype.serialize = function () {
  26269. return BABYLON.SerializationHelper.Serialize(this);
  26270. };
  26271. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  26272. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  26273. multiMaterial.id = parsedMultiMaterial.id;
  26274. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  26275. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  26276. var subMatId = parsedMultiMaterial.materials[matIndex];
  26277. if (subMatId) {
  26278. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  26279. }
  26280. else {
  26281. multiMaterial.subMaterials.push(null);
  26282. }
  26283. }
  26284. return multiMaterial;
  26285. };
  26286. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  26287. if (!parsedMaterial.customType) {
  26288. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  26289. }
  26290. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  26291. return materialType.Parse(parsedMaterial, scene, rootUrl);
  26292. ;
  26293. };
  26294. return Material;
  26295. }());
  26296. Material._TriangleFillMode = 0;
  26297. Material._WireFrameFillMode = 1;
  26298. Material._PointFillMode = 2;
  26299. Material._ClockWiseSideOrientation = 0;
  26300. Material._CounterClockWiseSideOrientation = 1;
  26301. __decorate([
  26302. BABYLON.serialize()
  26303. ], Material.prototype, "id", void 0);
  26304. __decorate([
  26305. BABYLON.serialize()
  26306. ], Material.prototype, "name", void 0);
  26307. __decorate([
  26308. BABYLON.serialize()
  26309. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  26310. __decorate([
  26311. BABYLON.serialize()
  26312. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  26313. __decorate([
  26314. BABYLON.serialize()
  26315. ], Material.prototype, "state", void 0);
  26316. __decorate([
  26317. BABYLON.serialize()
  26318. ], Material.prototype, "alpha", void 0);
  26319. __decorate([
  26320. BABYLON.serialize()
  26321. ], Material.prototype, "backFaceCulling", void 0);
  26322. __decorate([
  26323. BABYLON.serialize()
  26324. ], Material.prototype, "sideOrientation", void 0);
  26325. __decorate([
  26326. BABYLON.serialize()
  26327. ], Material.prototype, "alphaMode", void 0);
  26328. __decorate([
  26329. BABYLON.serialize()
  26330. ], Material.prototype, "disableDepthWrite", void 0);
  26331. __decorate([
  26332. BABYLON.serialize()
  26333. ], Material.prototype, "fogEnabled", void 0);
  26334. __decorate([
  26335. BABYLON.serialize()
  26336. ], Material.prototype, "pointSize", void 0);
  26337. __decorate([
  26338. BABYLON.serialize()
  26339. ], Material.prototype, "zOffset", void 0);
  26340. __decorate([
  26341. BABYLON.serialize()
  26342. ], Material.prototype, "wireframe", null);
  26343. __decorate([
  26344. BABYLON.serialize()
  26345. ], Material.prototype, "pointsCloud", null);
  26346. __decorate([
  26347. BABYLON.serialize()
  26348. ], Material.prototype, "fillMode", null);
  26349. BABYLON.Material = Material;
  26350. })(BABYLON || (BABYLON = {}));
  26351. //# sourceMappingURL=babylon.material.js.map
  26352. var BABYLON;
  26353. (function (BABYLON) {
  26354. var StandardMaterialDefines = (function (_super) {
  26355. __extends(StandardMaterialDefines, _super);
  26356. function StandardMaterialDefines() {
  26357. var _this = _super.call(this) || this;
  26358. _this.DIFFUSE = false;
  26359. _this.AMBIENT = false;
  26360. _this.OPACITY = false;
  26361. _this.OPACITYRGB = false;
  26362. _this.REFLECTION = false;
  26363. _this.EMISSIVE = false;
  26364. _this.SPECULAR = false;
  26365. _this.BUMP = false;
  26366. _this.PARALLAX = false;
  26367. _this.PARALLAXOCCLUSION = false;
  26368. _this.SPECULAROVERALPHA = false;
  26369. _this.CLIPPLANE = false;
  26370. _this.ALPHATEST = false;
  26371. _this.ALPHAFROMDIFFUSE = false;
  26372. _this.POINTSIZE = false;
  26373. _this.FOG = false;
  26374. _this.SPECULARTERM = false;
  26375. _this.DIFFUSEFRESNEL = false;
  26376. _this.OPACITYFRESNEL = false;
  26377. _this.REFLECTIONFRESNEL = false;
  26378. _this.REFRACTIONFRESNEL = false;
  26379. _this.EMISSIVEFRESNEL = false;
  26380. _this.FRESNEL = false;
  26381. _this.NORMAL = false;
  26382. _this.UV1 = false;
  26383. _this.UV2 = false;
  26384. _this.VERTEXCOLOR = false;
  26385. _this.VERTEXALPHA = false;
  26386. _this.NUM_BONE_INFLUENCERS = 0;
  26387. _this.BonesPerMesh = 0;
  26388. _this.INSTANCES = false;
  26389. _this.GLOSSINESS = false;
  26390. _this.ROUGHNESS = false;
  26391. _this.EMISSIVEASILLUMINATION = false;
  26392. _this.LINKEMISSIVEWITHDIFFUSE = false;
  26393. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  26394. _this.LIGHTMAP = false;
  26395. _this.USELIGHTMAPASSHADOWMAP = false;
  26396. _this.REFLECTIONMAP_3D = false;
  26397. _this.REFLECTIONMAP_SPHERICAL = false;
  26398. _this.REFLECTIONMAP_PLANAR = false;
  26399. _this.REFLECTIONMAP_CUBIC = false;
  26400. _this.REFLECTIONMAP_PROJECTION = false;
  26401. _this.REFLECTIONMAP_SKYBOX = false;
  26402. _this.REFLECTIONMAP_EXPLICIT = false;
  26403. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  26404. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  26405. _this.INVERTCUBICMAP = false;
  26406. _this.LOGARITHMICDEPTH = false;
  26407. _this.REFRACTION = false;
  26408. _this.REFRACTIONMAP_3D = false;
  26409. _this.REFLECTIONOVERALPHA = false;
  26410. _this.INVERTNORMALMAPX = false;
  26411. _this.INVERTNORMALMAPY = false;
  26412. _this.SHADOWFULLFLOAT = false;
  26413. _this.CAMERACOLORGRADING = false;
  26414. _this.CAMERACOLORCURVES = false;
  26415. _this.rebuild();
  26416. return _this;
  26417. }
  26418. return StandardMaterialDefines;
  26419. }(BABYLON.MaterialDefines));
  26420. var StandardMaterial = (function (_super) {
  26421. __extends(StandardMaterial, _super);
  26422. function StandardMaterial(name, scene) {
  26423. var _this = _super.call(this, name, scene) || this;
  26424. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  26425. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  26426. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  26427. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  26428. _this.specularPower = 64;
  26429. _this.useAlphaFromDiffuseTexture = false;
  26430. _this.useEmissiveAsIllumination = false;
  26431. _this.linkEmissiveWithDiffuse = false;
  26432. _this.useReflectionFresnelFromSpecular = false;
  26433. _this.useSpecularOverAlpha = false;
  26434. _this.useReflectionOverAlpha = false;
  26435. _this.disableLighting = false;
  26436. _this.useParallax = false;
  26437. _this.useParallaxOcclusion = false;
  26438. _this.parallaxScaleBias = 0.05;
  26439. _this.roughness = 0;
  26440. _this.indexOfRefraction = 0.98;
  26441. _this.invertRefractionY = true;
  26442. _this.useLightmapAsShadowmap = false;
  26443. _this.useGlossinessFromSpecularMapAlpha = false;
  26444. _this.maxSimultaneousLights = 4;
  26445. /**
  26446. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  26447. */
  26448. _this.invertNormalMapX = false;
  26449. /**
  26450. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  26451. */
  26452. _this.invertNormalMapY = false;
  26453. /**
  26454. * Color Grading 2D Lookup Texture.
  26455. * This allows special effects like sepia, black and white to sixties rendering style.
  26456. */
  26457. _this.cameraColorGradingTexture = null;
  26458. /**
  26459. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  26460. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  26461. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  26462. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  26463. */
  26464. _this.cameraColorCurves = null;
  26465. _this._renderTargets = new BABYLON.SmartArray(16);
  26466. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  26467. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  26468. _this._defines = new StandardMaterialDefines();
  26469. _this._cachedDefines = new StandardMaterialDefines();
  26470. _this._cachedDefines.BonesPerMesh = -1;
  26471. _this.getRenderTargetTextures = function () {
  26472. _this._renderTargets.reset();
  26473. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  26474. _this._renderTargets.push(_this.reflectionTexture);
  26475. }
  26476. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  26477. _this._renderTargets.push(_this.refractionTexture);
  26478. }
  26479. return _this._renderTargets;
  26480. };
  26481. return _this;
  26482. }
  26483. StandardMaterial.prototype.getClassName = function () {
  26484. return "StandardMaterial";
  26485. };
  26486. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  26487. get: function () {
  26488. return this._useLogarithmicDepth;
  26489. },
  26490. set: function (value) {
  26491. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  26492. },
  26493. enumerable: true,
  26494. configurable: true
  26495. });
  26496. StandardMaterial.prototype.needAlphaBlending = function () {
  26497. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  26498. };
  26499. StandardMaterial.prototype.needAlphaTesting = function () {
  26500. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha;
  26501. };
  26502. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  26503. return this.diffuseTexture != null && this.diffuseTexture.hasAlpha && this.useAlphaFromDiffuseTexture;
  26504. };
  26505. StandardMaterial.prototype.getAlphaTestTexture = function () {
  26506. return this.diffuseTexture;
  26507. };
  26508. // Methods
  26509. StandardMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  26510. if (!mesh) {
  26511. return true;
  26512. }
  26513. if (this._defines.INSTANCES !== useInstances) {
  26514. return false;
  26515. }
  26516. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  26517. return true;
  26518. }
  26519. return false;
  26520. };
  26521. StandardMaterial.prototype.isReady = function (mesh, useInstances) {
  26522. if (this.isFrozen) {
  26523. if (this._wasPreviouslyReady) {
  26524. return true;
  26525. }
  26526. }
  26527. var scene = this.getScene();
  26528. var engine = scene.getEngine();
  26529. var needUVs = false;
  26530. var needNormals = false;
  26531. this._defines.reset();
  26532. // Lights
  26533. if (scene.lightsEnabled && !this.disableLighting) {
  26534. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights);
  26535. }
  26536. if (!this.checkReadyOnEveryCall) {
  26537. if (this._renderId === scene.getRenderId()) {
  26538. if (this._checkCache(scene, mesh, useInstances)) {
  26539. return true;
  26540. }
  26541. }
  26542. }
  26543. // Textures
  26544. if (scene.texturesEnabled) {
  26545. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26546. if (!this.diffuseTexture.isReady()) {
  26547. return false;
  26548. }
  26549. else {
  26550. needUVs = true;
  26551. this._defines.DIFFUSE = true;
  26552. }
  26553. }
  26554. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26555. if (!this.ambientTexture.isReady()) {
  26556. return false;
  26557. }
  26558. else {
  26559. needUVs = true;
  26560. this._defines.AMBIENT = true;
  26561. }
  26562. }
  26563. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26564. if (!this.opacityTexture.isReady()) {
  26565. return false;
  26566. }
  26567. else {
  26568. needUVs = true;
  26569. this._defines.OPACITY = true;
  26570. if (this.opacityTexture.getAlphaFromRGB) {
  26571. this._defines.OPACITYRGB = true;
  26572. }
  26573. }
  26574. }
  26575. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26576. if (!this.reflectionTexture.isReady()) {
  26577. return false;
  26578. }
  26579. else {
  26580. needNormals = true;
  26581. this._defines.REFLECTION = true;
  26582. if (this.roughness > 0) {
  26583. this._defines.ROUGHNESS = true;
  26584. }
  26585. if (this.useReflectionOverAlpha) {
  26586. this._defines.REFLECTIONOVERALPHA = true;
  26587. }
  26588. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  26589. this._defines.INVERTCUBICMAP = true;
  26590. }
  26591. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  26592. switch (this.reflectionTexture.coordinatesMode) {
  26593. case BABYLON.Texture.CUBIC_MODE:
  26594. case BABYLON.Texture.INVCUBIC_MODE:
  26595. this._defines.REFLECTIONMAP_CUBIC = true;
  26596. break;
  26597. case BABYLON.Texture.EXPLICIT_MODE:
  26598. this._defines.REFLECTIONMAP_EXPLICIT = true;
  26599. break;
  26600. case BABYLON.Texture.PLANAR_MODE:
  26601. this._defines.REFLECTIONMAP_PLANAR = true;
  26602. break;
  26603. case BABYLON.Texture.PROJECTION_MODE:
  26604. this._defines.REFLECTIONMAP_PROJECTION = true;
  26605. break;
  26606. case BABYLON.Texture.SKYBOX_MODE:
  26607. this._defines.REFLECTIONMAP_SKYBOX = true;
  26608. break;
  26609. case BABYLON.Texture.SPHERICAL_MODE:
  26610. this._defines.REFLECTIONMAP_SPHERICAL = true;
  26611. break;
  26612. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  26613. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  26614. break;
  26615. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  26616. this._defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  26617. break;
  26618. }
  26619. }
  26620. }
  26621. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26622. if (!this.emissiveTexture.isReady()) {
  26623. return false;
  26624. }
  26625. else {
  26626. needUVs = true;
  26627. this._defines.EMISSIVE = true;
  26628. }
  26629. }
  26630. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26631. if (!this.lightmapTexture.isReady()) {
  26632. return false;
  26633. }
  26634. else {
  26635. needUVs = true;
  26636. this._defines.LIGHTMAP = true;
  26637. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  26638. }
  26639. }
  26640. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26641. if (!this.specularTexture.isReady()) {
  26642. return false;
  26643. }
  26644. else {
  26645. needUVs = true;
  26646. this._defines.SPECULAR = true;
  26647. this._defines.GLOSSINESS = this.useGlossinessFromSpecularMapAlpha;
  26648. }
  26649. }
  26650. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && StandardMaterial.BumpTextureEnabled) {
  26651. if (!this.bumpTexture.isReady()) {
  26652. return false;
  26653. }
  26654. else {
  26655. needUVs = true;
  26656. this._defines.BUMP = true;
  26657. if (this.useParallax) {
  26658. this._defines.PARALLAX = true;
  26659. if (this.useParallaxOcclusion) {
  26660. this._defines.PARALLAXOCCLUSION = true;
  26661. }
  26662. }
  26663. if (this.invertNormalMapX) {
  26664. this._defines.INVERTNORMALMAPX = true;
  26665. }
  26666. if (this.invertNormalMapY) {
  26667. this._defines.INVERTNORMALMAPY = true;
  26668. }
  26669. if (scene._mirroredCameraPosition) {
  26670. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  26671. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  26672. }
  26673. }
  26674. }
  26675. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26676. if (!this.refractionTexture.isReady()) {
  26677. return false;
  26678. }
  26679. else {
  26680. needUVs = true;
  26681. this._defines.REFRACTION = true;
  26682. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  26683. }
  26684. }
  26685. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26686. if (!this.cameraColorGradingTexture.isReady()) {
  26687. return false;
  26688. }
  26689. else {
  26690. this._defines.CAMERACOLORGRADING = true;
  26691. }
  26692. }
  26693. }
  26694. // Effect
  26695. if (scene.clipPlane) {
  26696. this._defines.CLIPPLANE = true;
  26697. }
  26698. if (engine.getAlphaTesting()) {
  26699. this._defines.ALPHATEST = true;
  26700. }
  26701. if (this._shouldUseAlphaFromDiffuseTexture()) {
  26702. this._defines.ALPHAFROMDIFFUSE = true;
  26703. }
  26704. if (this.useEmissiveAsIllumination) {
  26705. this._defines.EMISSIVEASILLUMINATION = true;
  26706. }
  26707. if (this.linkEmissiveWithDiffuse) {
  26708. this._defines.LINKEMISSIVEWITHDIFFUSE = true;
  26709. }
  26710. if (this.useLogarithmicDepth) {
  26711. this._defines.LOGARITHMICDEPTH = true;
  26712. }
  26713. if (this.cameraColorCurves) {
  26714. this._defines.CAMERACOLORCURVES = true;
  26715. }
  26716. // Point size
  26717. if (this.pointsCloud || scene.forcePointsCloud) {
  26718. this._defines.POINTSIZE = true;
  26719. }
  26720. // Fog
  26721. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  26722. this._defines.FOG = true;
  26723. }
  26724. if (StandardMaterial.FresnelEnabled) {
  26725. // Fresnel
  26726. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled ||
  26727. this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  26728. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled ||
  26729. this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled ||
  26730. this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26731. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26732. this._defines.DIFFUSEFRESNEL = true;
  26733. }
  26734. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26735. this._defines.OPACITYFRESNEL = true;
  26736. }
  26737. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26738. this._defines.REFLECTIONFRESNEL = true;
  26739. if (this.useReflectionFresnelFromSpecular) {
  26740. this._defines.REFLECTIONFRESNELFROMSPECULAR = true;
  26741. }
  26742. }
  26743. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26744. this._defines.REFRACTIONFRESNEL = true;
  26745. }
  26746. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26747. this._defines.EMISSIVEFRESNEL = true;
  26748. }
  26749. needNormals = true;
  26750. this._defines.FRESNEL = true;
  26751. }
  26752. }
  26753. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  26754. this._defines.SPECULAROVERALPHA = true;
  26755. }
  26756. // Attribs
  26757. if (mesh) {
  26758. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26759. this._defines.NORMAL = true;
  26760. }
  26761. if (needUVs) {
  26762. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26763. this._defines.UV1 = true;
  26764. }
  26765. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26766. this._defines.UV2 = true;
  26767. }
  26768. }
  26769. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26770. this._defines.VERTEXCOLOR = true;
  26771. if (mesh.hasVertexAlpha) {
  26772. this._defines.VERTEXALPHA = true;
  26773. }
  26774. }
  26775. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  26776. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  26777. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  26778. }
  26779. // Instances
  26780. if (useInstances) {
  26781. this._defines.INSTANCES = true;
  26782. }
  26783. }
  26784. // Get correct effect
  26785. if (!this._defines.isEqual(this._cachedDefines)) {
  26786. this._defines.cloneTo(this._cachedDefines);
  26787. scene.resetCachedMaterial();
  26788. // Fallbacks
  26789. var fallbacks = new BABYLON.EffectFallbacks();
  26790. if (this._defines.REFLECTION) {
  26791. fallbacks.addFallback(0, "REFLECTION");
  26792. }
  26793. if (this._defines.SPECULAR) {
  26794. fallbacks.addFallback(0, "SPECULAR");
  26795. }
  26796. if (this._defines.BUMP) {
  26797. fallbacks.addFallback(0, "BUMP");
  26798. }
  26799. if (this._defines.PARALLAX) {
  26800. fallbacks.addFallback(1, "PARALLAX");
  26801. }
  26802. if (this._defines.PARALLAXOCCLUSION) {
  26803. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  26804. }
  26805. if (this._defines.SPECULAROVERALPHA) {
  26806. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  26807. }
  26808. if (this._defines.FOG) {
  26809. fallbacks.addFallback(1, "FOG");
  26810. }
  26811. if (this._defines.POINTSIZE) {
  26812. fallbacks.addFallback(0, "POINTSIZE");
  26813. }
  26814. if (this._defines.LOGARITHMICDEPTH) {
  26815. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  26816. }
  26817. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  26818. if (this._defines.SPECULARTERM) {
  26819. fallbacks.addFallback(0, "SPECULARTERM");
  26820. }
  26821. if (this._defines.DIFFUSEFRESNEL) {
  26822. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  26823. }
  26824. if (this._defines.OPACITYFRESNEL) {
  26825. fallbacks.addFallback(2, "OPACITYFRESNEL");
  26826. }
  26827. if (this._defines.REFLECTIONFRESNEL) {
  26828. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  26829. }
  26830. if (this._defines.EMISSIVEFRESNEL) {
  26831. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  26832. }
  26833. if (this._defines.FRESNEL) {
  26834. fallbacks.addFallback(4, "FRESNEL");
  26835. }
  26836. //Attributes
  26837. var attribs = [BABYLON.VertexBuffer.PositionKind];
  26838. if (this._defines.NORMAL) {
  26839. attribs.push(BABYLON.VertexBuffer.NormalKind);
  26840. }
  26841. if (this._defines.UV1) {
  26842. attribs.push(BABYLON.VertexBuffer.UVKind);
  26843. }
  26844. if (this._defines.UV2) {
  26845. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  26846. }
  26847. if (this._defines.VERTEXCOLOR) {
  26848. attribs.push(BABYLON.VertexBuffer.ColorKind);
  26849. }
  26850. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  26851. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  26852. var shaderName = "default";
  26853. var join = this._defines.toString();
  26854. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  26855. "vFogInfos", "vFogColor", "pointSize",
  26856. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  26857. "mBones",
  26858. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  26859. "depthValues",
  26860. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  26861. "logarithmicDepthConstant"
  26862. ];
  26863. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  26864. if (this._defines.CAMERACOLORCURVES) {
  26865. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  26866. }
  26867. if (this._defines.CAMERACOLORGRADING) {
  26868. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  26869. }
  26870. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  26871. this._effect = scene.getEngine().createEffect(shaderName, attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights - 1 });
  26872. }
  26873. if (!this._effect.isReady()) {
  26874. return false;
  26875. }
  26876. this._renderId = scene.getRenderId();
  26877. this._wasPreviouslyReady = true;
  26878. if (mesh) {
  26879. if (!mesh._materialDefines) {
  26880. mesh._materialDefines = new StandardMaterialDefines();
  26881. }
  26882. this._defines.cloneTo(mesh._materialDefines);
  26883. }
  26884. return true;
  26885. };
  26886. StandardMaterial.prototype.unbind = function () {
  26887. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  26888. this._effect.setTexture("reflection2DSampler", null);
  26889. }
  26890. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  26891. this._effect.setTexture("refraction2DSampler", null);
  26892. }
  26893. _super.prototype.unbind.call(this);
  26894. };
  26895. StandardMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26896. this._effect.setMatrix("world", world);
  26897. };
  26898. StandardMaterial.prototype.bind = function (world, mesh) {
  26899. var scene = this.getScene();
  26900. // Matrices
  26901. this.bindOnlyWorldMatrix(world);
  26902. // Bones
  26903. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  26904. if (scene.getCachedMaterial() !== this) {
  26905. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  26906. if (StandardMaterial.FresnelEnabled) {
  26907. // Fresnel
  26908. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  26909. this._effect.setColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  26910. this._effect.setColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  26911. }
  26912. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  26913. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  26914. }
  26915. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  26916. this._effect.setColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  26917. this._effect.setColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  26918. }
  26919. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  26920. this._effect.setColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  26921. this._effect.setColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  26922. }
  26923. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  26924. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  26925. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  26926. }
  26927. }
  26928. // Textures
  26929. if (scene.texturesEnabled) {
  26930. if (this.diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  26931. this._effect.setTexture("diffuseSampler", this.diffuseTexture);
  26932. this._effect.setFloat2("vDiffuseInfos", this.diffuseTexture.coordinatesIndex, this.diffuseTexture.level);
  26933. this._effect.setMatrix("diffuseMatrix", this.diffuseTexture.getTextureMatrix());
  26934. }
  26935. if (this.ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  26936. this._effect.setTexture("ambientSampler", this.ambientTexture);
  26937. this._effect.setFloat2("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level);
  26938. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  26939. }
  26940. if (this.opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  26941. this._effect.setTexture("opacitySampler", this.opacityTexture);
  26942. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  26943. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  26944. }
  26945. if (this.reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  26946. if (this.reflectionTexture.isCube) {
  26947. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  26948. }
  26949. else {
  26950. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  26951. }
  26952. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  26953. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, this.roughness);
  26954. }
  26955. if (this.emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  26956. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  26957. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  26958. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  26959. }
  26960. if (this.lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  26961. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  26962. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  26963. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  26964. }
  26965. if (this.specularTexture && StandardMaterial.SpecularTextureEnabled) {
  26966. this._effect.setTexture("specularSampler", this.specularTexture);
  26967. this._effect.setFloat2("vSpecularInfos", this.specularTexture.coordinatesIndex, this.specularTexture.level);
  26968. this._effect.setMatrix("specularMatrix", this.specularTexture.getTextureMatrix());
  26969. }
  26970. if (this.bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  26971. this._effect.setTexture("bumpSampler", this.bumpTexture);
  26972. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  26973. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  26974. }
  26975. if (this.refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  26976. var depth = 1.0;
  26977. if (this.refractionTexture.isCube) {
  26978. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  26979. }
  26980. else {
  26981. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  26982. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  26983. if (this.refractionTexture.depth) {
  26984. depth = this.refractionTexture.depth;
  26985. }
  26986. }
  26987. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  26988. }
  26989. if (this.cameraColorGradingTexture && StandardMaterial.ColorGradingTextureEnabled) {
  26990. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  26991. }
  26992. }
  26993. // Clip plane
  26994. BABYLON.MaterialHelper.BindClipPlane(this._effect, scene);
  26995. // Point size
  26996. if (this.pointsCloud) {
  26997. this._effect.setFloat("pointSize", this.pointSize);
  26998. }
  26999. // Colors
  27000. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  27001. this._effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.position);
  27002. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  27003. if (this._defines.SPECULARTERM) {
  27004. this._effect.setColor4("vSpecularColor", this.specularColor, this.specularPower);
  27005. }
  27006. this._effect.setColor3("vEmissiveColor", this.emissiveColor);
  27007. }
  27008. if (scene.getCachedMaterial() !== this || !this.isFrozen) {
  27009. // Diffuse
  27010. this._effect.setColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  27011. // Lights
  27012. if (scene.lightsEnabled && !this.disableLighting) {
  27013. BABYLON.MaterialHelper.BindLights(scene, mesh, this._effect, this._defines, this.maxSimultaneousLights);
  27014. }
  27015. // View
  27016. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture || this.refractionTexture) {
  27017. this._effect.setMatrix("view", scene.getViewMatrix());
  27018. }
  27019. // Fog
  27020. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._effect);
  27021. // Log. depth
  27022. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, scene);
  27023. // Color Curves
  27024. if (this.cameraColorCurves) {
  27025. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  27026. }
  27027. }
  27028. _super.prototype.bind.call(this, world, mesh);
  27029. };
  27030. StandardMaterial.prototype.getAnimatables = function () {
  27031. var results = [];
  27032. if (this.diffuseTexture && this.diffuseTexture.animations && this.diffuseTexture.animations.length > 0) {
  27033. results.push(this.diffuseTexture);
  27034. }
  27035. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  27036. results.push(this.ambientTexture);
  27037. }
  27038. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  27039. results.push(this.opacityTexture);
  27040. }
  27041. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  27042. results.push(this.reflectionTexture);
  27043. }
  27044. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  27045. results.push(this.emissiveTexture);
  27046. }
  27047. if (this.specularTexture && this.specularTexture.animations && this.specularTexture.animations.length > 0) {
  27048. results.push(this.specularTexture);
  27049. }
  27050. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  27051. results.push(this.bumpTexture);
  27052. }
  27053. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  27054. results.push(this.lightmapTexture);
  27055. }
  27056. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  27057. results.push(this.refractionTexture);
  27058. }
  27059. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  27060. results.push(this.cameraColorGradingTexture);
  27061. }
  27062. return results;
  27063. };
  27064. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  27065. if (forceDisposeTextures) {
  27066. if (this.diffuseTexture) {
  27067. this.diffuseTexture.dispose();
  27068. }
  27069. if (this.ambientTexture) {
  27070. this.ambientTexture.dispose();
  27071. }
  27072. if (this.opacityTexture) {
  27073. this.opacityTexture.dispose();
  27074. }
  27075. if (this.reflectionTexture) {
  27076. this.reflectionTexture.dispose();
  27077. }
  27078. if (this.emissiveTexture) {
  27079. this.emissiveTexture.dispose();
  27080. }
  27081. if (this.specularTexture) {
  27082. this.specularTexture.dispose();
  27083. }
  27084. if (this.bumpTexture) {
  27085. this.bumpTexture.dispose();
  27086. }
  27087. if (this.lightmapTexture) {
  27088. this.lightmapTexture.dispose();
  27089. }
  27090. if (this.refractionTexture) {
  27091. this.refractionTexture.dispose();
  27092. }
  27093. if (this.cameraColorGradingTexture) {
  27094. this.cameraColorGradingTexture.dispose();
  27095. }
  27096. }
  27097. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  27098. };
  27099. StandardMaterial.prototype.clone = function (name) {
  27100. var _this = this;
  27101. return BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  27102. };
  27103. StandardMaterial.prototype.serialize = function () {
  27104. return BABYLON.SerializationHelper.Serialize(this);
  27105. };
  27106. // Statics
  27107. StandardMaterial.Parse = function (source, scene, rootUrl) {
  27108. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  27109. };
  27110. return StandardMaterial;
  27111. }(BABYLON.Material));
  27112. // Flags used to enable or disable a type of texture for all Standard Materials
  27113. StandardMaterial.DiffuseTextureEnabled = true;
  27114. StandardMaterial.AmbientTextureEnabled = true;
  27115. StandardMaterial.OpacityTextureEnabled = true;
  27116. StandardMaterial.ReflectionTextureEnabled = true;
  27117. StandardMaterial.EmissiveTextureEnabled = true;
  27118. StandardMaterial.SpecularTextureEnabled = true;
  27119. StandardMaterial.BumpTextureEnabled = true;
  27120. StandardMaterial.FresnelEnabled = true;
  27121. StandardMaterial.LightmapTextureEnabled = true;
  27122. StandardMaterial.RefractionTextureEnabled = true;
  27123. StandardMaterial.ColorGradingTextureEnabled = true;
  27124. __decorate([
  27125. BABYLON.serializeAsTexture()
  27126. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  27127. __decorate([
  27128. BABYLON.serializeAsTexture()
  27129. ], StandardMaterial.prototype, "ambientTexture", void 0);
  27130. __decorate([
  27131. BABYLON.serializeAsTexture()
  27132. ], StandardMaterial.prototype, "opacityTexture", void 0);
  27133. __decorate([
  27134. BABYLON.serializeAsTexture()
  27135. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  27136. __decorate([
  27137. BABYLON.serializeAsTexture()
  27138. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  27139. __decorate([
  27140. BABYLON.serializeAsTexture()
  27141. ], StandardMaterial.prototype, "specularTexture", void 0);
  27142. __decorate([
  27143. BABYLON.serializeAsTexture()
  27144. ], StandardMaterial.prototype, "bumpTexture", void 0);
  27145. __decorate([
  27146. BABYLON.serializeAsTexture()
  27147. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  27148. __decorate([
  27149. BABYLON.serializeAsTexture()
  27150. ], StandardMaterial.prototype, "refractionTexture", void 0);
  27151. __decorate([
  27152. BABYLON.serializeAsColor3("ambient")
  27153. ], StandardMaterial.prototype, "ambientColor", void 0);
  27154. __decorate([
  27155. BABYLON.serializeAsColor3("diffuse")
  27156. ], StandardMaterial.prototype, "diffuseColor", void 0);
  27157. __decorate([
  27158. BABYLON.serializeAsColor3("specular")
  27159. ], StandardMaterial.prototype, "specularColor", void 0);
  27160. __decorate([
  27161. BABYLON.serializeAsColor3("emissive")
  27162. ], StandardMaterial.prototype, "emissiveColor", void 0);
  27163. __decorate([
  27164. BABYLON.serialize()
  27165. ], StandardMaterial.prototype, "specularPower", void 0);
  27166. __decorate([
  27167. BABYLON.serialize()
  27168. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  27169. __decorate([
  27170. BABYLON.serialize()
  27171. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  27172. __decorate([
  27173. BABYLON.serialize()
  27174. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  27175. __decorate([
  27176. BABYLON.serialize()
  27177. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  27178. __decorate([
  27179. BABYLON.serialize()
  27180. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  27181. __decorate([
  27182. BABYLON.serialize()
  27183. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  27184. __decorate([
  27185. BABYLON.serialize()
  27186. ], StandardMaterial.prototype, "disableLighting", void 0);
  27187. __decorate([
  27188. BABYLON.serialize()
  27189. ], StandardMaterial.prototype, "useParallax", void 0);
  27190. __decorate([
  27191. BABYLON.serialize()
  27192. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  27193. __decorate([
  27194. BABYLON.serialize()
  27195. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  27196. __decorate([
  27197. BABYLON.serialize()
  27198. ], StandardMaterial.prototype, "roughness", void 0);
  27199. __decorate([
  27200. BABYLON.serialize()
  27201. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  27202. __decorate([
  27203. BABYLON.serialize()
  27204. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  27205. __decorate([
  27206. BABYLON.serialize()
  27207. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  27208. __decorate([
  27209. BABYLON.serializeAsFresnelParameters()
  27210. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  27211. __decorate([
  27212. BABYLON.serializeAsFresnelParameters()
  27213. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  27214. __decorate([
  27215. BABYLON.serializeAsFresnelParameters()
  27216. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  27217. __decorate([
  27218. BABYLON.serializeAsFresnelParameters()
  27219. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  27220. __decorate([
  27221. BABYLON.serializeAsFresnelParameters()
  27222. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  27223. __decorate([
  27224. BABYLON.serialize()
  27225. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  27226. __decorate([
  27227. BABYLON.serialize()
  27228. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  27229. __decorate([
  27230. BABYLON.serialize()
  27231. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  27232. __decorate([
  27233. BABYLON.serialize()
  27234. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  27235. __decorate([
  27236. BABYLON.serializeAsTexture()
  27237. ], StandardMaterial.prototype, "cameraColorGradingTexture", void 0);
  27238. __decorate([
  27239. BABYLON.serializeAsColorCurves()
  27240. ], StandardMaterial.prototype, "cameraColorCurves", void 0);
  27241. __decorate([
  27242. BABYLON.serialize()
  27243. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  27244. BABYLON.StandardMaterial = StandardMaterial;
  27245. })(BABYLON || (BABYLON = {}));
  27246. //# sourceMappingURL=babylon.standardMaterial.js.map
  27247. var BABYLON;
  27248. (function (BABYLON) {
  27249. var MultiMaterial = (function (_super) {
  27250. __extends(MultiMaterial, _super);
  27251. function MultiMaterial(name, scene) {
  27252. var _this = _super.call(this, name, scene, true) || this;
  27253. _this.subMaterials = new Array();
  27254. scene.multiMaterials.push(_this);
  27255. return _this;
  27256. }
  27257. // Properties
  27258. MultiMaterial.prototype.getSubMaterial = function (index) {
  27259. if (index < 0 || index >= this.subMaterials.length) {
  27260. return this.getScene().defaultMaterial;
  27261. }
  27262. return this.subMaterials[index];
  27263. };
  27264. // Methods
  27265. MultiMaterial.prototype.getClassName = function () {
  27266. return "MultiMaterial";
  27267. };
  27268. MultiMaterial.prototype.isReady = function (mesh) {
  27269. for (var index = 0; index < this.subMaterials.length; index++) {
  27270. var subMaterial = this.subMaterials[index];
  27271. if (subMaterial) {
  27272. if (!this.subMaterials[index].isReady(mesh)) {
  27273. return false;
  27274. }
  27275. }
  27276. }
  27277. return true;
  27278. };
  27279. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  27280. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  27281. for (var index = 0; index < this.subMaterials.length; index++) {
  27282. var subMaterial = null;
  27283. if (cloneChildren) {
  27284. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  27285. }
  27286. else {
  27287. subMaterial = this.subMaterials[index];
  27288. }
  27289. newMultiMaterial.subMaterials.push(subMaterial);
  27290. }
  27291. return newMultiMaterial;
  27292. };
  27293. MultiMaterial.prototype.serialize = function () {
  27294. var serializationObject = {};
  27295. serializationObject.name = this.name;
  27296. serializationObject.id = this.id;
  27297. serializationObject.tags = BABYLON.Tags.GetTags(this);
  27298. serializationObject.materials = [];
  27299. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  27300. var subMat = this.subMaterials[matIndex];
  27301. if (subMat) {
  27302. serializationObject.materials.push(subMat.id);
  27303. }
  27304. else {
  27305. serializationObject.materials.push(null);
  27306. }
  27307. }
  27308. return serializationObject;
  27309. };
  27310. return MultiMaterial;
  27311. }(BABYLON.Material));
  27312. BABYLON.MultiMaterial = MultiMaterial;
  27313. })(BABYLON || (BABYLON = {}));
  27314. //# sourceMappingURL=babylon.multiMaterial.js.map
  27315. var BABYLON;
  27316. (function (BABYLON) {
  27317. var SceneLoader = (function () {
  27318. function SceneLoader() {
  27319. }
  27320. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  27321. get: function () {
  27322. return 0;
  27323. },
  27324. enumerable: true,
  27325. configurable: true
  27326. });
  27327. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  27328. get: function () {
  27329. return 1;
  27330. },
  27331. enumerable: true,
  27332. configurable: true
  27333. });
  27334. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  27335. get: function () {
  27336. return 2;
  27337. },
  27338. enumerable: true,
  27339. configurable: true
  27340. });
  27341. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  27342. get: function () {
  27343. return 3;
  27344. },
  27345. enumerable: true,
  27346. configurable: true
  27347. });
  27348. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  27349. get: function () {
  27350. return SceneLoader._ForceFullSceneLoadingForIncremental;
  27351. },
  27352. set: function (value) {
  27353. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  27354. },
  27355. enumerable: true,
  27356. configurable: true
  27357. });
  27358. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  27359. get: function () {
  27360. return SceneLoader._ShowLoadingScreen;
  27361. },
  27362. set: function (value) {
  27363. SceneLoader._ShowLoadingScreen = value;
  27364. },
  27365. enumerable: true,
  27366. configurable: true
  27367. });
  27368. Object.defineProperty(SceneLoader, "loggingLevel", {
  27369. get: function () {
  27370. return SceneLoader._loggingLevel;
  27371. },
  27372. set: function (value) {
  27373. SceneLoader._loggingLevel = value;
  27374. },
  27375. enumerable: true,
  27376. configurable: true
  27377. });
  27378. SceneLoader._getDefaultPlugin = function () {
  27379. return SceneLoader._registeredPlugins[".babylon"];
  27380. };
  27381. SceneLoader._getPluginForExtension = function (extension) {
  27382. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  27383. if (registeredPlugin) {
  27384. return registeredPlugin;
  27385. }
  27386. return SceneLoader._getDefaultPlugin();
  27387. };
  27388. SceneLoader._getPluginForFilename = function (sceneFilename) {
  27389. if (sceneFilename.name) {
  27390. sceneFilename = sceneFilename.name;
  27391. }
  27392. var dotPosition = sceneFilename.lastIndexOf(".");
  27393. var queryStringPosition = sceneFilename.indexOf("?");
  27394. if (queryStringPosition === -1) {
  27395. queryStringPosition = sceneFilename.length;
  27396. }
  27397. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  27398. return SceneLoader._getPluginForExtension(extension);
  27399. };
  27400. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  27401. SceneLoader._getDirectLoad = function (sceneFilename) {
  27402. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  27403. return sceneFilename.substr(5);
  27404. }
  27405. return null;
  27406. };
  27407. // Public functions
  27408. SceneLoader.GetPluginForExtension = function (extension) {
  27409. return SceneLoader._getPluginForExtension(extension).plugin;
  27410. };
  27411. SceneLoader.RegisterPlugin = function (plugin) {
  27412. if (typeof plugin.extensions === "string") {
  27413. var extension = plugin.extensions;
  27414. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27415. plugin: plugin,
  27416. isBinary: false
  27417. };
  27418. }
  27419. else {
  27420. var extensions = plugin.extensions;
  27421. Object.keys(extensions).forEach(function (extension) {
  27422. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  27423. plugin: plugin,
  27424. isBinary: extensions[extension].isBinary
  27425. };
  27426. });
  27427. }
  27428. };
  27429. SceneLoader.ImportMesh = function (meshesNames, rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27430. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27431. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27432. return;
  27433. }
  27434. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27435. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27436. return;
  27437. }
  27438. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27439. var loadingToken = {};
  27440. scene._addPendingData(loadingToken);
  27441. var manifestChecked = function (success) {
  27442. scene.database = database;
  27443. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27444. var plugin = registeredPlugin.plugin;
  27445. var useArrayBuffer = registeredPlugin.isBinary;
  27446. var importMeshFromData = function (data) {
  27447. var meshes = [];
  27448. var particleSystems = [];
  27449. var skeletons = [];
  27450. try {
  27451. if (plugin.importMesh) {
  27452. var syncedPlugin = plugin;
  27453. if (!syncedPlugin.importMesh(meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons)) {
  27454. if (onerror) {
  27455. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27456. }
  27457. scene._removePendingData(loadingToken);
  27458. return;
  27459. }
  27460. if (onsuccess) {
  27461. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27462. onsuccess(meshes, particleSystems, skeletons);
  27463. scene._removePendingData(loadingToken);
  27464. }
  27465. }
  27466. else {
  27467. var asyncedPlugin = plugin;
  27468. asyncedPlugin.importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  27469. if (onsuccess) {
  27470. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  27471. onsuccess(meshes, particleSystems, skeletons);
  27472. scene._removePendingData(loadingToken);
  27473. }
  27474. }, function () {
  27475. if (onerror) {
  27476. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename);
  27477. }
  27478. scene._removePendingData(loadingToken);
  27479. });
  27480. }
  27481. }
  27482. catch (e) {
  27483. if (onerror) {
  27484. onerror(scene, 'Unable to import meshes from ' + rootUrl + sceneFilename, e);
  27485. }
  27486. scene._removePendingData(loadingToken);
  27487. }
  27488. };
  27489. if (directLoad) {
  27490. importMeshFromData(directLoad);
  27491. return;
  27492. }
  27493. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, function (data) {
  27494. importMeshFromData(data);
  27495. }, progressCallBack, database, useArrayBuffer);
  27496. };
  27497. if (scene.getEngine().enableOfflineSupport && !directLoad) {
  27498. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27499. var database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27500. }
  27501. else {
  27502. // If the scene is a data stream or offline support is not enabled, it's a direct load
  27503. manifestChecked(true);
  27504. }
  27505. };
  27506. /**
  27507. * Load a scene
  27508. * @param rootUrl a string that defines the root url for scene and resources
  27509. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27510. * @param engine is the instance of BABYLON.Engine to use to create the scene
  27511. */
  27512. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onsuccess, progressCallBack, onerror) {
  27513. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onsuccess, progressCallBack, onerror);
  27514. };
  27515. /**
  27516. * Append a scene
  27517. * @param rootUrl a string that defines the root url for scene and resources
  27518. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  27519. * @param scene is the instance of BABYLON.Scene to append to
  27520. */
  27521. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onsuccess, progressCallBack, onerror) {
  27522. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  27523. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  27524. return;
  27525. }
  27526. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  27527. var registeredPlugin = directLoad ? SceneLoader._getDefaultPlugin() : SceneLoader._getPluginForFilename(sceneFilename);
  27528. var plugin = registeredPlugin.plugin;
  27529. var useArrayBuffer = registeredPlugin.isBinary;
  27530. var database;
  27531. var loadingToken = {};
  27532. scene._addPendingData(loadingToken);
  27533. if (SceneLoader.ShowLoadingScreen) {
  27534. scene.getEngine().displayLoadingUI();
  27535. }
  27536. var loadSceneFromData = function (data) {
  27537. scene.database = database;
  27538. if (plugin.load) {
  27539. var syncedPlugin = plugin;
  27540. if (!syncedPlugin.load(scene, data, rootUrl)) {
  27541. if (onerror) {
  27542. onerror(scene);
  27543. }
  27544. scene._removePendingData(loadingToken);
  27545. scene.getEngine().hideLoadingUI();
  27546. return;
  27547. }
  27548. if (onsuccess) {
  27549. onsuccess(scene);
  27550. }
  27551. scene._removePendingData(loadingToken);
  27552. }
  27553. else {
  27554. var asyncedPlugin = plugin;
  27555. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  27556. if (onsuccess) {
  27557. onsuccess(scene);
  27558. }
  27559. scene._removePendingData(loadingToken);
  27560. }, function () {
  27561. if (onerror) {
  27562. onerror(scene);
  27563. }
  27564. scene._removePendingData(loadingToken);
  27565. scene.getEngine().hideLoadingUI();
  27566. });
  27567. }
  27568. if (SceneLoader.ShowLoadingScreen) {
  27569. scene.executeWhenReady(function () {
  27570. scene.getEngine().hideLoadingUI();
  27571. });
  27572. }
  27573. };
  27574. var manifestChecked = function (success) {
  27575. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, loadSceneFromData, progressCallBack, database, useArrayBuffer);
  27576. };
  27577. if (directLoad) {
  27578. loadSceneFromData(directLoad);
  27579. return;
  27580. }
  27581. if (rootUrl.indexOf("file:") === -1) {
  27582. if (scene.getEngine().enableOfflineSupport) {
  27583. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  27584. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  27585. }
  27586. else {
  27587. manifestChecked(true);
  27588. }
  27589. }
  27590. else {
  27591. BABYLON.Tools.ReadFile(sceneFilename, loadSceneFromData, progressCallBack, useArrayBuffer);
  27592. }
  27593. };
  27594. return SceneLoader;
  27595. }());
  27596. // Flags
  27597. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  27598. SceneLoader._ShowLoadingScreen = true;
  27599. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  27600. // Members
  27601. SceneLoader._registeredPlugins = {};
  27602. BABYLON.SceneLoader = SceneLoader;
  27603. ;
  27604. })(BABYLON || (BABYLON = {}));
  27605. //# sourceMappingURL=babylon.sceneLoader.js.map
  27606. var BABYLON;
  27607. (function (BABYLON) {
  27608. var Internals;
  27609. (function (Internals) {
  27610. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  27611. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27612. var parsedMaterial = parsedData.materials[index];
  27613. if (parsedMaterial.id === id) {
  27614. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27615. }
  27616. }
  27617. return null;
  27618. };
  27619. var isDescendantOf = function (mesh, names, hierarchyIds) {
  27620. names = (names instanceof Array) ? names : [names];
  27621. for (var i in names) {
  27622. if (mesh.name === names[i]) {
  27623. hierarchyIds.push(mesh.id);
  27624. return true;
  27625. }
  27626. }
  27627. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  27628. hierarchyIds.push(mesh.id);
  27629. return true;
  27630. }
  27631. return false;
  27632. };
  27633. var logOperation = function (operation, producer) {
  27634. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  27635. };
  27636. BABYLON.SceneLoader.RegisterPlugin({
  27637. extensions: ".babylon",
  27638. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  27639. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27640. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27641. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27642. // and avoid problems with multiple concurrent .babylon loads.
  27643. var log = "importMesh has failed JSON parse";
  27644. try {
  27645. var parsedData = JSON.parse(data);
  27646. log = "";
  27647. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27648. var loadedSkeletonsIds = [];
  27649. var loadedMaterialsIds = [];
  27650. var hierarchyIds = [];
  27651. var index;
  27652. var cache;
  27653. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27654. var parsedMesh = parsedData.meshes[index];
  27655. if (!meshesNames || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  27656. if (meshesNames instanceof Array) {
  27657. // Remove found mesh name from list.
  27658. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  27659. }
  27660. //Geometry?
  27661. if (parsedMesh.geometryId) {
  27662. //does the file contain geometries?
  27663. if (parsedData.geometries) {
  27664. //find the correct geometry and add it to the scene
  27665. var found = false;
  27666. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  27667. if (found || !parsedData.geometries[geometryType] || !(parsedData.geometries[geometryType] instanceof Array)) {
  27668. return;
  27669. }
  27670. else {
  27671. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  27672. if (parsedGeometryData.id === parsedMesh.geometryId) {
  27673. switch (geometryType) {
  27674. case "boxes":
  27675. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  27676. break;
  27677. case "spheres":
  27678. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  27679. break;
  27680. case "cylinders":
  27681. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  27682. break;
  27683. case "toruses":
  27684. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  27685. break;
  27686. case "grounds":
  27687. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  27688. break;
  27689. case "planes":
  27690. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  27691. break;
  27692. case "torusKnots":
  27693. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  27694. break;
  27695. case "vertexData":
  27696. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  27697. break;
  27698. }
  27699. found = true;
  27700. }
  27701. });
  27702. }
  27703. });
  27704. if (!found) {
  27705. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  27706. }
  27707. }
  27708. }
  27709. // Material ?
  27710. if (parsedMesh.materialId) {
  27711. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  27712. if (!materialFound && parsedData.multiMaterials) {
  27713. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  27714. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  27715. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  27716. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  27717. var subMatId = parsedMultiMaterial.materials[matIndex];
  27718. loadedMaterialsIds.push(subMatId);
  27719. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  27720. log += "\n\tMaterial " + mat.toString(fullDetails);
  27721. }
  27722. loadedMaterialsIds.push(parsedMultiMaterial.id);
  27723. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27724. materialFound = true;
  27725. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  27726. break;
  27727. }
  27728. }
  27729. }
  27730. if (!materialFound) {
  27731. loadedMaterialsIds.push(parsedMesh.materialId);
  27732. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  27733. if (!mat) {
  27734. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  27735. }
  27736. else {
  27737. log += "\n\tMaterial " + mat.toString(fullDetails);
  27738. }
  27739. }
  27740. }
  27741. // Skeleton ?
  27742. if (parsedMesh.skeletonId > -1 && scene.skeletons) {
  27743. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  27744. if (!skeletonAlreadyLoaded) {
  27745. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  27746. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  27747. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  27748. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27749. skeletons.push(skeleton);
  27750. loadedSkeletonsIds.push(parsedSkeleton.id);
  27751. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  27752. }
  27753. }
  27754. }
  27755. }
  27756. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27757. meshes.push(mesh);
  27758. log += "\n\tMesh " + mesh.toString(fullDetails);
  27759. }
  27760. }
  27761. // Connecting parents
  27762. var currentMesh;
  27763. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27764. currentMesh = scene.meshes[index];
  27765. if (currentMesh._waitingParentId) {
  27766. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  27767. currentMesh._waitingParentId = undefined;
  27768. }
  27769. }
  27770. // freeze and compute world matrix application
  27771. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  27772. currentMesh = scene.meshes[index];
  27773. if (currentMesh._waitingFreezeWorldMatrix) {
  27774. currentMesh.freezeWorldMatrix();
  27775. currentMesh._waitingFreezeWorldMatrix = undefined;
  27776. }
  27777. else {
  27778. currentMesh.computeWorldMatrix(true);
  27779. }
  27780. }
  27781. // Particles
  27782. if (parsedData.particleSystems) {
  27783. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  27784. var parsedParticleSystem = parsedData.particleSystems[index];
  27785. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  27786. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  27787. }
  27788. }
  27789. }
  27790. return true;
  27791. }
  27792. catch (err) {
  27793. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  27794. log = null;
  27795. throw err;
  27796. }
  27797. finally {
  27798. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  27799. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  27800. }
  27801. }
  27802. },
  27803. load: function (scene, data, rootUrl) {
  27804. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  27805. // when SceneLoader.debugLogging = true (default), or exception encountered.
  27806. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  27807. // and avoid problems with multiple concurrent .babylon loads.
  27808. var log = "importScene has failed JSON parse";
  27809. try {
  27810. var parsedData = JSON.parse(data);
  27811. log = "";
  27812. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  27813. // Scene
  27814. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  27815. scene.autoClear = parsedData.autoClear;
  27816. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  27817. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  27818. if (parsedData.gravity) {
  27819. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  27820. }
  27821. // Fog
  27822. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  27823. scene.fogMode = parsedData.fogMode;
  27824. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  27825. scene.fogStart = parsedData.fogStart;
  27826. scene.fogEnd = parsedData.fogEnd;
  27827. scene.fogDensity = parsedData.fogDensity;
  27828. log += "\tFog mode for scene: ";
  27829. switch (scene.fogMode) {
  27830. // getters not compiling, so using hardcoded
  27831. case 1:
  27832. log += "exp\n";
  27833. break;
  27834. case 2:
  27835. log += "exp2\n";
  27836. break;
  27837. case 3:
  27838. log += "linear\n";
  27839. break;
  27840. }
  27841. }
  27842. //Physics
  27843. if (parsedData.physicsEnabled) {
  27844. var physicsPlugin;
  27845. if (parsedData.physicsEngine === "cannon") {
  27846. physicsPlugin = new BABYLON.CannonJSPlugin();
  27847. }
  27848. else if (parsedData.physicsEngine === "oimo") {
  27849. physicsPlugin = new BABYLON.OimoJSPlugin();
  27850. }
  27851. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  27852. //else - default engine, which is currently oimo
  27853. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  27854. scene.enablePhysics(physicsGravity, physicsPlugin);
  27855. }
  27856. // Metadata
  27857. if (parsedData.metadata !== undefined) {
  27858. scene.metadata = parsedData.metadata;
  27859. }
  27860. //collisions, if defined. otherwise, default is true
  27861. if (parsedData.collisionsEnabled != undefined) {
  27862. scene.collisionsEnabled = parsedData.collisionsEnabled;
  27863. }
  27864. scene.workerCollisions = !!parsedData.workerCollisions;
  27865. var index;
  27866. var cache;
  27867. // Lights
  27868. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  27869. var parsedLight = parsedData.lights[index];
  27870. var light = BABYLON.Light.Parse(parsedLight, scene);
  27871. log += (index === 0 ? "\n\tLights:" : "");
  27872. log += "\n\t\t" + light.toString(fullDetails);
  27873. }
  27874. // Animations
  27875. if (parsedData.animations) {
  27876. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  27877. var parsedAnimation = parsedData.animations[index];
  27878. var animation = BABYLON.Animation.Parse(parsedAnimation);
  27879. scene.animations.push(animation);
  27880. log += (index === 0 ? "\n\tAnimations:" : "");
  27881. log += "\n\t\t" + animation.toString(fullDetails);
  27882. }
  27883. }
  27884. if (parsedData.autoAnimate) {
  27885. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  27886. }
  27887. // Materials
  27888. if (parsedData.materials) {
  27889. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  27890. var parsedMaterial = parsedData.materials[index];
  27891. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  27892. log += (index === 0 ? "\n\tMaterials:" : "");
  27893. log += "\n\t\t" + mat.toString(fullDetails);
  27894. }
  27895. }
  27896. if (parsedData.multiMaterials) {
  27897. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  27898. var parsedMultiMaterial = parsedData.multiMaterials[index];
  27899. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  27900. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  27901. log += "\n\t\t" + mmat.toString(fullDetails);
  27902. }
  27903. }
  27904. // Skeletons
  27905. if (parsedData.skeletons) {
  27906. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  27907. var parsedSkeleton = parsedData.skeletons[index];
  27908. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  27909. log += (index === 0 ? "\n\tSkeletons:" : "");
  27910. log += "\n\t\t" + skeleton.toString(fullDetails);
  27911. }
  27912. }
  27913. // Geometries
  27914. var geometries = parsedData.geometries;
  27915. if (geometries) {
  27916. // Boxes
  27917. var boxes = geometries.boxes;
  27918. if (boxes) {
  27919. for (index = 0, cache = boxes.length; index < cache; index++) {
  27920. var parsedBox = boxes[index];
  27921. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  27922. }
  27923. }
  27924. // Spheres
  27925. var spheres = geometries.spheres;
  27926. if (spheres) {
  27927. for (index = 0, cache = spheres.length; index < cache; index++) {
  27928. var parsedSphere = spheres[index];
  27929. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  27930. }
  27931. }
  27932. // Cylinders
  27933. var cylinders = geometries.cylinders;
  27934. if (cylinders) {
  27935. for (index = 0, cache = cylinders.length; index < cache; index++) {
  27936. var parsedCylinder = cylinders[index];
  27937. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  27938. }
  27939. }
  27940. // Toruses
  27941. var toruses = geometries.toruses;
  27942. if (toruses) {
  27943. for (index = 0, cache = toruses.length; index < cache; index++) {
  27944. var parsedTorus = toruses[index];
  27945. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  27946. }
  27947. }
  27948. // Grounds
  27949. var grounds = geometries.grounds;
  27950. if (grounds) {
  27951. for (index = 0, cache = grounds.length; index < cache; index++) {
  27952. var parsedGround = grounds[index];
  27953. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  27954. }
  27955. }
  27956. // Planes
  27957. var planes = geometries.planes;
  27958. if (planes) {
  27959. for (index = 0, cache = planes.length; index < cache; index++) {
  27960. var parsedPlane = planes[index];
  27961. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  27962. }
  27963. }
  27964. // TorusKnots
  27965. var torusKnots = geometries.torusKnots;
  27966. if (torusKnots) {
  27967. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  27968. var parsedTorusKnot = torusKnots[index];
  27969. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  27970. }
  27971. }
  27972. // VertexData
  27973. var vertexData = geometries.vertexData;
  27974. if (vertexData) {
  27975. for (index = 0, cache = vertexData.length; index < cache; index++) {
  27976. var parsedVertexData = vertexData[index];
  27977. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  27978. }
  27979. }
  27980. }
  27981. // Meshes
  27982. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  27983. var parsedMesh = parsedData.meshes[index];
  27984. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  27985. log += (index === 0 ? "\n\tMeshes:" : "");
  27986. log += "\n\t\t" + mesh.toString(fullDetails);
  27987. }
  27988. // Cameras
  27989. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  27990. var parsedCamera = parsedData.cameras[index];
  27991. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  27992. log += (index === 0 ? "\n\tCameras:" : "");
  27993. log += "\n\t\t" + camera.toString(fullDetails);
  27994. }
  27995. if (parsedData.activeCameraID) {
  27996. scene.setActiveCameraByID(parsedData.activeCameraID);
  27997. }
  27998. // Browsing all the graph to connect the dots
  27999. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  28000. var camera = scene.cameras[index];
  28001. if (camera._waitingParentId) {
  28002. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  28003. camera._waitingParentId = undefined;
  28004. }
  28005. }
  28006. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  28007. var light = scene.lights[index];
  28008. if (light._waitingParentId) {
  28009. light.parent = scene.getLastEntryByID(light._waitingParentId);
  28010. light._waitingParentId = undefined;
  28011. }
  28012. }
  28013. // Sounds
  28014. var loadedSounds = [];
  28015. var loadedSound;
  28016. if (BABYLON.AudioEngine && parsedData.sounds) {
  28017. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  28018. var parsedSound = parsedData.sounds[index];
  28019. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  28020. if (!parsedSound.url)
  28021. parsedSound.url = parsedSound.name;
  28022. if (!loadedSounds[parsedSound.url]) {
  28023. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  28024. loadedSounds[parsedSound.url] = loadedSound;
  28025. }
  28026. else {
  28027. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  28028. }
  28029. }
  28030. else {
  28031. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  28032. }
  28033. }
  28034. }
  28035. loadedSounds = [];
  28036. // Connect parents & children and parse actions
  28037. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28038. var mesh = scene.meshes[index];
  28039. if (mesh._waitingParentId) {
  28040. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  28041. mesh._waitingParentId = undefined;
  28042. }
  28043. if (mesh._waitingActions) {
  28044. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  28045. mesh._waitingActions = undefined;
  28046. }
  28047. }
  28048. // freeze world matrix application
  28049. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  28050. var currentMesh = scene.meshes[index];
  28051. if (currentMesh._waitingFreezeWorldMatrix) {
  28052. currentMesh.freezeWorldMatrix();
  28053. currentMesh._waitingFreezeWorldMatrix = undefined;
  28054. }
  28055. else {
  28056. currentMesh.computeWorldMatrix(true);
  28057. }
  28058. }
  28059. // Particles Systems
  28060. if (parsedData.particleSystems) {
  28061. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  28062. var parsedParticleSystem = parsedData.particleSystems[index];
  28063. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  28064. }
  28065. }
  28066. // Lens flares
  28067. if (parsedData.lensFlareSystems) {
  28068. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  28069. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  28070. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  28071. }
  28072. }
  28073. // Shadows
  28074. if (parsedData.shadowGenerators) {
  28075. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  28076. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  28077. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  28078. }
  28079. }
  28080. // Actions (scene)
  28081. if (parsedData.actions) {
  28082. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  28083. }
  28084. // Finish
  28085. return true;
  28086. }
  28087. catch (err) {
  28088. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  28089. log = null;
  28090. throw err;
  28091. }
  28092. finally {
  28093. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  28094. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  28095. }
  28096. }
  28097. }
  28098. });
  28099. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  28100. })(BABYLON || (BABYLON = {}));
  28101. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  28102. var BABYLON;
  28103. (function (BABYLON) {
  28104. var SpriteManager = (function () {
  28105. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  28106. if (epsilon === void 0) { epsilon = 0.01; }
  28107. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  28108. this.name = name;
  28109. this.sprites = new Array();
  28110. this.renderingGroupId = 0;
  28111. this.layerMask = 0x0FFFFFFF;
  28112. this.fogEnabled = true;
  28113. this.isPickable = false;
  28114. /**
  28115. * An event triggered when the manager is disposed.
  28116. * @type {BABYLON.Observable}
  28117. */
  28118. this.onDisposeObservable = new BABYLON.Observable();
  28119. this._vertexBuffers = {};
  28120. this._capacity = capacity;
  28121. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  28122. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28123. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  28124. if (cellSize.width && cellSize.height) {
  28125. this.cellWidth = cellSize.width;
  28126. this.cellHeight = cellSize.height;
  28127. }
  28128. else if (cellSize !== undefined) {
  28129. this.cellWidth = cellSize;
  28130. this.cellHeight = cellSize;
  28131. }
  28132. else {
  28133. return;
  28134. }
  28135. this._epsilon = epsilon;
  28136. this._scene = scene;
  28137. this._scene.spriteManagers.push(this);
  28138. var indices = [];
  28139. var index = 0;
  28140. for (var count = 0; count < capacity; count++) {
  28141. indices.push(index);
  28142. indices.push(index + 1);
  28143. indices.push(index + 2);
  28144. indices.push(index);
  28145. indices.push(index + 2);
  28146. indices.push(index + 3);
  28147. index += 4;
  28148. }
  28149. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28150. // VBO
  28151. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  28152. this._vertexData = new Float32Array(capacity * 16 * 4);
  28153. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  28154. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  28155. var options = this._buffer.createVertexBuffer("options", 4, 4);
  28156. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  28157. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  28158. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28159. this._vertexBuffers["options"] = options;
  28160. this._vertexBuffers["cellInfo"] = cellInfo;
  28161. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28162. // Effects
  28163. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  28164. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  28165. }
  28166. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  28167. set: function (callback) {
  28168. if (this._onDisposeObserver) {
  28169. this.onDisposeObservable.remove(this._onDisposeObserver);
  28170. }
  28171. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28172. },
  28173. enumerable: true,
  28174. configurable: true
  28175. });
  28176. Object.defineProperty(SpriteManager.prototype, "texture", {
  28177. get: function () {
  28178. return this._spriteTexture;
  28179. },
  28180. set: function (value) {
  28181. this._spriteTexture = value;
  28182. },
  28183. enumerable: true,
  28184. configurable: true
  28185. });
  28186. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  28187. var arrayOffset = index * 16;
  28188. if (offsetX === 0)
  28189. offsetX = this._epsilon;
  28190. else if (offsetX === 1)
  28191. offsetX = 1 - this._epsilon;
  28192. if (offsetY === 0)
  28193. offsetY = this._epsilon;
  28194. else if (offsetY === 1)
  28195. offsetY = 1 - this._epsilon;
  28196. this._vertexData[arrayOffset] = sprite.position.x;
  28197. this._vertexData[arrayOffset + 1] = sprite.position.y;
  28198. this._vertexData[arrayOffset + 2] = sprite.position.z;
  28199. this._vertexData[arrayOffset + 3] = sprite.angle;
  28200. this._vertexData[arrayOffset + 4] = sprite.width;
  28201. this._vertexData[arrayOffset + 5] = sprite.height;
  28202. this._vertexData[arrayOffset + 6] = offsetX;
  28203. this._vertexData[arrayOffset + 7] = offsetY;
  28204. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  28205. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  28206. var offset = (sprite.cellIndex / rowSize) >> 0;
  28207. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  28208. this._vertexData[arrayOffset + 11] = offset;
  28209. // Color
  28210. this._vertexData[arrayOffset + 12] = sprite.color.r;
  28211. this._vertexData[arrayOffset + 13] = sprite.color.g;
  28212. this._vertexData[arrayOffset + 14] = sprite.color.b;
  28213. this._vertexData[arrayOffset + 15] = sprite.color.a;
  28214. };
  28215. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  28216. var count = Math.min(this._capacity, this.sprites.length);
  28217. var min = BABYLON.Vector3.Zero();
  28218. var max = BABYLON.Vector3.Zero();
  28219. var distance = Number.MAX_VALUE;
  28220. var currentSprite;
  28221. var cameraSpacePosition = BABYLON.Vector3.Zero();
  28222. var cameraView = camera.getViewMatrix();
  28223. for (var index = 0; index < count; index++) {
  28224. var sprite = this.sprites[index];
  28225. if (!sprite) {
  28226. continue;
  28227. }
  28228. if (predicate) {
  28229. if (!predicate(sprite)) {
  28230. continue;
  28231. }
  28232. }
  28233. else if (!sprite.isPickable) {
  28234. continue;
  28235. }
  28236. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  28237. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  28238. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  28239. if (ray.intersectsBoxMinMax(min, max)) {
  28240. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  28241. if (distance > currentDistance) {
  28242. distance = currentDistance;
  28243. currentSprite = sprite;
  28244. if (fastCheck) {
  28245. break;
  28246. }
  28247. }
  28248. }
  28249. }
  28250. if (currentSprite) {
  28251. var result = new BABYLON.PickingInfo();
  28252. result.hit = true;
  28253. result.pickedSprite = currentSprite;
  28254. result.distance = distance;
  28255. return result;
  28256. }
  28257. return null;
  28258. };
  28259. SpriteManager.prototype.render = function () {
  28260. // Check
  28261. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  28262. return;
  28263. var engine = this._scene.getEngine();
  28264. var baseSize = this._spriteTexture.getBaseSize();
  28265. // Sprites
  28266. var deltaTime = engine.getDeltaTime();
  28267. var max = Math.min(this._capacity, this.sprites.length);
  28268. var rowSize = baseSize.width / this.cellWidth;
  28269. var offset = 0;
  28270. for (var index = 0; index < max; index++) {
  28271. var sprite = this.sprites[index];
  28272. if (!sprite) {
  28273. continue;
  28274. }
  28275. sprite._animate(deltaTime);
  28276. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  28277. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  28278. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  28279. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  28280. }
  28281. this._buffer.update(this._vertexData);
  28282. // Render
  28283. var effect = this._effectBase;
  28284. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28285. effect = this._effectFog;
  28286. }
  28287. engine.enableEffect(effect);
  28288. var viewMatrix = this._scene.getViewMatrix();
  28289. effect.setTexture("diffuseSampler", this._spriteTexture);
  28290. effect.setMatrix("view", viewMatrix);
  28291. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28292. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  28293. // Fog
  28294. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  28295. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  28296. effect.setColor3("vFogColor", this._scene.fogColor);
  28297. }
  28298. // VBOs
  28299. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28300. // Draw order
  28301. engine.setDepthFunctionToLessOrEqual();
  28302. effect.setBool("alphaTest", true);
  28303. engine.setColorWrite(false);
  28304. engine.draw(true, 0, max * 6);
  28305. engine.setColorWrite(true);
  28306. effect.setBool("alphaTest", false);
  28307. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28308. engine.draw(true, 0, max * 6);
  28309. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28310. };
  28311. SpriteManager.prototype.dispose = function () {
  28312. if (this._buffer) {
  28313. this._buffer.dispose();
  28314. this._buffer = null;
  28315. }
  28316. if (this._indexBuffer) {
  28317. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28318. this._indexBuffer = null;
  28319. }
  28320. if (this._spriteTexture) {
  28321. this._spriteTexture.dispose();
  28322. this._spriteTexture = null;
  28323. }
  28324. // Remove from scene
  28325. var index = this._scene.spriteManagers.indexOf(this);
  28326. this._scene.spriteManagers.splice(index, 1);
  28327. // Callback
  28328. this.onDisposeObservable.notifyObservers(this);
  28329. this.onDisposeObservable.clear();
  28330. };
  28331. return SpriteManager;
  28332. }());
  28333. BABYLON.SpriteManager = SpriteManager;
  28334. })(BABYLON || (BABYLON = {}));
  28335. //# sourceMappingURL=babylon.spriteManager.js.map
  28336. var BABYLON;
  28337. (function (BABYLON) {
  28338. var Sprite = (function () {
  28339. function Sprite(name, manager) {
  28340. this.name = name;
  28341. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28342. this.width = 1.0;
  28343. this.height = 1.0;
  28344. this.angle = 0;
  28345. this.cellIndex = 0;
  28346. this.invertU = 0;
  28347. this.invertV = 0;
  28348. this.animations = new Array();
  28349. this.isPickable = false;
  28350. this._animationStarted = false;
  28351. this._loopAnimation = false;
  28352. this._fromIndex = 0;
  28353. this._toIndex = 0;
  28354. this._delay = 0;
  28355. this._direction = 1;
  28356. this._frameCount = 0;
  28357. this._time = 0;
  28358. this._manager = manager;
  28359. this._manager.sprites.push(this);
  28360. this.position = BABYLON.Vector3.Zero();
  28361. }
  28362. Object.defineProperty(Sprite.prototype, "size", {
  28363. get: function () {
  28364. return this.width;
  28365. },
  28366. set: function (value) {
  28367. this.width = value;
  28368. this.height = value;
  28369. },
  28370. enumerable: true,
  28371. configurable: true
  28372. });
  28373. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  28374. this._fromIndex = from;
  28375. this._toIndex = to;
  28376. this._loopAnimation = loop;
  28377. this._delay = delay;
  28378. this._animationStarted = true;
  28379. this._direction = from < to ? 1 : -1;
  28380. this.cellIndex = from;
  28381. this._time = 0;
  28382. this._onAnimationEnd = onAnimationEnd;
  28383. };
  28384. Sprite.prototype.stopAnimation = function () {
  28385. this._animationStarted = false;
  28386. };
  28387. Sprite.prototype._animate = function (deltaTime) {
  28388. if (!this._animationStarted)
  28389. return;
  28390. this._time += deltaTime;
  28391. if (this._time > this._delay) {
  28392. this._time = this._time % this._delay;
  28393. this.cellIndex += this._direction;
  28394. if (this.cellIndex === this._toIndex) {
  28395. if (this._loopAnimation) {
  28396. this.cellIndex = this._fromIndex;
  28397. }
  28398. else {
  28399. this._animationStarted = false;
  28400. if (this._onAnimationEnd) {
  28401. this._onAnimationEnd();
  28402. }
  28403. if (this.disposeWhenFinishedAnimating) {
  28404. this.dispose();
  28405. }
  28406. }
  28407. }
  28408. }
  28409. };
  28410. Sprite.prototype.dispose = function () {
  28411. for (var i = 0; i < this._manager.sprites.length; i++) {
  28412. if (this._manager.sprites[i] == this) {
  28413. this._manager.sprites.splice(i, 1);
  28414. }
  28415. }
  28416. };
  28417. return Sprite;
  28418. }());
  28419. BABYLON.Sprite = Sprite;
  28420. })(BABYLON || (BABYLON = {}));
  28421. //# sourceMappingURL=babylon.sprite.js.map
  28422. var BABYLON;
  28423. (function (BABYLON) {
  28424. var Layer = (function () {
  28425. function Layer(name, imgUrl, scene, isBackground, color) {
  28426. this.name = name;
  28427. this.scale = new BABYLON.Vector2(1, 1);
  28428. this.offset = new BABYLON.Vector2(0, 0);
  28429. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  28430. this._vertexBuffers = {};
  28431. // Events
  28432. /**
  28433. * An event triggered when the layer is disposed.
  28434. * @type {BABYLON.Observable}
  28435. */
  28436. this.onDisposeObservable = new BABYLON.Observable();
  28437. /**
  28438. * An event triggered before rendering the scene
  28439. * @type {BABYLON.Observable}
  28440. */
  28441. this.onBeforeRenderObservable = new BABYLON.Observable();
  28442. /**
  28443. * An event triggered after rendering the scene
  28444. * @type {BABYLON.Observable}
  28445. */
  28446. this.onAfterRenderObservable = new BABYLON.Observable();
  28447. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  28448. this.isBackground = isBackground === undefined ? true : isBackground;
  28449. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  28450. this._scene = scene;
  28451. this._scene.layers.push(this);
  28452. var engine = scene.getEngine();
  28453. // VBO
  28454. var vertices = [];
  28455. vertices.push(1, 1);
  28456. vertices.push(-1, 1);
  28457. vertices.push(-1, -1);
  28458. vertices.push(1, -1);
  28459. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  28460. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  28461. // Indices
  28462. var indices = [];
  28463. indices.push(0);
  28464. indices.push(1);
  28465. indices.push(2);
  28466. indices.push(0);
  28467. indices.push(2);
  28468. indices.push(3);
  28469. this._indexBuffer = engine.createIndexBuffer(indices);
  28470. // Effects
  28471. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  28472. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  28473. }
  28474. Object.defineProperty(Layer.prototype, "onDispose", {
  28475. set: function (callback) {
  28476. if (this._onDisposeObserver) {
  28477. this.onDisposeObservable.remove(this._onDisposeObserver);
  28478. }
  28479. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28480. },
  28481. enumerable: true,
  28482. configurable: true
  28483. });
  28484. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  28485. set: function (callback) {
  28486. if (this._onBeforeRenderObserver) {
  28487. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  28488. }
  28489. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  28490. },
  28491. enumerable: true,
  28492. configurable: true
  28493. });
  28494. Object.defineProperty(Layer.prototype, "onAfterRender", {
  28495. set: function (callback) {
  28496. if (this._onAfterRenderObserver) {
  28497. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  28498. }
  28499. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  28500. },
  28501. enumerable: true,
  28502. configurable: true
  28503. });
  28504. Layer.prototype.render = function () {
  28505. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  28506. // Check
  28507. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  28508. return;
  28509. var engine = this._scene.getEngine();
  28510. this.onBeforeRenderObservable.notifyObservers(this);
  28511. // Render
  28512. engine.enableEffect(currentEffect);
  28513. engine.setState(false);
  28514. // Texture
  28515. currentEffect.setTexture("textureSampler", this.texture);
  28516. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  28517. // Color
  28518. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  28519. // Scale / offset
  28520. currentEffect.setVector2("offset", this.offset);
  28521. currentEffect.setVector2("scale", this.scale);
  28522. // VBOs
  28523. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  28524. // Draw order
  28525. if (!this.alphaTest) {
  28526. engine.setAlphaMode(this.alphaBlendingMode);
  28527. engine.draw(true, 0, 6);
  28528. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28529. }
  28530. else {
  28531. engine.draw(true, 0, 6);
  28532. }
  28533. this.onAfterRenderObservable.notifyObservers(this);
  28534. };
  28535. Layer.prototype.dispose = function () {
  28536. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  28537. if (vertexBuffer) {
  28538. vertexBuffer.dispose();
  28539. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  28540. }
  28541. if (this._indexBuffer) {
  28542. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28543. this._indexBuffer = null;
  28544. }
  28545. if (this.texture) {
  28546. this.texture.dispose();
  28547. this.texture = null;
  28548. }
  28549. // Remove from scene
  28550. var index = this._scene.layers.indexOf(this);
  28551. this._scene.layers.splice(index, 1);
  28552. // Callback
  28553. this.onDisposeObservable.notifyObservers(this);
  28554. this.onDisposeObservable.clear();
  28555. this.onAfterRenderObservable.clear();
  28556. this.onBeforeRenderObservable.clear();
  28557. };
  28558. return Layer;
  28559. }());
  28560. BABYLON.Layer = Layer;
  28561. })(BABYLON || (BABYLON = {}));
  28562. //# sourceMappingURL=babylon.layer.js.map
  28563. var BABYLON;
  28564. (function (BABYLON) {
  28565. var Particle = (function () {
  28566. function Particle() {
  28567. this.position = BABYLON.Vector3.Zero();
  28568. this.direction = BABYLON.Vector3.Zero();
  28569. this.color = new BABYLON.Color4(0, 0, 0, 0);
  28570. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  28571. this.lifeTime = 1.0;
  28572. this.age = 0;
  28573. this.size = 0;
  28574. this.angle = 0;
  28575. this.angularSpeed = 0;
  28576. }
  28577. Particle.prototype.copyTo = function (other) {
  28578. other.position.copyFrom(this.position);
  28579. other.direction.copyFrom(this.direction);
  28580. other.color.copyFrom(this.color);
  28581. other.colorStep.copyFrom(this.colorStep);
  28582. other.lifeTime = this.lifeTime;
  28583. other.age = this.age;
  28584. other.size = this.size;
  28585. other.angle = this.angle;
  28586. other.angularSpeed = this.angularSpeed;
  28587. };
  28588. return Particle;
  28589. }());
  28590. BABYLON.Particle = Particle;
  28591. })(BABYLON || (BABYLON = {}));
  28592. //# sourceMappingURL=babylon.particle.js.map
  28593. var BABYLON;
  28594. (function (BABYLON) {
  28595. var randomNumber = function (min, max) {
  28596. if (min === max) {
  28597. return (min);
  28598. }
  28599. var random = Math.random();
  28600. return ((random * (max - min)) + min);
  28601. };
  28602. var ParticleSystem = (function () {
  28603. function ParticleSystem(name, capacity, scene, customEffect) {
  28604. var _this = this;
  28605. this.name = name;
  28606. // Members
  28607. this.animations = [];
  28608. this.renderingGroupId = 0;
  28609. this.emitter = null;
  28610. this.emitRate = 10;
  28611. this.manualEmitCount = -1;
  28612. this.updateSpeed = 0.01;
  28613. this.targetStopDuration = 0;
  28614. this.disposeOnStop = false;
  28615. this.minEmitPower = 1;
  28616. this.maxEmitPower = 1;
  28617. this.minLifeTime = 1;
  28618. this.maxLifeTime = 1;
  28619. this.minSize = 1;
  28620. this.maxSize = 1;
  28621. this.minAngularSpeed = 0;
  28622. this.maxAngularSpeed = 0;
  28623. this.layerMask = 0x0FFFFFFF;
  28624. /**
  28625. * An event triggered when the system is disposed.
  28626. * @type {BABYLON.Observable}
  28627. */
  28628. this.onDisposeObservable = new BABYLON.Observable();
  28629. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  28630. this.forceDepthWrite = false;
  28631. this.gravity = BABYLON.Vector3.Zero();
  28632. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  28633. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  28634. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  28635. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  28636. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28637. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28638. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  28639. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  28640. this.particles = new Array();
  28641. this._stockParticles = new Array();
  28642. this._newPartsExcess = 0;
  28643. this._vertexBuffers = {};
  28644. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  28645. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  28646. this._scaledDirection = BABYLON.Vector3.Zero();
  28647. this._scaledGravity = BABYLON.Vector3.Zero();
  28648. this._currentRenderId = -1;
  28649. this._started = false;
  28650. this._stopped = false;
  28651. this._actualFrame = 0;
  28652. this.id = name;
  28653. this._capacity = capacity;
  28654. this._scene = scene;
  28655. this._customEffect = customEffect;
  28656. scene.particleSystems.push(this);
  28657. var indices = [];
  28658. var index = 0;
  28659. for (var count = 0; count < capacity; count++) {
  28660. indices.push(index);
  28661. indices.push(index + 1);
  28662. indices.push(index + 2);
  28663. indices.push(index);
  28664. indices.push(index + 2);
  28665. indices.push(index + 3);
  28666. index += 4;
  28667. }
  28668. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  28669. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  28670. this._vertexData = new Float32Array(capacity * 11 * 4);
  28671. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  28672. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  28673. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  28674. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  28675. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  28676. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  28677. this._vertexBuffers["options"] = options;
  28678. // Default behaviors
  28679. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  28680. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  28681. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  28682. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  28683. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  28684. };
  28685. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  28686. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  28687. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  28688. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  28689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  28690. };
  28691. this.updateFunction = function (particles) {
  28692. for (var index = 0; index < particles.length; index++) {
  28693. var particle = particles[index];
  28694. particle.age += _this._scaledUpdateSpeed;
  28695. if (particle.age >= particle.lifeTime) {
  28696. _this.recycleParticle(particle);
  28697. index--;
  28698. continue;
  28699. }
  28700. else {
  28701. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  28702. particle.color.addInPlace(_this._scaledColorStep);
  28703. if (particle.color.a < 0)
  28704. particle.color.a = 0;
  28705. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  28706. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  28707. particle.position.addInPlace(_this._scaledDirection);
  28708. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  28709. particle.direction.addInPlace(_this._scaledGravity);
  28710. }
  28711. }
  28712. };
  28713. }
  28714. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  28715. set: function (callback) {
  28716. if (this._onDisposeObserver) {
  28717. this.onDisposeObservable.remove(this._onDisposeObserver);
  28718. }
  28719. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  28720. },
  28721. enumerable: true,
  28722. configurable: true
  28723. });
  28724. ParticleSystem.prototype.recycleParticle = function (particle) {
  28725. var lastParticle = this.particles.pop();
  28726. if (lastParticle !== particle) {
  28727. lastParticle.copyTo(particle);
  28728. this._stockParticles.push(lastParticle);
  28729. }
  28730. };
  28731. ParticleSystem.prototype.getCapacity = function () {
  28732. return this._capacity;
  28733. };
  28734. ParticleSystem.prototype.isAlive = function () {
  28735. return this._alive;
  28736. };
  28737. ParticleSystem.prototype.isStarted = function () {
  28738. return this._started;
  28739. };
  28740. ParticleSystem.prototype.start = function () {
  28741. this._started = true;
  28742. this._stopped = false;
  28743. this._actualFrame = 0;
  28744. };
  28745. ParticleSystem.prototype.stop = function () {
  28746. this._stopped = true;
  28747. };
  28748. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  28749. var offset = index * 11;
  28750. this._vertexData[offset] = particle.position.x;
  28751. this._vertexData[offset + 1] = particle.position.y;
  28752. this._vertexData[offset + 2] = particle.position.z;
  28753. this._vertexData[offset + 3] = particle.color.r;
  28754. this._vertexData[offset + 4] = particle.color.g;
  28755. this._vertexData[offset + 5] = particle.color.b;
  28756. this._vertexData[offset + 6] = particle.color.a;
  28757. this._vertexData[offset + 7] = particle.angle;
  28758. this._vertexData[offset + 8] = particle.size;
  28759. this._vertexData[offset + 9] = offsetX;
  28760. this._vertexData[offset + 10] = offsetY;
  28761. };
  28762. ParticleSystem.prototype._update = function (newParticles) {
  28763. // Update current
  28764. this._alive = this.particles.length > 0;
  28765. this.updateFunction(this.particles);
  28766. // Add new ones
  28767. var worldMatrix;
  28768. if (this.emitter.position) {
  28769. worldMatrix = this.emitter.getWorldMatrix();
  28770. }
  28771. else {
  28772. worldMatrix = BABYLON.Matrix.Translation(this.emitter.x, this.emitter.y, this.emitter.z);
  28773. }
  28774. var particle;
  28775. for (var index = 0; index < newParticles; index++) {
  28776. if (this.particles.length === this._capacity) {
  28777. break;
  28778. }
  28779. if (this._stockParticles.length !== 0) {
  28780. particle = this._stockParticles.pop();
  28781. particle.age = 0;
  28782. }
  28783. else {
  28784. particle = new BABYLON.Particle();
  28785. }
  28786. this.particles.push(particle);
  28787. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  28788. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  28789. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  28790. particle.size = randomNumber(this.minSize, this.maxSize);
  28791. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  28792. this.startPositionFunction(worldMatrix, particle.position, particle);
  28793. var step = randomNumber(0, 1.0);
  28794. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  28795. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  28796. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  28797. }
  28798. };
  28799. ParticleSystem.prototype._getEffect = function () {
  28800. if (this._customEffect) {
  28801. return this._customEffect;
  28802. }
  28803. ;
  28804. var defines = [];
  28805. if (this._scene.clipPlane) {
  28806. defines.push("#define CLIPPLANE");
  28807. }
  28808. // Effect
  28809. var join = defines.join("\n");
  28810. if (this._cachedDefines !== join) {
  28811. this._cachedDefines = join;
  28812. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  28813. }
  28814. return this._effect;
  28815. };
  28816. ParticleSystem.prototype.animate = function () {
  28817. if (!this._started)
  28818. return;
  28819. var effect = this._getEffect();
  28820. // Check
  28821. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  28822. return;
  28823. if (this._currentRenderId === this._scene.getRenderId()) {
  28824. return;
  28825. }
  28826. this._currentRenderId = this._scene.getRenderId();
  28827. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  28828. // determine the number of particles we need to create
  28829. var newParticles;
  28830. if (this.manualEmitCount > -1) {
  28831. newParticles = this.manualEmitCount;
  28832. this._newPartsExcess = 0;
  28833. this.manualEmitCount = 0;
  28834. }
  28835. else {
  28836. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  28837. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  28838. }
  28839. if (this._newPartsExcess > 1.0) {
  28840. newParticles += this._newPartsExcess >> 0;
  28841. this._newPartsExcess -= this._newPartsExcess >> 0;
  28842. }
  28843. this._alive = false;
  28844. if (!this._stopped) {
  28845. this._actualFrame += this._scaledUpdateSpeed;
  28846. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  28847. this.stop();
  28848. }
  28849. else {
  28850. newParticles = 0;
  28851. }
  28852. this._update(newParticles);
  28853. // Stopped?
  28854. if (this._stopped) {
  28855. if (!this._alive) {
  28856. this._started = false;
  28857. if (this.disposeOnStop) {
  28858. this._scene._toBeDisposed.push(this);
  28859. }
  28860. }
  28861. }
  28862. // Update VBO
  28863. var offset = 0;
  28864. for (var index = 0; index < this.particles.length; index++) {
  28865. var particle = this.particles[index];
  28866. this._appendParticleVertex(offset++, particle, 0, 0);
  28867. this._appendParticleVertex(offset++, particle, 1, 0);
  28868. this._appendParticleVertex(offset++, particle, 1, 1);
  28869. this._appendParticleVertex(offset++, particle, 0, 1);
  28870. }
  28871. this._vertexBuffer.update(this._vertexData);
  28872. };
  28873. ParticleSystem.prototype.render = function () {
  28874. var effect = this._getEffect();
  28875. // Check
  28876. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  28877. return 0;
  28878. var engine = this._scene.getEngine();
  28879. // Render
  28880. engine.enableEffect(effect);
  28881. engine.setState(false);
  28882. var viewMatrix = this._scene.getViewMatrix();
  28883. effect.setTexture("diffuseSampler", this.particleTexture);
  28884. effect.setMatrix("view", viewMatrix);
  28885. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  28886. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  28887. if (this._scene.clipPlane) {
  28888. var clipPlane = this._scene.clipPlane;
  28889. var invView = viewMatrix.clone();
  28890. invView.invert();
  28891. effect.setMatrix("invView", invView);
  28892. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  28893. }
  28894. // VBOs
  28895. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  28896. // Draw order
  28897. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  28898. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  28899. }
  28900. else {
  28901. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  28902. }
  28903. if (this.forceDepthWrite) {
  28904. engine.setDepthWrite(true);
  28905. }
  28906. engine.draw(true, 0, this.particles.length * 6);
  28907. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  28908. return this.particles.length;
  28909. };
  28910. ParticleSystem.prototype.dispose = function () {
  28911. if (this._vertexBuffer) {
  28912. this._vertexBuffer.dispose();
  28913. this._vertexBuffer = null;
  28914. }
  28915. if (this._indexBuffer) {
  28916. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  28917. this._indexBuffer = null;
  28918. }
  28919. if (this.particleTexture) {
  28920. this.particleTexture.dispose();
  28921. this.particleTexture = null;
  28922. }
  28923. // Remove from scene
  28924. var index = this._scene.particleSystems.indexOf(this);
  28925. this._scene.particleSystems.splice(index, 1);
  28926. // Callback
  28927. this.onDisposeObservable.notifyObservers(this);
  28928. this.onDisposeObservable.clear();
  28929. };
  28930. // Clone
  28931. ParticleSystem.prototype.clone = function (name, newEmitter) {
  28932. var result = new ParticleSystem(name, this._capacity, this._scene);
  28933. BABYLON.Tools.DeepCopy(this, result, ["particles"]);
  28934. if (newEmitter === undefined) {
  28935. newEmitter = this.emitter;
  28936. }
  28937. result.emitter = newEmitter;
  28938. if (this.particleTexture) {
  28939. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  28940. }
  28941. result.start();
  28942. return result;
  28943. };
  28944. ParticleSystem.prototype.serialize = function () {
  28945. var serializationObject = {};
  28946. serializationObject.name = this.name;
  28947. serializationObject.id = this.id;
  28948. // Emitter
  28949. if (this.emitter.position) {
  28950. serializationObject.emitterId = this.emitter.id;
  28951. }
  28952. else {
  28953. serializationObject.emitter = this.emitter.asArray();
  28954. }
  28955. serializationObject.capacity = this.getCapacity();
  28956. if (this.particleTexture) {
  28957. serializationObject.textureName = this.particleTexture.name;
  28958. }
  28959. // Animations
  28960. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  28961. // Particle system
  28962. serializationObject.minAngularSpeed = this.minAngularSpeed;
  28963. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  28964. serializationObject.minSize = this.minSize;
  28965. serializationObject.maxSize = this.maxSize;
  28966. serializationObject.minEmitPower = this.minEmitPower;
  28967. serializationObject.maxEmitPower = this.maxEmitPower;
  28968. serializationObject.minLifeTime = this.minLifeTime;
  28969. serializationObject.maxLifeTime = this.maxLifeTime;
  28970. serializationObject.emitRate = this.emitRate;
  28971. serializationObject.minEmitBox = this.minEmitBox.asArray();
  28972. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  28973. serializationObject.gravity = this.gravity.asArray();
  28974. serializationObject.direction1 = this.direction1.asArray();
  28975. serializationObject.direction2 = this.direction2.asArray();
  28976. serializationObject.color1 = this.color1.asArray();
  28977. serializationObject.color2 = this.color2.asArray();
  28978. serializationObject.colorDead = this.colorDead.asArray();
  28979. serializationObject.updateSpeed = this.updateSpeed;
  28980. serializationObject.targetStopDuration = this.targetStopDuration;
  28981. serializationObject.textureMask = this.textureMask.asArray();
  28982. serializationObject.blendMode = this.blendMode;
  28983. return serializationObject;
  28984. };
  28985. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  28986. var name = parsedParticleSystem.name;
  28987. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene);
  28988. if (parsedParticleSystem.id) {
  28989. particleSystem.id = parsedParticleSystem.id;
  28990. }
  28991. // Texture
  28992. if (parsedParticleSystem.textureName) {
  28993. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  28994. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  28995. }
  28996. // Emitter
  28997. if (parsedParticleSystem.emitterId) {
  28998. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  28999. }
  29000. else {
  29001. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  29002. }
  29003. // Animations
  29004. if (parsedParticleSystem.animations) {
  29005. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  29006. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  29007. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  29008. }
  29009. }
  29010. if (parsedParticleSystem.autoAnimate) {
  29011. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  29012. }
  29013. // Particle system
  29014. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  29015. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  29016. particleSystem.minSize = parsedParticleSystem.minSize;
  29017. particleSystem.maxSize = parsedParticleSystem.maxSize;
  29018. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  29019. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  29020. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  29021. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  29022. particleSystem.emitRate = parsedParticleSystem.emitRate;
  29023. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  29024. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  29025. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  29026. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  29027. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  29028. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  29029. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  29030. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  29031. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  29032. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  29033. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  29034. particleSystem.blendMode = parsedParticleSystem.blendMode;
  29035. if (!parsedParticleSystem.preventAutoStart) {
  29036. particleSystem.start();
  29037. }
  29038. return particleSystem;
  29039. };
  29040. return ParticleSystem;
  29041. }());
  29042. // Statics
  29043. ParticleSystem.BLENDMODE_ONEONE = 0;
  29044. ParticleSystem.BLENDMODE_STANDARD = 1;
  29045. BABYLON.ParticleSystem = ParticleSystem;
  29046. })(BABYLON || (BABYLON = {}));
  29047. //# sourceMappingURL=babylon.particleSystem.js.map
  29048. var BABYLON;
  29049. (function (BABYLON) {
  29050. var AnimationRange = (function () {
  29051. function AnimationRange(name, from, to) {
  29052. this.name = name;
  29053. this.from = from;
  29054. this.to = to;
  29055. }
  29056. AnimationRange.prototype.clone = function () {
  29057. return new AnimationRange(this.name, this.from, this.to);
  29058. };
  29059. return AnimationRange;
  29060. }());
  29061. BABYLON.AnimationRange = AnimationRange;
  29062. /**
  29063. * Composed of a frame, and an action function
  29064. */
  29065. var AnimationEvent = (function () {
  29066. function AnimationEvent(frame, action, onlyOnce) {
  29067. this.frame = frame;
  29068. this.action = action;
  29069. this.onlyOnce = onlyOnce;
  29070. this.isDone = false;
  29071. }
  29072. return AnimationEvent;
  29073. }());
  29074. BABYLON.AnimationEvent = AnimationEvent;
  29075. var PathCursor = (function () {
  29076. function PathCursor(path) {
  29077. this.path = path;
  29078. this._onchange = new Array();
  29079. this.value = 0;
  29080. this.animations = new Array();
  29081. }
  29082. PathCursor.prototype.getPoint = function () {
  29083. var point = this.path.getPointAtLengthPosition(this.value);
  29084. return new BABYLON.Vector3(point.x, 0, point.y);
  29085. };
  29086. PathCursor.prototype.moveAhead = function (step) {
  29087. if (step === void 0) { step = 0.002; }
  29088. this.move(step);
  29089. return this;
  29090. };
  29091. PathCursor.prototype.moveBack = function (step) {
  29092. if (step === void 0) { step = 0.002; }
  29093. this.move(-step);
  29094. return this;
  29095. };
  29096. PathCursor.prototype.move = function (step) {
  29097. if (Math.abs(step) > 1) {
  29098. throw "step size should be less than 1.";
  29099. }
  29100. this.value += step;
  29101. this.ensureLimits();
  29102. this.raiseOnChange();
  29103. return this;
  29104. };
  29105. PathCursor.prototype.ensureLimits = function () {
  29106. while (this.value > 1) {
  29107. this.value -= 1;
  29108. }
  29109. while (this.value < 0) {
  29110. this.value += 1;
  29111. }
  29112. return this;
  29113. };
  29114. // used by animation engine
  29115. PathCursor.prototype.markAsDirty = function (propertyName) {
  29116. this.ensureLimits();
  29117. this.raiseOnChange();
  29118. return this;
  29119. };
  29120. PathCursor.prototype.raiseOnChange = function () {
  29121. var _this = this;
  29122. this._onchange.forEach(function (f) { return f(_this); });
  29123. return this;
  29124. };
  29125. PathCursor.prototype.onchange = function (f) {
  29126. this._onchange.push(f);
  29127. return this;
  29128. };
  29129. return PathCursor;
  29130. }());
  29131. BABYLON.PathCursor = PathCursor;
  29132. var Animation = (function () {
  29133. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  29134. this.name = name;
  29135. this.targetProperty = targetProperty;
  29136. this.framePerSecond = framePerSecond;
  29137. this.dataType = dataType;
  29138. this.loopMode = loopMode;
  29139. this.enableBlending = enableBlending;
  29140. this._offsetsCache = {};
  29141. this._highLimitsCache = {};
  29142. this._stopped = false;
  29143. this._blendingFactor = 0;
  29144. // The set of event that will be linked to this animation
  29145. this._events = new Array();
  29146. this.allowMatricesInterpolation = false;
  29147. this.blendingSpeed = 0.01;
  29148. this._ranges = {};
  29149. this.targetPropertyPath = targetProperty.split(".");
  29150. this.dataType = dataType;
  29151. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  29152. }
  29153. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  29154. var dataType = undefined;
  29155. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  29156. dataType = Animation.ANIMATIONTYPE_FLOAT;
  29157. }
  29158. else if (from instanceof BABYLON.Quaternion) {
  29159. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  29160. }
  29161. else if (from instanceof BABYLON.Vector3) {
  29162. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  29163. }
  29164. else if (from instanceof BABYLON.Vector2) {
  29165. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  29166. }
  29167. else if (from instanceof BABYLON.Color3) {
  29168. dataType = Animation.ANIMATIONTYPE_COLOR3;
  29169. }
  29170. else if (from instanceof BABYLON.Size) {
  29171. dataType = Animation.ANIMATIONTYPE_SIZE;
  29172. }
  29173. if (dataType == undefined) {
  29174. return null;
  29175. }
  29176. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  29177. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  29178. animation.setKeys(keys);
  29179. if (easingFunction !== undefined) {
  29180. animation.setEasingFunction(easingFunction);
  29181. }
  29182. return animation;
  29183. };
  29184. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29185. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29186. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29187. };
  29188. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  29189. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  29190. node.animations.push(animation);
  29191. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  29192. };
  29193. // Methods
  29194. /**
  29195. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  29196. */
  29197. Animation.prototype.toString = function (fullDetails) {
  29198. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  29199. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  29200. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  29201. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  29202. if (fullDetails) {
  29203. ret += ", Ranges: {";
  29204. var first = true;
  29205. for (var name in this._ranges) {
  29206. if (first) {
  29207. ret += ", ";
  29208. first = false;
  29209. }
  29210. ret += name;
  29211. }
  29212. ret += "}";
  29213. }
  29214. return ret;
  29215. };
  29216. /**
  29217. * Add an event to this animation.
  29218. */
  29219. Animation.prototype.addEvent = function (event) {
  29220. this._events.push(event);
  29221. };
  29222. /**
  29223. * Remove all events found at the given frame
  29224. * @param frame
  29225. */
  29226. Animation.prototype.removeEvents = function (frame) {
  29227. for (var index = 0; index < this._events.length; index++) {
  29228. if (this._events[index].frame === frame) {
  29229. this._events.splice(index, 1);
  29230. index--;
  29231. }
  29232. }
  29233. };
  29234. Animation.prototype.createRange = function (name, from, to) {
  29235. // check name not already in use; could happen for bones after serialized
  29236. if (!this._ranges[name]) {
  29237. this._ranges[name] = new AnimationRange(name, from, to);
  29238. }
  29239. };
  29240. Animation.prototype.deleteRange = function (name, deleteFrames) {
  29241. if (deleteFrames === void 0) { deleteFrames = true; }
  29242. if (this._ranges[name]) {
  29243. if (deleteFrames) {
  29244. var from = this._ranges[name].from;
  29245. var to = this._ranges[name].to;
  29246. // this loop MUST go high to low for multiple splices to work
  29247. for (var key = this._keys.length - 1; key >= 0; key--) {
  29248. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  29249. this._keys.splice(key, 1);
  29250. }
  29251. }
  29252. }
  29253. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  29254. }
  29255. };
  29256. Animation.prototype.getRange = function (name) {
  29257. return this._ranges[name];
  29258. };
  29259. Animation.prototype.reset = function () {
  29260. this._offsetsCache = {};
  29261. this._highLimitsCache = {};
  29262. this.currentFrame = 0;
  29263. this._blendingFactor = 0;
  29264. this._originalBlendValue = null;
  29265. };
  29266. Animation.prototype.isStopped = function () {
  29267. return this._stopped;
  29268. };
  29269. Animation.prototype.getKeys = function () {
  29270. return this._keys;
  29271. };
  29272. Animation.prototype.getHighestFrame = function () {
  29273. var ret = 0;
  29274. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  29275. if (ret < this._keys[key].frame) {
  29276. ret = this._keys[key].frame;
  29277. }
  29278. }
  29279. return ret;
  29280. };
  29281. Animation.prototype.getEasingFunction = function () {
  29282. return this._easingFunction;
  29283. };
  29284. Animation.prototype.setEasingFunction = function (easingFunction) {
  29285. this._easingFunction = easingFunction;
  29286. };
  29287. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  29288. return startValue + (endValue - startValue) * gradient;
  29289. };
  29290. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  29291. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  29292. };
  29293. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  29294. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  29295. };
  29296. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  29297. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  29298. };
  29299. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  29300. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  29301. };
  29302. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  29303. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  29304. };
  29305. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  29306. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  29307. };
  29308. Animation.prototype.clone = function () {
  29309. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  29310. if (this._keys) {
  29311. clone.setKeys(this._keys);
  29312. }
  29313. if (this._ranges) {
  29314. clone._ranges = {};
  29315. for (var name in this._ranges) {
  29316. clone._ranges[name] = this._ranges[name].clone();
  29317. }
  29318. }
  29319. return clone;
  29320. };
  29321. Animation.prototype.setKeys = function (values) {
  29322. this._keys = values.slice(0);
  29323. this._offsetsCache = {};
  29324. this._highLimitsCache = {};
  29325. };
  29326. Animation.prototype._getKeyValue = function (value) {
  29327. if (typeof value === "function") {
  29328. return value();
  29329. }
  29330. return value;
  29331. };
  29332. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  29333. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  29334. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  29335. }
  29336. this.currentFrame = currentFrame;
  29337. // Try to get a hash to find the right key
  29338. 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));
  29339. if (this._keys[startKey].frame >= currentFrame) {
  29340. while (startKey - 1 >= 0 && this._keys[startKey].frame >= currentFrame) {
  29341. startKey--;
  29342. }
  29343. }
  29344. for (var key = startKey; key < this._keys.length; key++) {
  29345. if (this._keys[key + 1].frame >= currentFrame) {
  29346. var startValue = this._getKeyValue(this._keys[key].value);
  29347. var endValue = this._getKeyValue(this._keys[key + 1].value);
  29348. // gradient : percent of currentFrame between the frame inf and the frame sup
  29349. var gradient = (currentFrame - this._keys[key].frame) / (this._keys[key + 1].frame - this._keys[key].frame);
  29350. // check for easingFunction and correction of gradient
  29351. if (this._easingFunction != null) {
  29352. gradient = this._easingFunction.ease(gradient);
  29353. }
  29354. switch (this.dataType) {
  29355. // Float
  29356. case Animation.ANIMATIONTYPE_FLOAT:
  29357. switch (loopMode) {
  29358. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29359. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29360. return this.floatInterpolateFunction(startValue, endValue, gradient);
  29361. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29362. return offsetValue * repeatCount + this.floatInterpolateFunction(startValue, endValue, gradient);
  29363. }
  29364. break;
  29365. // Quaternion
  29366. case Animation.ANIMATIONTYPE_QUATERNION:
  29367. var quaternion = null;
  29368. switch (loopMode) {
  29369. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29370. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29371. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient);
  29372. break;
  29373. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29374. quaternion = this.quaternionInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29375. break;
  29376. }
  29377. return quaternion;
  29378. // Vector3
  29379. case Animation.ANIMATIONTYPE_VECTOR3:
  29380. switch (loopMode) {
  29381. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29382. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29383. return this.vector3InterpolateFunction(startValue, endValue, gradient);
  29384. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29385. return this.vector3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29386. }
  29387. // Vector2
  29388. case Animation.ANIMATIONTYPE_VECTOR2:
  29389. switch (loopMode) {
  29390. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29391. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29392. return this.vector2InterpolateFunction(startValue, endValue, gradient);
  29393. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29394. return this.vector2InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29395. }
  29396. // Size
  29397. case Animation.ANIMATIONTYPE_SIZE:
  29398. switch (loopMode) {
  29399. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29400. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29401. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  29402. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29403. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29404. }
  29405. // Color3
  29406. case Animation.ANIMATIONTYPE_COLOR3:
  29407. switch (loopMode) {
  29408. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29409. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29410. return this.color3InterpolateFunction(startValue, endValue, gradient);
  29411. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29412. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  29413. }
  29414. // Matrix
  29415. case Animation.ANIMATIONTYPE_MATRIX:
  29416. switch (loopMode) {
  29417. case Animation.ANIMATIONLOOPMODE_CYCLE:
  29418. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  29419. if (this.allowMatricesInterpolation) {
  29420. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  29421. }
  29422. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  29423. return startValue;
  29424. }
  29425. default:
  29426. break;
  29427. }
  29428. break;
  29429. }
  29430. }
  29431. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  29432. };
  29433. Animation.prototype.setValue = function (currentValue, blend) {
  29434. if (blend === void 0) { blend = false; }
  29435. // Set value
  29436. var path;
  29437. var destination;
  29438. if (this.targetPropertyPath.length > 1) {
  29439. var property = this._target[this.targetPropertyPath[0]];
  29440. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  29441. property = property[this.targetPropertyPath[index]];
  29442. }
  29443. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  29444. destination = property;
  29445. }
  29446. else {
  29447. path = this.targetPropertyPath[0];
  29448. destination = this._target;
  29449. }
  29450. // Blending
  29451. if (this.enableBlending && this._blendingFactor <= 1.0) {
  29452. if (!this._originalBlendValue) {
  29453. if (destination[path].clone) {
  29454. this._originalBlendValue = destination[path].clone();
  29455. }
  29456. else {
  29457. this._originalBlendValue = destination[path];
  29458. }
  29459. }
  29460. if (this._originalBlendValue.prototype) {
  29461. if (this._originalBlendValue.prototype.Lerp) {
  29462. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  29463. }
  29464. else {
  29465. destination[path] = currentValue;
  29466. }
  29467. }
  29468. else if (this._originalBlendValue.m) {
  29469. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  29470. }
  29471. else {
  29472. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  29473. }
  29474. this._blendingFactor += this.blendingSpeed;
  29475. }
  29476. else {
  29477. destination[path] = currentValue;
  29478. }
  29479. if (this._target.markAsDirty) {
  29480. this._target.markAsDirty(this.targetProperty);
  29481. }
  29482. };
  29483. Animation.prototype.goToFrame = function (frame) {
  29484. if (frame < this._keys[0].frame) {
  29485. frame = this._keys[0].frame;
  29486. }
  29487. else if (frame > this._keys[this._keys.length - 1].frame) {
  29488. frame = this._keys[this._keys.length - 1].frame;
  29489. }
  29490. var currentValue = this._interpolate(frame, 0, this.loopMode);
  29491. this.setValue(currentValue);
  29492. };
  29493. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  29494. if (blend === void 0) { blend = false; }
  29495. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  29496. this._stopped = true;
  29497. return false;
  29498. }
  29499. var returnValue = true;
  29500. // Adding a start key at frame 0 if missing
  29501. if (this._keys[0].frame !== 0) {
  29502. var newKey = { frame: 0, value: this._keys[0].value };
  29503. this._keys.splice(0, 0, newKey);
  29504. }
  29505. // Check limits
  29506. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  29507. from = this._keys[0].frame;
  29508. }
  29509. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  29510. to = this._keys[this._keys.length - 1].frame;
  29511. }
  29512. //to and from cannot be the same key
  29513. if (from === to) {
  29514. from++;
  29515. }
  29516. // Compute ratio
  29517. var range = to - from;
  29518. var offsetValue;
  29519. // ratio represents the frame delta between from and to
  29520. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  29521. var highLimitValue = 0;
  29522. if (ratio > range && !loop) {
  29523. returnValue = false;
  29524. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  29525. }
  29526. else {
  29527. // Get max value if required
  29528. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  29529. var keyOffset = to.toString() + from.toString();
  29530. if (!this._offsetsCache[keyOffset]) {
  29531. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29532. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  29533. switch (this.dataType) {
  29534. // Float
  29535. case Animation.ANIMATIONTYPE_FLOAT:
  29536. this._offsetsCache[keyOffset] = toValue - fromValue;
  29537. break;
  29538. // Quaternion
  29539. case Animation.ANIMATIONTYPE_QUATERNION:
  29540. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29541. break;
  29542. // Vector3
  29543. case Animation.ANIMATIONTYPE_VECTOR3:
  29544. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29545. // Vector2
  29546. case Animation.ANIMATIONTYPE_VECTOR2:
  29547. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29548. // Size
  29549. case Animation.ANIMATIONTYPE_SIZE:
  29550. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29551. // Color3
  29552. case Animation.ANIMATIONTYPE_COLOR3:
  29553. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  29554. default:
  29555. break;
  29556. }
  29557. this._highLimitsCache[keyOffset] = toValue;
  29558. }
  29559. highLimitValue = this._highLimitsCache[keyOffset];
  29560. offsetValue = this._offsetsCache[keyOffset];
  29561. }
  29562. }
  29563. if (offsetValue === undefined) {
  29564. switch (this.dataType) {
  29565. // Float
  29566. case Animation.ANIMATIONTYPE_FLOAT:
  29567. offsetValue = 0;
  29568. break;
  29569. // Quaternion
  29570. case Animation.ANIMATIONTYPE_QUATERNION:
  29571. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  29572. break;
  29573. // Vector3
  29574. case Animation.ANIMATIONTYPE_VECTOR3:
  29575. offsetValue = BABYLON.Vector3.Zero();
  29576. break;
  29577. // Vector2
  29578. case Animation.ANIMATIONTYPE_VECTOR2:
  29579. offsetValue = BABYLON.Vector2.Zero();
  29580. break;
  29581. // Size
  29582. case Animation.ANIMATIONTYPE_SIZE:
  29583. offsetValue = BABYLON.Size.Zero();
  29584. break;
  29585. // Color3
  29586. case Animation.ANIMATIONTYPE_COLOR3:
  29587. offsetValue = BABYLON.Color3.Black();
  29588. }
  29589. }
  29590. // Compute value
  29591. var repeatCount = (ratio / range) >> 0;
  29592. var currentFrame = returnValue ? from + ratio % range : to;
  29593. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  29594. // Set value
  29595. this.setValue(currentValue);
  29596. // Check events
  29597. for (var index = 0; index < this._events.length; index++) {
  29598. if (currentFrame >= this._events[index].frame) {
  29599. var event = this._events[index];
  29600. if (!event.isDone) {
  29601. // If event should be done only once, remove it.
  29602. if (event.onlyOnce) {
  29603. this._events.splice(index, 1);
  29604. index--;
  29605. }
  29606. event.isDone = true;
  29607. event.action();
  29608. } // Don't do anything if the event has already be done.
  29609. }
  29610. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  29611. // reset event, the animation is looping
  29612. this._events[index].isDone = false;
  29613. }
  29614. }
  29615. if (!returnValue) {
  29616. this._stopped = true;
  29617. }
  29618. return returnValue;
  29619. };
  29620. Animation.prototype.serialize = function () {
  29621. var serializationObject = {};
  29622. serializationObject.name = this.name;
  29623. serializationObject.property = this.targetProperty;
  29624. serializationObject.framePerSecond = this.framePerSecond;
  29625. serializationObject.dataType = this.dataType;
  29626. serializationObject.loopBehavior = this.loopMode;
  29627. var dataType = this.dataType;
  29628. serializationObject.keys = [];
  29629. var keys = this.getKeys();
  29630. for (var index = 0; index < keys.length; index++) {
  29631. var animationKey = keys[index];
  29632. var key = {};
  29633. key.frame = animationKey.frame;
  29634. switch (dataType) {
  29635. case Animation.ANIMATIONTYPE_FLOAT:
  29636. key.values = [animationKey.value];
  29637. break;
  29638. case Animation.ANIMATIONTYPE_QUATERNION:
  29639. case Animation.ANIMATIONTYPE_MATRIX:
  29640. case Animation.ANIMATIONTYPE_VECTOR3:
  29641. case Animation.ANIMATIONTYPE_COLOR3:
  29642. key.values = animationKey.value.asArray();
  29643. break;
  29644. }
  29645. serializationObject.keys.push(key);
  29646. }
  29647. serializationObject.ranges = [];
  29648. for (var name in this._ranges) {
  29649. var range = {};
  29650. range.name = name;
  29651. range.from = this._ranges[name].from;
  29652. range.to = this._ranges[name].to;
  29653. serializationObject.ranges.push(range);
  29654. }
  29655. return serializationObject;
  29656. };
  29657. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  29658. get: function () {
  29659. return Animation._ANIMATIONTYPE_FLOAT;
  29660. },
  29661. enumerable: true,
  29662. configurable: true
  29663. });
  29664. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  29665. get: function () {
  29666. return Animation._ANIMATIONTYPE_VECTOR3;
  29667. },
  29668. enumerable: true,
  29669. configurable: true
  29670. });
  29671. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  29672. get: function () {
  29673. return Animation._ANIMATIONTYPE_VECTOR2;
  29674. },
  29675. enumerable: true,
  29676. configurable: true
  29677. });
  29678. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  29679. get: function () {
  29680. return Animation._ANIMATIONTYPE_SIZE;
  29681. },
  29682. enumerable: true,
  29683. configurable: true
  29684. });
  29685. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  29686. get: function () {
  29687. return Animation._ANIMATIONTYPE_QUATERNION;
  29688. },
  29689. enumerable: true,
  29690. configurable: true
  29691. });
  29692. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  29693. get: function () {
  29694. return Animation._ANIMATIONTYPE_MATRIX;
  29695. },
  29696. enumerable: true,
  29697. configurable: true
  29698. });
  29699. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  29700. get: function () {
  29701. return Animation._ANIMATIONTYPE_COLOR3;
  29702. },
  29703. enumerable: true,
  29704. configurable: true
  29705. });
  29706. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  29707. get: function () {
  29708. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  29709. },
  29710. enumerable: true,
  29711. configurable: true
  29712. });
  29713. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  29714. get: function () {
  29715. return Animation._ANIMATIONLOOPMODE_CYCLE;
  29716. },
  29717. enumerable: true,
  29718. configurable: true
  29719. });
  29720. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  29721. get: function () {
  29722. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  29723. },
  29724. enumerable: true,
  29725. configurable: true
  29726. });
  29727. Animation.Parse = function (parsedAnimation) {
  29728. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  29729. var dataType = parsedAnimation.dataType;
  29730. var keys = [];
  29731. var data;
  29732. var index;
  29733. for (index = 0; index < parsedAnimation.keys.length; index++) {
  29734. var key = parsedAnimation.keys[index];
  29735. switch (dataType) {
  29736. case Animation.ANIMATIONTYPE_FLOAT:
  29737. data = key.values[0];
  29738. break;
  29739. case Animation.ANIMATIONTYPE_QUATERNION:
  29740. data = BABYLON.Quaternion.FromArray(key.values);
  29741. break;
  29742. case Animation.ANIMATIONTYPE_MATRIX:
  29743. data = BABYLON.Matrix.FromArray(key.values);
  29744. break;
  29745. case Animation.ANIMATIONTYPE_COLOR3:
  29746. data = BABYLON.Color3.FromArray(key.values);
  29747. break;
  29748. case Animation.ANIMATIONTYPE_VECTOR3:
  29749. default:
  29750. data = BABYLON.Vector3.FromArray(key.values);
  29751. break;
  29752. }
  29753. keys.push({
  29754. frame: key.frame,
  29755. value: data
  29756. });
  29757. }
  29758. animation.setKeys(keys);
  29759. if (parsedAnimation.ranges) {
  29760. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  29761. data = parsedAnimation.ranges[index];
  29762. animation.createRange(data.name, data.from, data.to);
  29763. }
  29764. }
  29765. return animation;
  29766. };
  29767. Animation.AppendSerializedAnimations = function (source, destination) {
  29768. if (source.animations) {
  29769. destination.animations = [];
  29770. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  29771. var animation = source.animations[animationIndex];
  29772. destination.animations.push(animation.serialize());
  29773. }
  29774. }
  29775. };
  29776. return Animation;
  29777. }());
  29778. // Statics
  29779. Animation._ANIMATIONTYPE_FLOAT = 0;
  29780. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  29781. Animation._ANIMATIONTYPE_QUATERNION = 2;
  29782. Animation._ANIMATIONTYPE_MATRIX = 3;
  29783. Animation._ANIMATIONTYPE_COLOR3 = 4;
  29784. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  29785. Animation._ANIMATIONTYPE_SIZE = 6;
  29786. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  29787. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  29788. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  29789. BABYLON.Animation = Animation;
  29790. })(BABYLON || (BABYLON = {}));
  29791. //# sourceMappingURL=babylon.animation.js.map
  29792. var BABYLON;
  29793. (function (BABYLON) {
  29794. var Animatable = (function () {
  29795. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  29796. if (fromFrame === void 0) { fromFrame = 0; }
  29797. if (toFrame === void 0) { toFrame = 100; }
  29798. if (loopAnimation === void 0) { loopAnimation = false; }
  29799. if (speedRatio === void 0) { speedRatio = 1.0; }
  29800. this.target = target;
  29801. this.fromFrame = fromFrame;
  29802. this.toFrame = toFrame;
  29803. this.loopAnimation = loopAnimation;
  29804. this.speedRatio = speedRatio;
  29805. this.onAnimationEnd = onAnimationEnd;
  29806. this._animations = new Array();
  29807. this._paused = false;
  29808. this.animationStarted = false;
  29809. if (animations) {
  29810. this.appendAnimations(target, animations);
  29811. }
  29812. this._scene = scene;
  29813. scene._activeAnimatables.push(this);
  29814. }
  29815. // Methods
  29816. Animatable.prototype.getAnimations = function () {
  29817. return this._animations;
  29818. };
  29819. Animatable.prototype.appendAnimations = function (target, animations) {
  29820. for (var index = 0; index < animations.length; index++) {
  29821. var animation = animations[index];
  29822. animation._target = target;
  29823. this._animations.push(animation);
  29824. }
  29825. };
  29826. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  29827. var animations = this._animations;
  29828. for (var index = 0; index < animations.length; index++) {
  29829. if (animations[index].targetProperty === property) {
  29830. return animations[index];
  29831. }
  29832. }
  29833. return null;
  29834. };
  29835. Animatable.prototype.reset = function () {
  29836. var animations = this._animations;
  29837. for (var index = 0; index < animations.length; index++) {
  29838. animations[index].reset();
  29839. }
  29840. this._localDelayOffset = null;
  29841. this._pausedDelay = null;
  29842. };
  29843. Animatable.prototype.enableBlending = function (blendingSpeed) {
  29844. var animations = this._animations;
  29845. for (var index = 0; index < animations.length; index++) {
  29846. animations[index].enableBlending = true;
  29847. animations[index].blendingSpeed = blendingSpeed;
  29848. }
  29849. };
  29850. Animatable.prototype.disableBlending = function () {
  29851. var animations = this._animations;
  29852. for (var index = 0; index < animations.length; index++) {
  29853. animations[index].enableBlending = false;
  29854. }
  29855. };
  29856. Animatable.prototype.goToFrame = function (frame) {
  29857. var animations = this._animations;
  29858. if (animations[0]) {
  29859. var fps = animations[0].framePerSecond;
  29860. var currentFrame = animations[0].currentFrame;
  29861. var adjustTime = frame - currentFrame;
  29862. var delay = adjustTime * 1000 / fps;
  29863. this._localDelayOffset -= delay;
  29864. }
  29865. for (var index = 0; index < animations.length; index++) {
  29866. animations[index].goToFrame(frame);
  29867. }
  29868. };
  29869. Animatable.prototype.pause = function () {
  29870. if (this._paused) {
  29871. return;
  29872. }
  29873. this._paused = true;
  29874. };
  29875. Animatable.prototype.restart = function () {
  29876. this._paused = false;
  29877. };
  29878. Animatable.prototype.stop = function (animationName) {
  29879. var idx = this._scene._activeAnimatables.indexOf(this);
  29880. if (idx > -1) {
  29881. var animations = this._animations;
  29882. var numberOfAnimationsStopped = 0;
  29883. for (var index = animations.length - 1; index >= 0; index--) {
  29884. if (typeof animationName === "string" && animations[index].name != animationName) {
  29885. continue;
  29886. }
  29887. animations[index].reset();
  29888. animations.splice(index, 1);
  29889. numberOfAnimationsStopped++;
  29890. }
  29891. if (animations.length == numberOfAnimationsStopped) {
  29892. this._scene._activeAnimatables.splice(idx, 1);
  29893. if (this.onAnimationEnd) {
  29894. this.onAnimationEnd();
  29895. }
  29896. }
  29897. }
  29898. };
  29899. Animatable.prototype._animate = function (delay) {
  29900. if (this._paused) {
  29901. this.animationStarted = false;
  29902. if (!this._pausedDelay) {
  29903. this._pausedDelay = delay;
  29904. }
  29905. return true;
  29906. }
  29907. if (!this._localDelayOffset) {
  29908. this._localDelayOffset = delay;
  29909. }
  29910. else if (this._pausedDelay) {
  29911. this._localDelayOffset += delay - this._pausedDelay;
  29912. this._pausedDelay = null;
  29913. }
  29914. // Animating
  29915. var running = false;
  29916. var animations = this._animations;
  29917. var index;
  29918. for (index = 0; index < animations.length; index++) {
  29919. var animation = animations[index];
  29920. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  29921. running = running || isRunning;
  29922. }
  29923. this.animationStarted = running;
  29924. if (!running) {
  29925. // Remove from active animatables
  29926. index = this._scene._activeAnimatables.indexOf(this);
  29927. this._scene._activeAnimatables.splice(index, 1);
  29928. }
  29929. if (!running && this.onAnimationEnd) {
  29930. this.onAnimationEnd();
  29931. this.onAnimationEnd = null;
  29932. }
  29933. return running;
  29934. };
  29935. return Animatable;
  29936. }());
  29937. BABYLON.Animatable = Animatable;
  29938. })(BABYLON || (BABYLON = {}));
  29939. //# sourceMappingURL=babylon.animatable.js.map
  29940. var BABYLON;
  29941. (function (BABYLON) {
  29942. var EasingFunction = (function () {
  29943. function EasingFunction() {
  29944. // Properties
  29945. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  29946. }
  29947. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  29948. get: function () {
  29949. return EasingFunction._EASINGMODE_EASEIN;
  29950. },
  29951. enumerable: true,
  29952. configurable: true
  29953. });
  29954. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  29955. get: function () {
  29956. return EasingFunction._EASINGMODE_EASEOUT;
  29957. },
  29958. enumerable: true,
  29959. configurable: true
  29960. });
  29961. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  29962. get: function () {
  29963. return EasingFunction._EASINGMODE_EASEINOUT;
  29964. },
  29965. enumerable: true,
  29966. configurable: true
  29967. });
  29968. EasingFunction.prototype.setEasingMode = function (easingMode) {
  29969. var n = Math.min(Math.max(easingMode, 0), 2);
  29970. this._easingMode = n;
  29971. };
  29972. EasingFunction.prototype.getEasingMode = function () {
  29973. return this._easingMode;
  29974. };
  29975. EasingFunction.prototype.easeInCore = function (gradient) {
  29976. throw new Error('You must implement this method');
  29977. };
  29978. EasingFunction.prototype.ease = function (gradient) {
  29979. switch (this._easingMode) {
  29980. case EasingFunction.EASINGMODE_EASEIN:
  29981. return this.easeInCore(gradient);
  29982. case EasingFunction.EASINGMODE_EASEOUT:
  29983. return (1 - this.easeInCore(1 - gradient));
  29984. }
  29985. if (gradient >= 0.5) {
  29986. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  29987. }
  29988. return (this.easeInCore(gradient * 2) * 0.5);
  29989. };
  29990. return EasingFunction;
  29991. }());
  29992. //Statics
  29993. EasingFunction._EASINGMODE_EASEIN = 0;
  29994. EasingFunction._EASINGMODE_EASEOUT = 1;
  29995. EasingFunction._EASINGMODE_EASEINOUT = 2;
  29996. BABYLON.EasingFunction = EasingFunction;
  29997. var CircleEase = (function (_super) {
  29998. __extends(CircleEase, _super);
  29999. function CircleEase() {
  30000. return _super.apply(this, arguments) || this;
  30001. }
  30002. CircleEase.prototype.easeInCore = function (gradient) {
  30003. gradient = Math.max(0, Math.min(1, gradient));
  30004. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  30005. };
  30006. return CircleEase;
  30007. }(EasingFunction));
  30008. BABYLON.CircleEase = CircleEase;
  30009. var BackEase = (function (_super) {
  30010. __extends(BackEase, _super);
  30011. function BackEase(amplitude) {
  30012. if (amplitude === void 0) { amplitude = 1; }
  30013. var _this = _super.call(this) || this;
  30014. _this.amplitude = amplitude;
  30015. return _this;
  30016. }
  30017. BackEase.prototype.easeInCore = function (gradient) {
  30018. var num = Math.max(0, this.amplitude);
  30019. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  30020. };
  30021. return BackEase;
  30022. }(EasingFunction));
  30023. BABYLON.BackEase = BackEase;
  30024. var BounceEase = (function (_super) {
  30025. __extends(BounceEase, _super);
  30026. function BounceEase(bounces, bounciness) {
  30027. if (bounces === void 0) { bounces = 3; }
  30028. if (bounciness === void 0) { bounciness = 2; }
  30029. var _this = _super.call(this) || this;
  30030. _this.bounces = bounces;
  30031. _this.bounciness = bounciness;
  30032. return _this;
  30033. }
  30034. BounceEase.prototype.easeInCore = function (gradient) {
  30035. var y = Math.max(0.0, this.bounces);
  30036. var bounciness = this.bounciness;
  30037. if (bounciness <= 1.0) {
  30038. bounciness = 1.001;
  30039. }
  30040. var num9 = Math.pow(bounciness, y);
  30041. var num5 = 1.0 - bounciness;
  30042. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  30043. var num15 = gradient * num4;
  30044. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  30045. var num3 = Math.floor(num65);
  30046. var num13 = num3 + 1.0;
  30047. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  30048. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  30049. var num7 = (num8 + num12) * 0.5;
  30050. var num6 = gradient - num7;
  30051. var num2 = num7 - num8;
  30052. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  30053. };
  30054. return BounceEase;
  30055. }(EasingFunction));
  30056. BABYLON.BounceEase = BounceEase;
  30057. var CubicEase = (function (_super) {
  30058. __extends(CubicEase, _super);
  30059. function CubicEase() {
  30060. return _super.apply(this, arguments) || this;
  30061. }
  30062. CubicEase.prototype.easeInCore = function (gradient) {
  30063. return (gradient * gradient * gradient);
  30064. };
  30065. return CubicEase;
  30066. }(EasingFunction));
  30067. BABYLON.CubicEase = CubicEase;
  30068. var ElasticEase = (function (_super) {
  30069. __extends(ElasticEase, _super);
  30070. function ElasticEase(oscillations, springiness) {
  30071. if (oscillations === void 0) { oscillations = 3; }
  30072. if (springiness === void 0) { springiness = 3; }
  30073. var _this = _super.call(this) || this;
  30074. _this.oscillations = oscillations;
  30075. _this.springiness = springiness;
  30076. return _this;
  30077. }
  30078. ElasticEase.prototype.easeInCore = function (gradient) {
  30079. var num2;
  30080. var num3 = Math.max(0.0, this.oscillations);
  30081. var num = Math.max(0.0, this.springiness);
  30082. if (num == 0) {
  30083. num2 = gradient;
  30084. }
  30085. else {
  30086. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  30087. }
  30088. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  30089. };
  30090. return ElasticEase;
  30091. }(EasingFunction));
  30092. BABYLON.ElasticEase = ElasticEase;
  30093. var ExponentialEase = (function (_super) {
  30094. __extends(ExponentialEase, _super);
  30095. function ExponentialEase(exponent) {
  30096. if (exponent === void 0) { exponent = 2; }
  30097. var _this = _super.call(this) || this;
  30098. _this.exponent = exponent;
  30099. return _this;
  30100. }
  30101. ExponentialEase.prototype.easeInCore = function (gradient) {
  30102. if (this.exponent <= 0) {
  30103. return gradient;
  30104. }
  30105. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  30106. };
  30107. return ExponentialEase;
  30108. }(EasingFunction));
  30109. BABYLON.ExponentialEase = ExponentialEase;
  30110. var PowerEase = (function (_super) {
  30111. __extends(PowerEase, _super);
  30112. function PowerEase(power) {
  30113. if (power === void 0) { power = 2; }
  30114. var _this = _super.call(this) || this;
  30115. _this.power = power;
  30116. return _this;
  30117. }
  30118. PowerEase.prototype.easeInCore = function (gradient) {
  30119. var y = Math.max(0.0, this.power);
  30120. return Math.pow(gradient, y);
  30121. };
  30122. return PowerEase;
  30123. }(EasingFunction));
  30124. BABYLON.PowerEase = PowerEase;
  30125. var QuadraticEase = (function (_super) {
  30126. __extends(QuadraticEase, _super);
  30127. function QuadraticEase() {
  30128. return _super.apply(this, arguments) || this;
  30129. }
  30130. QuadraticEase.prototype.easeInCore = function (gradient) {
  30131. return (gradient * gradient);
  30132. };
  30133. return QuadraticEase;
  30134. }(EasingFunction));
  30135. BABYLON.QuadraticEase = QuadraticEase;
  30136. var QuarticEase = (function (_super) {
  30137. __extends(QuarticEase, _super);
  30138. function QuarticEase() {
  30139. return _super.apply(this, arguments) || this;
  30140. }
  30141. QuarticEase.prototype.easeInCore = function (gradient) {
  30142. return (gradient * gradient * gradient * gradient);
  30143. };
  30144. return QuarticEase;
  30145. }(EasingFunction));
  30146. BABYLON.QuarticEase = QuarticEase;
  30147. var QuinticEase = (function (_super) {
  30148. __extends(QuinticEase, _super);
  30149. function QuinticEase() {
  30150. return _super.apply(this, arguments) || this;
  30151. }
  30152. QuinticEase.prototype.easeInCore = function (gradient) {
  30153. return (gradient * gradient * gradient * gradient * gradient);
  30154. };
  30155. return QuinticEase;
  30156. }(EasingFunction));
  30157. BABYLON.QuinticEase = QuinticEase;
  30158. var SineEase = (function (_super) {
  30159. __extends(SineEase, _super);
  30160. function SineEase() {
  30161. return _super.apply(this, arguments) || this;
  30162. }
  30163. SineEase.prototype.easeInCore = function (gradient) {
  30164. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  30165. };
  30166. return SineEase;
  30167. }(EasingFunction));
  30168. BABYLON.SineEase = SineEase;
  30169. var BezierCurveEase = (function (_super) {
  30170. __extends(BezierCurveEase, _super);
  30171. function BezierCurveEase(x1, y1, x2, y2) {
  30172. if (x1 === void 0) { x1 = 0; }
  30173. if (y1 === void 0) { y1 = 0; }
  30174. if (x2 === void 0) { x2 = 1; }
  30175. if (y2 === void 0) { y2 = 1; }
  30176. var _this = _super.call(this) || this;
  30177. _this.x1 = x1;
  30178. _this.y1 = y1;
  30179. _this.x2 = x2;
  30180. _this.y2 = y2;
  30181. return _this;
  30182. }
  30183. BezierCurveEase.prototype.easeInCore = function (gradient) {
  30184. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  30185. };
  30186. return BezierCurveEase;
  30187. }(EasingFunction));
  30188. BABYLON.BezierCurveEase = BezierCurveEase;
  30189. })(BABYLON || (BABYLON = {}));
  30190. //# sourceMappingURL=babylon.easing.js.map
  30191. var BABYLON;
  30192. (function (BABYLON) {
  30193. var Bone = (function (_super) {
  30194. __extends(Bone, _super);
  30195. function Bone(name, skeleton, parentBone, matrix, restPose) {
  30196. var _this = _super.call(this, name, skeleton.getScene()) || this;
  30197. _this.name = name;
  30198. _this.children = new Array();
  30199. _this.animations = new Array();
  30200. _this._worldTransform = new BABYLON.Matrix();
  30201. _this._absoluteTransform = new BABYLON.Matrix();
  30202. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  30203. _this._scaleMatrix = BABYLON.Matrix.Identity();
  30204. _this._scaleVector = new BABYLON.Vector3(1, 1, 1);
  30205. _this._negateScaleChildren = new BABYLON.Vector3(1, 1, 1);
  30206. _this._scalingDeterminant = 1;
  30207. _this._syncScaleVector = function () {
  30208. var lm = this.getLocalMatrix();
  30209. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  30210. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  30211. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  30212. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  30213. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  30214. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  30215. this._scaleVector.x = xs * Math.sqrt(xsq);
  30216. this._scaleVector.y = ys * Math.sqrt(ysq);
  30217. this._scaleVector.z = zs * Math.sqrt(zsq);
  30218. if (this._parent) {
  30219. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  30220. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  30221. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  30222. }
  30223. BABYLON.Matrix.FromValuesToRef(this._scaleVector.x, 0, 0, 0, 0, this._scaleVector.y, 0, 0, 0, 0, this._scaleVector.z, 0, 0, 0, 0, 1, this._scaleMatrix);
  30224. };
  30225. _this._skeleton = skeleton;
  30226. _this._matrix = matrix;
  30227. _this._baseMatrix = matrix;
  30228. _this._restPose = restPose ? restPose : matrix.clone();
  30229. skeleton.bones.push(_this);
  30230. if (parentBone) {
  30231. _this._parent = parentBone;
  30232. parentBone.children.push(_this);
  30233. }
  30234. else {
  30235. _this._parent = null;
  30236. }
  30237. _this._updateDifferenceMatrix();
  30238. if (_this.getAbsoluteTransform().determinant() < 0) {
  30239. _this._scalingDeterminant *= -1;
  30240. }
  30241. return _this;
  30242. }
  30243. // Members
  30244. Bone.prototype.getParent = function () {
  30245. return this._parent;
  30246. };
  30247. Bone.prototype.getLocalMatrix = function () {
  30248. return this._matrix;
  30249. };
  30250. Bone.prototype.getBaseMatrix = function () {
  30251. return this._baseMatrix;
  30252. };
  30253. Bone.prototype.getRestPose = function () {
  30254. return this._restPose;
  30255. };
  30256. Bone.prototype.returnToRest = function () {
  30257. this.updateMatrix(this._restPose.clone());
  30258. };
  30259. Bone.prototype.getWorldMatrix = function () {
  30260. return this._worldTransform;
  30261. };
  30262. Bone.prototype.getInvertedAbsoluteTransform = function () {
  30263. return this._invertedAbsoluteTransform;
  30264. };
  30265. Bone.prototype.getAbsoluteTransform = function () {
  30266. return this._absoluteTransform;
  30267. };
  30268. // Methods
  30269. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  30270. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  30271. this._baseMatrix = matrix.clone();
  30272. this._matrix = matrix.clone();
  30273. this._skeleton._markAsDirty();
  30274. if (updateDifferenceMatrix) {
  30275. this._updateDifferenceMatrix();
  30276. }
  30277. };
  30278. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  30279. if (!rootMatrix) {
  30280. rootMatrix = this._baseMatrix;
  30281. }
  30282. if (this._parent) {
  30283. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30284. }
  30285. else {
  30286. this._absoluteTransform.copyFrom(rootMatrix);
  30287. }
  30288. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  30289. for (var index = 0; index < this.children.length; index++) {
  30290. this.children[index]._updateDifferenceMatrix();
  30291. }
  30292. };
  30293. Bone.prototype.markAsDirty = function () {
  30294. this._currentRenderId++;
  30295. this._skeleton._markAsDirty();
  30296. };
  30297. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  30298. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  30299. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  30300. // all animation may be coming from a library skeleton, so may need to create animation
  30301. if (this.animations.length === 0) {
  30302. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  30303. this.animations[0].setKeys([]);
  30304. }
  30305. // get animation info / verify there is such a range from the source bone
  30306. var sourceRange = source.animations[0].getRange(rangeName);
  30307. if (!sourceRange) {
  30308. return false;
  30309. }
  30310. var from = sourceRange.from;
  30311. var to = sourceRange.to;
  30312. var sourceKeys = source.animations[0].getKeys();
  30313. // rescaling prep
  30314. var sourceBoneLength = source.length;
  30315. var sourceParent = source.getParent();
  30316. var parent = this.getParent();
  30317. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  30318. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  30319. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  30320. var destKeys = this.animations[0].getKeys();
  30321. // loop vars declaration
  30322. var orig;
  30323. var origTranslation;
  30324. var mat;
  30325. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  30326. orig = sourceKeys[key];
  30327. if (orig.frame >= from && orig.frame <= to) {
  30328. if (rescaleAsRequired) {
  30329. mat = orig.value.clone();
  30330. // scale based on parent ratio, when bone has parent
  30331. if (parentScalingReqd) {
  30332. origTranslation = mat.getTranslation();
  30333. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  30334. }
  30335. else if (dimensionsScalingReqd) {
  30336. origTranslation = mat.getTranslation();
  30337. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  30338. }
  30339. else {
  30340. mat = orig.value;
  30341. }
  30342. }
  30343. else {
  30344. mat = orig.value;
  30345. }
  30346. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  30347. }
  30348. }
  30349. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  30350. return true;
  30351. };
  30352. Bone.prototype.translate = function (vec, space, mesh) {
  30353. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30354. var lm = this.getLocalMatrix();
  30355. if (space == BABYLON.Space.LOCAL) {
  30356. lm.m[12] += vec.x;
  30357. lm.m[13] += vec.y;
  30358. lm.m[14] += vec.z;
  30359. }
  30360. else {
  30361. this._skeleton.computeAbsoluteTransforms();
  30362. var tmat = BABYLON.Tmp.Matrix[0];
  30363. var tvec = BABYLON.Tmp.Vector3[0];
  30364. if (mesh) {
  30365. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30366. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30367. }
  30368. else {
  30369. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30370. }
  30371. tmat.m[12] = 0;
  30372. tmat.m[13] = 0;
  30373. tmat.m[14] = 0;
  30374. tmat.invert();
  30375. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  30376. lm.m[12] += tvec.x;
  30377. lm.m[13] += tvec.y;
  30378. lm.m[14] += tvec.z;
  30379. }
  30380. this.markAsDirty();
  30381. };
  30382. Bone.prototype.setPosition = function (position, space, mesh) {
  30383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30384. var lm = this.getLocalMatrix();
  30385. if (space == BABYLON.Space.LOCAL) {
  30386. lm.m[12] = position.x;
  30387. lm.m[13] = position.y;
  30388. lm.m[14] = position.z;
  30389. }
  30390. else {
  30391. this._skeleton.computeAbsoluteTransforms();
  30392. var tmat = BABYLON.Tmp.Matrix[0];
  30393. var vec = BABYLON.Tmp.Vector3[0];
  30394. if (mesh) {
  30395. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30396. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30397. }
  30398. else {
  30399. tmat.copyFrom(this._parent.getAbsoluteTransform());
  30400. }
  30401. tmat.invert();
  30402. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  30403. lm.m[12] = vec.x;
  30404. lm.m[13] = vec.y;
  30405. lm.m[14] = vec.z;
  30406. }
  30407. this.markAsDirty();
  30408. };
  30409. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  30410. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  30411. };
  30412. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  30413. if (scaleChildren === void 0) { scaleChildren = false; }
  30414. if (this.animations[0] && !this.animations[0].isStopped()) {
  30415. if (!scaleChildren) {
  30416. this._negateScaleChildren.x = 1 / x;
  30417. this._negateScaleChildren.y = 1 / y;
  30418. this._negateScaleChildren.z = 1 / z;
  30419. }
  30420. this._syncScaleVector();
  30421. }
  30422. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  30423. };
  30424. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  30425. if (scaleChildren === void 0) { scaleChildren = false; }
  30426. var locMat = this.getLocalMatrix();
  30427. var origLocMat = BABYLON.Tmp.Matrix[0];
  30428. origLocMat.copyFrom(locMat);
  30429. var origLocMatInv = BABYLON.Tmp.Matrix[1];
  30430. origLocMatInv.copyFrom(origLocMat);
  30431. origLocMatInv.invert();
  30432. var scaleMat = BABYLON.Tmp.Matrix[2];
  30433. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  30434. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  30435. this._scaleVector.x *= x;
  30436. this._scaleVector.y *= y;
  30437. this._scaleVector.z *= z;
  30438. locMat.multiplyToRef(origLocMatInv, locMat);
  30439. locMat.multiplyToRef(scaleMat, locMat);
  30440. locMat.multiplyToRef(origLocMat, locMat);
  30441. var parent = this.getParent();
  30442. if (parent) {
  30443. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  30444. }
  30445. else {
  30446. this.getAbsoluteTransform().copyFrom(locMat);
  30447. }
  30448. var len = this.children.length;
  30449. scaleMat.invert();
  30450. for (var i = 0; i < len; i++) {
  30451. var child = this.children[i];
  30452. var cm = child.getLocalMatrix();
  30453. cm.multiplyToRef(scaleMat, cm);
  30454. var lm = child.getLocalMatrix();
  30455. lm.m[12] *= x;
  30456. lm.m[13] *= y;
  30457. lm.m[14] *= z;
  30458. }
  30459. this.computeAbsoluteTransforms();
  30460. if (scaleChildren) {
  30461. for (var i = 0; i < len; i++) {
  30462. this.children[i].scale(x, y, z, scaleChildren);
  30463. }
  30464. }
  30465. this.markAsDirty();
  30466. };
  30467. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  30468. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30469. var rotMat = BABYLON.Tmp.Matrix[0];
  30470. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  30471. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30472. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30473. rotMatInv.multiplyToRef(rotMat, rotMat);
  30474. this._rotateWithMatrix(rotMat, space, mesh);
  30475. };
  30476. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  30477. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30478. var rmat = BABYLON.Tmp.Matrix[0];
  30479. rmat.m[12] = 0;
  30480. rmat.m[13] = 0;
  30481. rmat.m[14] = 0;
  30482. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  30483. this._rotateWithMatrix(rmat, space, mesh);
  30484. };
  30485. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  30486. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30487. var rotMat = BABYLON.Tmp.Matrix[0];
  30488. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  30489. var rotMatInv = BABYLON.Tmp.Matrix[1];
  30490. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30491. rotMatInv.multiplyToRef(rotMat, rotMat);
  30492. this._rotateWithMatrix(rotMat, space, mesh);
  30493. };
  30494. Bone.prototype.setRotation = function (rotation, space, mesh) {
  30495. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30496. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  30497. };
  30498. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  30499. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30500. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30501. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30502. var rotMat = BABYLON.Tmp.Matrix[1];
  30503. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  30504. rotMatInv.multiplyToRef(rotMat, rotMat);
  30505. this._rotateWithMatrix(rotMat, space, mesh);
  30506. };
  30507. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  30508. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30509. var rotMatInv = BABYLON.Tmp.Matrix[0];
  30510. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  30511. var rotMat2 = BABYLON.Tmp.Matrix[1];
  30512. rotMat2.copyFrom(rotMat);
  30513. rotMatInv.multiplyToRef(rotMat, rotMat2);
  30514. this._rotateWithMatrix(rotMat2, space, mesh);
  30515. };
  30516. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  30517. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30518. var lmat = this.getLocalMatrix();
  30519. var lx = lmat.m[12];
  30520. var ly = lmat.m[13];
  30521. var lz = lmat.m[14];
  30522. var parent = this.getParent();
  30523. var parentScale = BABYLON.Tmp.Matrix[3];
  30524. var parentScaleInv = BABYLON.Tmp.Matrix[4];
  30525. if (parent) {
  30526. if (space == BABYLON.Space.WORLD) {
  30527. if (mesh) {
  30528. parentScale.copyFrom(mesh.getWorldMatrix());
  30529. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  30530. }
  30531. else {
  30532. parentScale.copyFrom(parent.getAbsoluteTransform());
  30533. }
  30534. }
  30535. else {
  30536. parentScale = parent._scaleMatrix;
  30537. }
  30538. parentScaleInv.copyFrom(parentScale);
  30539. parentScaleInv.invert();
  30540. lmat.multiplyToRef(parentScale, lmat);
  30541. lmat.multiplyToRef(rmat, lmat);
  30542. lmat.multiplyToRef(parentScaleInv, lmat);
  30543. }
  30544. else {
  30545. if (space == BABYLON.Space.WORLD && mesh) {
  30546. parentScale.copyFrom(mesh.getWorldMatrix());
  30547. parentScaleInv.copyFrom(parentScale);
  30548. parentScaleInv.invert();
  30549. lmat.multiplyToRef(parentScale, lmat);
  30550. lmat.multiplyToRef(rmat, lmat);
  30551. lmat.multiplyToRef(parentScaleInv, lmat);
  30552. }
  30553. else {
  30554. lmat.multiplyToRef(rmat, lmat);
  30555. }
  30556. }
  30557. lmat.m[12] = lx;
  30558. lmat.m[13] = ly;
  30559. lmat.m[14] = lz;
  30560. this.computeAbsoluteTransforms();
  30561. this.markAsDirty();
  30562. };
  30563. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  30564. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30565. if (space == BABYLON.Space.WORLD) {
  30566. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30567. scaleMatrix.copyFrom(this._scaleMatrix);
  30568. rotMatInv.copyFrom(this.getAbsoluteTransform());
  30569. if (mesh) {
  30570. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  30571. var meshScale = BABYLON.Tmp.Matrix[3];
  30572. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  30573. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  30574. }
  30575. rotMatInv.invert();
  30576. scaleMatrix.m[0] *= this._scalingDeterminant;
  30577. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30578. }
  30579. else {
  30580. rotMatInv.copyFrom(this.getLocalMatrix());
  30581. rotMatInv.invert();
  30582. var scaleMatrix = BABYLON.Tmp.Matrix[2];
  30583. scaleMatrix.copyFrom(this._scaleMatrix);
  30584. if (this._parent) {
  30585. var pscaleMatrix = BABYLON.Tmp.Matrix[3];
  30586. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  30587. pscaleMatrix.invert();
  30588. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  30589. }
  30590. else {
  30591. scaleMatrix.m[0] *= this._scalingDeterminant;
  30592. }
  30593. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  30594. }
  30595. };
  30596. Bone.prototype.getScale = function () {
  30597. return this._scaleVector.clone();
  30598. };
  30599. Bone.prototype.getScaleToRef = function (result) {
  30600. result.copyFrom(this._scaleVector);
  30601. };
  30602. Bone.prototype.getPosition = function (space, mesh) {
  30603. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30604. var pos = BABYLON.Vector3.Zero();
  30605. this.getPositionToRef(space, mesh, pos);
  30606. return pos;
  30607. };
  30608. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  30609. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30610. if (space == BABYLON.Space.LOCAL) {
  30611. var lm = this.getLocalMatrix();
  30612. result.x = lm.m[12];
  30613. result.y = lm.m[13];
  30614. result.z = lm.m[14];
  30615. }
  30616. else {
  30617. this._skeleton.computeAbsoluteTransforms();
  30618. var tmat = BABYLON.Tmp.Matrix[0];
  30619. if (mesh) {
  30620. tmat.copyFrom(this.getAbsoluteTransform());
  30621. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30622. }
  30623. else {
  30624. tmat = this.getAbsoluteTransform();
  30625. }
  30626. result.x = tmat.m[12];
  30627. result.y = tmat.m[13];
  30628. result.z = tmat.m[14];
  30629. }
  30630. };
  30631. Bone.prototype.getAbsolutePosition = function (mesh) {
  30632. var pos = BABYLON.Vector3.Zero();
  30633. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  30634. return pos;
  30635. };
  30636. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  30637. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  30638. };
  30639. Bone.prototype.computeAbsoluteTransforms = function () {
  30640. if (this._parent) {
  30641. this._matrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  30642. }
  30643. else {
  30644. this._absoluteTransform.copyFrom(this._matrix);
  30645. var poseMatrix = this._skeleton.getPoseMatrix();
  30646. if (poseMatrix) {
  30647. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  30648. }
  30649. }
  30650. var children = this.children;
  30651. var len = children.length;
  30652. for (var i = 0; i < len; i++) {
  30653. children[i].computeAbsoluteTransforms();
  30654. }
  30655. };
  30656. Bone.prototype.getDirection = function (localAxis, mesh) {
  30657. var result = BABYLON.Vector3.Zero();
  30658. this.getDirectionToRef(localAxis, mesh, result);
  30659. return result;
  30660. };
  30661. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  30662. this._skeleton.computeAbsoluteTransforms();
  30663. var mat = BABYLON.Tmp.Matrix[0];
  30664. mat.copyFrom(this.getAbsoluteTransform());
  30665. if (mesh) {
  30666. mat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30667. }
  30668. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  30669. result.normalize();
  30670. };
  30671. Bone.prototype.getRotation = function (space, mesh) {
  30672. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30673. var result = BABYLON.Vector3.Zero();
  30674. this.getRotationToRef(space, mesh, result);
  30675. return result;
  30676. };
  30677. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  30678. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30679. var quat = BABYLON.Tmp.Quaternion[0];
  30680. this.getRotationQuaternionToRef(space, mesh, quat);
  30681. quat.toEulerAnglesToRef(result);
  30682. };
  30683. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  30684. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30685. var result = BABYLON.Quaternion.Identity();
  30686. this.getRotationQuaternionToRef(space, mesh, result);
  30687. return result;
  30688. };
  30689. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  30690. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30691. if (space == BABYLON.Space.LOCAL) {
  30692. this.getLocalMatrix().decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30693. }
  30694. else {
  30695. var mat = BABYLON.Tmp.Matrix[0];
  30696. var amat = this.getAbsoluteTransform();
  30697. if (mesh) {
  30698. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30699. }
  30700. else {
  30701. mat.copyFrom(amat);
  30702. }
  30703. mat.m[0] *= this._scalingDeterminant;
  30704. mat.m[1] *= this._scalingDeterminant;
  30705. mat.m[2] *= this._scalingDeterminant;
  30706. mat.decompose(BABYLON.Tmp.Vector3[0], result, BABYLON.Tmp.Vector3[1]);
  30707. }
  30708. };
  30709. Bone.prototype.getRotationMatrix = function (space, mesh) {
  30710. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30711. var result = BABYLON.Matrix.Identity();
  30712. this.getRotationMatrixToRef(space, mesh, result);
  30713. return result;
  30714. };
  30715. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  30716. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  30717. if (space == BABYLON.Space.LOCAL) {
  30718. this.getLocalMatrix().getRotationMatrixToRef(result);
  30719. }
  30720. else {
  30721. var mat = BABYLON.Tmp.Matrix[0];
  30722. var amat = this.getAbsoluteTransform();
  30723. if (mesh) {
  30724. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  30725. }
  30726. else {
  30727. mat.copyFrom(amat);
  30728. }
  30729. mat.m[0] *= this._scalingDeterminant;
  30730. mat.m[1] *= this._scalingDeterminant;
  30731. mat.m[2] *= this._scalingDeterminant;
  30732. mat.getRotationMatrixToRef(result);
  30733. }
  30734. };
  30735. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  30736. var result = BABYLON.Vector3.Zero();
  30737. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  30738. return result;
  30739. };
  30740. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  30741. this._skeleton.computeAbsoluteTransforms();
  30742. var tmat = BABYLON.Tmp.Matrix[0];
  30743. if (mesh) {
  30744. tmat.copyFrom(this.getAbsoluteTransform());
  30745. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30746. }
  30747. else {
  30748. tmat = this.getAbsoluteTransform();
  30749. }
  30750. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30751. };
  30752. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  30753. var result = BABYLON.Vector3.Zero();
  30754. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  30755. return result;
  30756. };
  30757. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  30758. this._skeleton.computeAbsoluteTransforms();
  30759. var tmat = BABYLON.Tmp.Matrix[0];
  30760. tmat.copyFrom(this.getAbsoluteTransform());
  30761. if (mesh) {
  30762. tmat.multiplyToRef(mesh.getWorldMatrix(), tmat);
  30763. }
  30764. tmat.invert();
  30765. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  30766. };
  30767. return Bone;
  30768. }(BABYLON.Node));
  30769. BABYLON.Bone = Bone;
  30770. })(BABYLON || (BABYLON = {}));
  30771. //# sourceMappingURL=babylon.bone.js.map
  30772. var BABYLON;
  30773. (function (BABYLON) {
  30774. var BoneIKController = (function () {
  30775. function BoneIKController(mesh, bone, options) {
  30776. this.targetPosition = BABYLON.Vector3.Zero();
  30777. this.poleTargetPosition = BABYLON.Vector3.Zero();
  30778. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  30779. this.poleAngle = 0;
  30780. this.slerpAmount = 1;
  30781. this._bone1Quat = BABYLON.Quaternion.Identity();
  30782. this._bone1Mat = BABYLON.Matrix.Identity();
  30783. this._bone2Ang = Math.PI;
  30784. this._maxAngle = Math.PI;
  30785. this._tmpVec1 = BABYLON.Vector3.Zero();
  30786. this._tmpVec2 = BABYLON.Vector3.Zero();
  30787. this._tmpVec3 = BABYLON.Vector3.Zero();
  30788. this._tmpVec4 = BABYLON.Vector3.Zero();
  30789. this._tmpVec5 = BABYLON.Vector3.Zero();
  30790. this._tmpMat1 = BABYLON.Matrix.Identity();
  30791. this._tmpMat2 = BABYLON.Matrix.Identity();
  30792. this._tmpQuat1 = BABYLON.Quaternion.Identity();
  30793. this._rightHandedSystem = false;
  30794. this._bendAxis = BABYLON.Vector3.Right();
  30795. this._slerping = false;
  30796. this._bone2 = bone;
  30797. this._bone1 = bone.getParent();
  30798. this.mesh = mesh;
  30799. if (bone.getAbsoluteTransform().determinant() > 0) {
  30800. this._rightHandedSystem = true;
  30801. this._bendAxis.x = 0;
  30802. this._bendAxis.y = 0;
  30803. this._bendAxis.z = 1;
  30804. }
  30805. if (this._bone1.length) {
  30806. var boneScale1 = this._bone1.getScale();
  30807. var boneScale2 = this._bone2.getScale();
  30808. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  30809. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  30810. }
  30811. else if (this._bone1.children[0]) {
  30812. mesh.computeWorldMatrix(true);
  30813. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  30814. var pos2 = this._bone2.getAbsolutePosition(mesh);
  30815. var pos3 = this._bone1.getAbsolutePosition(mesh);
  30816. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  30817. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  30818. }
  30819. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  30820. this.maxAngle = Math.PI;
  30821. if (options) {
  30822. if (options.targetMesh) {
  30823. this.targetMesh = options.targetMesh;
  30824. this.targetMesh.computeWorldMatrix(true);
  30825. }
  30826. if (options.poleTargetMesh) {
  30827. this.poleTargetMesh = options.poleTargetMesh;
  30828. this.poleTargetMesh.computeWorldMatrix(true);
  30829. }
  30830. else if (options.poleTargetBone) {
  30831. this.poleTargetBone = options.poleTargetBone;
  30832. }
  30833. else if (this._bone1.getParent()) {
  30834. this.poleTargetBone = this._bone1.getParent();
  30835. }
  30836. if (options.poleTargetLocalOffset) {
  30837. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  30838. }
  30839. if (options.poleAngle) {
  30840. this.poleAngle = options.poleAngle;
  30841. }
  30842. if (options.bendAxis) {
  30843. this._bendAxis.copyFrom(options.bendAxis);
  30844. }
  30845. if (options.maxAngle) {
  30846. this.maxAngle = options.maxAngle;
  30847. }
  30848. if (options.slerpAmount) {
  30849. this.slerpAmount = options.slerpAmount;
  30850. }
  30851. }
  30852. }
  30853. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  30854. get: function () {
  30855. return this._maxAngle;
  30856. },
  30857. set: function (value) {
  30858. this._setMaxAngle(value);
  30859. },
  30860. enumerable: true,
  30861. configurable: true
  30862. });
  30863. BoneIKController.prototype._setMaxAngle = function (ang) {
  30864. if (ang < 0) {
  30865. ang = 0;
  30866. }
  30867. if (ang > Math.PI || ang == undefined) {
  30868. ang = Math.PI;
  30869. }
  30870. this._maxAngle = ang;
  30871. var a = this._bone1Length;
  30872. var b = this._bone2Length;
  30873. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  30874. };
  30875. BoneIKController.prototype.update = function () {
  30876. var bone1 = this._bone1;
  30877. var target = this.targetPosition;
  30878. var poleTarget = this.poleTargetPosition;
  30879. var mat1 = this._tmpMat1;
  30880. var mat2 = this._tmpMat2;
  30881. if (this.targetMesh) {
  30882. target.copyFrom(this.targetMesh.getAbsolutePosition());
  30883. }
  30884. if (this.poleTargetBone) {
  30885. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  30886. }
  30887. else if (this.poleTargetMesh) {
  30888. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  30889. }
  30890. var bonePos = this._tmpVec1;
  30891. var zaxis = this._tmpVec2;
  30892. var xaxis = this._tmpVec3;
  30893. var yaxis = this._tmpVec4;
  30894. var upAxis = this._tmpVec5;
  30895. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  30896. poleTarget.subtractToRef(bonePos, upAxis);
  30897. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  30898. upAxis.y = 1;
  30899. }
  30900. else {
  30901. upAxis.normalize();
  30902. }
  30903. target.subtractToRef(bonePos, yaxis);
  30904. yaxis.normalize();
  30905. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  30906. zaxis.normalize();
  30907. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  30908. xaxis.normalize();
  30909. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  30910. var a = this._bone1Length;
  30911. var b = this._bone2Length;
  30912. var c = BABYLON.Vector3.Distance(bonePos, target);
  30913. if (this._maxReach > 0) {
  30914. c = Math.min(this._maxReach, c);
  30915. }
  30916. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  30917. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  30918. if (acosa > 1) {
  30919. acosa = 1;
  30920. }
  30921. if (acosb > 1) {
  30922. acosb = 1;
  30923. }
  30924. if (acosa < -1) {
  30925. acosa = -1;
  30926. }
  30927. if (acosb < -1) {
  30928. acosb = -1;
  30929. }
  30930. var angA = Math.acos(acosa);
  30931. var angB = Math.acos(acosb);
  30932. var angC = -angA - angB;
  30933. if (this._rightHandedSystem) {
  30934. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, Math.PI * .5, mat2);
  30935. mat2.multiplyToRef(mat1, mat1);
  30936. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  30937. mat2.multiplyToRef(mat1, mat1);
  30938. }
  30939. else {
  30940. this._tmpVec1.copyFrom(this._bendAxis);
  30941. this._tmpVec1.x *= -1;
  30942. BABYLON.Matrix.RotationAxisToRef(this._tmpVec1, -angB, mat2);
  30943. mat2.multiplyToRef(mat1, mat1);
  30944. }
  30945. if (this.poleAngle) {
  30946. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  30947. mat1.multiplyToRef(mat2, mat1);
  30948. }
  30949. if (this.slerpAmount < 1) {
  30950. if (!this._slerping) {
  30951. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  30952. }
  30953. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, this._tmpQuat1);
  30954. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, this._tmpQuat1, this.slerpAmount, this._bone1Quat);
  30955. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  30956. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  30957. this._slerping = true;
  30958. }
  30959. else {
  30960. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  30961. this._bone1Mat.copyFrom(mat1);
  30962. this._slerping = false;
  30963. }
  30964. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  30965. this._bone2Ang = angC;
  30966. };
  30967. return BoneIKController;
  30968. }());
  30969. BABYLON.BoneIKController = BoneIKController;
  30970. })(BABYLON || (BABYLON = {}));
  30971. //# sourceMappingURL=babylon.boneIKController.js.map
  30972. var BABYLON;
  30973. (function (BABYLON) {
  30974. var BoneLookController = (function () {
  30975. function BoneLookController(mesh, bone, target, options) {
  30976. this.upAxis = BABYLON.Vector3.Up();
  30977. this.adjustYaw = 0;
  30978. this.adjustPitch = 0;
  30979. this.adjustRoll = 0;
  30980. this._tmpVec1 = BABYLON.Vector3.Zero();
  30981. this._tmpVec2 = BABYLON.Vector3.Zero();
  30982. this._tmpVec3 = BABYLON.Vector3.Zero();
  30983. this._tmpVec4 = BABYLON.Vector3.Zero();
  30984. this._tmpMat1 = BABYLON.Matrix.Identity();
  30985. this._tmpMat2 = BABYLON.Matrix.Identity();
  30986. this.mesh = mesh;
  30987. this.bone = bone;
  30988. this.target = target;
  30989. if (options) {
  30990. if (options.adjustYaw) {
  30991. this.adjustYaw = options.adjustYaw;
  30992. }
  30993. if (options.adjustPitch) {
  30994. this.adjustPitch = options.adjustPitch;
  30995. }
  30996. if (options.adjustRoll) {
  30997. this.adjustRoll = options.adjustRoll;
  30998. }
  30999. }
  31000. }
  31001. BoneLookController.prototype.update = function () {
  31002. var bone = this.bone;
  31003. var target = this.target;
  31004. var bonePos = this._tmpVec1;
  31005. var zaxis = this._tmpVec2;
  31006. var xaxis = this._tmpVec3;
  31007. var yaxis = this._tmpVec4;
  31008. var mat1 = this._tmpMat1;
  31009. var mat2 = this._tmpMat2;
  31010. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  31011. target.subtractToRef(bonePos, zaxis);
  31012. zaxis.normalize();
  31013. BABYLON.Vector3.CrossToRef(this.upAxis, zaxis, xaxis);
  31014. xaxis.normalize();
  31015. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  31016. yaxis.normalize();
  31017. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  31018. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  31019. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, mat2);
  31020. mat2.multiplyToRef(mat1, mat1);
  31021. }
  31022. this.bone.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  31023. };
  31024. return BoneLookController;
  31025. }());
  31026. BABYLON.BoneLookController = BoneLookController;
  31027. })(BABYLON || (BABYLON = {}));
  31028. //# sourceMappingURL=babylon.boneLookController.js.map
  31029. var BABYLON;
  31030. (function (BABYLON) {
  31031. var Skeleton = (function () {
  31032. function Skeleton(name, id, scene) {
  31033. this.name = name;
  31034. this.id = id;
  31035. this.bones = new Array();
  31036. this.needInitialSkinMatrix = false;
  31037. this._isDirty = true;
  31038. this._meshesWithPoseMatrix = new Array();
  31039. this._identity = BABYLON.Matrix.Identity();
  31040. this._ranges = {};
  31041. this._lastAbsoluteTransformsUpdateId = -1;
  31042. this.bones = [];
  31043. this._scene = scene;
  31044. scene.skeletons.push(this);
  31045. //make sure it will recalculate the matrix next time prepare is called.
  31046. this._isDirty = true;
  31047. }
  31048. // Members
  31049. Skeleton.prototype.getTransformMatrices = function (mesh) {
  31050. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  31051. return mesh._bonesTransformMatrices;
  31052. }
  31053. if (!this._transformMatrices) {
  31054. this.prepare();
  31055. }
  31056. return this._transformMatrices;
  31057. };
  31058. Skeleton.prototype.getScene = function () {
  31059. return this._scene;
  31060. };
  31061. // Methods
  31062. /**
  31063. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31064. */
  31065. Skeleton.prototype.toString = function (fullDetails) {
  31066. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  31067. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  31068. if (fullDetails) {
  31069. ret += ", Ranges: {";
  31070. var first = true;
  31071. for (var name_1 in this._ranges) {
  31072. if (first) {
  31073. ret += ", ";
  31074. first = false;
  31075. }
  31076. ret += name_1;
  31077. }
  31078. ret += "}";
  31079. }
  31080. return ret;
  31081. };
  31082. /**
  31083. * Get bone's index searching by name
  31084. * @param {string} name is bone's name to search for
  31085. * @return {number} Indice of the bone. Returns -1 if not found
  31086. */
  31087. Skeleton.prototype.getBoneIndexByName = function (name) {
  31088. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  31089. if (this.bones[boneIndex].name === name) {
  31090. return boneIndex;
  31091. }
  31092. }
  31093. return -1;
  31094. };
  31095. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  31096. // check name not already in use
  31097. if (!this._ranges[name]) {
  31098. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  31099. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31100. if (this.bones[i].animations[0]) {
  31101. this.bones[i].animations[0].createRange(name, from, to);
  31102. }
  31103. }
  31104. }
  31105. };
  31106. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  31107. if (deleteFrames === void 0) { deleteFrames = true; }
  31108. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31109. if (this.bones[i].animations[0]) {
  31110. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  31111. }
  31112. }
  31113. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  31114. };
  31115. Skeleton.prototype.getAnimationRange = function (name) {
  31116. return this._ranges[name];
  31117. };
  31118. /**
  31119. * Returns as an Array, all AnimationRanges defined on this skeleton
  31120. */
  31121. Skeleton.prototype.getAnimationRanges = function () {
  31122. var animationRanges = [];
  31123. var name;
  31124. var i = 0;
  31125. for (name in this._ranges) {
  31126. animationRanges[i] = this._ranges[name];
  31127. i++;
  31128. }
  31129. return animationRanges;
  31130. };
  31131. /**
  31132. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  31133. */
  31134. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  31135. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  31136. if (this._ranges[name] || !source.getAnimationRange(name)) {
  31137. return false;
  31138. }
  31139. var ret = true;
  31140. var frameOffset = this._getHighestAnimationFrame() + 1;
  31141. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  31142. var boneDict = {};
  31143. var sourceBones = source.bones;
  31144. var nBones;
  31145. var i;
  31146. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  31147. boneDict[sourceBones[i].name] = sourceBones[i];
  31148. }
  31149. if (this.bones.length !== sourceBones.length) {
  31150. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  31151. ret = false;
  31152. }
  31153. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  31154. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  31155. var boneName = this.bones[i].name;
  31156. var sourceBone = boneDict[boneName];
  31157. if (sourceBone) {
  31158. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  31159. }
  31160. else {
  31161. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  31162. ret = false;
  31163. }
  31164. }
  31165. // do not call createAnimationRange(), since it also is done to bones, which was already done
  31166. var range = source.getAnimationRange(name);
  31167. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  31168. return ret;
  31169. };
  31170. Skeleton.prototype.returnToRest = function () {
  31171. for (var index = 0; index < this.bones.length; index++) {
  31172. this.bones[index].returnToRest();
  31173. }
  31174. };
  31175. Skeleton.prototype._getHighestAnimationFrame = function () {
  31176. var ret = 0;
  31177. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  31178. if (this.bones[i].animations[0]) {
  31179. var highest = this.bones[i].animations[0].getHighestFrame();
  31180. if (ret < highest) {
  31181. ret = highest;
  31182. }
  31183. }
  31184. }
  31185. return ret;
  31186. };
  31187. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  31188. var range = this.getAnimationRange(name);
  31189. if (!range) {
  31190. return null;
  31191. }
  31192. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  31193. };
  31194. Skeleton.prototype._markAsDirty = function () {
  31195. this._isDirty = true;
  31196. };
  31197. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  31198. this._meshesWithPoseMatrix.push(mesh);
  31199. };
  31200. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  31201. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  31202. if (index > -1) {
  31203. this._meshesWithPoseMatrix.splice(index, 1);
  31204. }
  31205. };
  31206. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  31207. for (var index = 0; index < this.bones.length; index++) {
  31208. var bone = this.bones[index];
  31209. var parentBone = bone.getParent();
  31210. if (parentBone) {
  31211. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  31212. }
  31213. else {
  31214. if (initialSkinMatrix) {
  31215. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  31216. }
  31217. else {
  31218. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  31219. }
  31220. }
  31221. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, index * 16);
  31222. }
  31223. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  31224. };
  31225. Skeleton.prototype.prepare = function () {
  31226. if (!this._isDirty) {
  31227. return;
  31228. }
  31229. if (this.needInitialSkinMatrix) {
  31230. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  31231. var mesh = this._meshesWithPoseMatrix[index];
  31232. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  31233. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31234. }
  31235. var poseMatrix = mesh.getPoseMatrix();
  31236. // Prepare bones
  31237. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  31238. var bone = this.bones[boneIndex];
  31239. if (!bone.getParent()) {
  31240. var matrix = bone.getBaseMatrix();
  31241. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[0]);
  31242. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[0]);
  31243. }
  31244. }
  31245. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  31246. }
  31247. }
  31248. else {
  31249. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  31250. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  31251. }
  31252. this._computeTransformMatrices(this._transformMatrices, null);
  31253. }
  31254. this._isDirty = false;
  31255. this._scene._activeBones.addCount(this.bones.length, false);
  31256. };
  31257. Skeleton.prototype.getAnimatables = function () {
  31258. if (!this._animatables || this._animatables.length !== this.bones.length) {
  31259. this._animatables = [];
  31260. for (var index = 0; index < this.bones.length; index++) {
  31261. this._animatables.push(this.bones[index]);
  31262. }
  31263. }
  31264. return this._animatables;
  31265. };
  31266. Skeleton.prototype.clone = function (name, id) {
  31267. var result = new Skeleton(name, id || name, this._scene);
  31268. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31269. for (var index = 0; index < this.bones.length; index++) {
  31270. var source = this.bones[index];
  31271. var parentBone = null;
  31272. if (source.getParent()) {
  31273. var parentIndex = this.bones.indexOf(source.getParent());
  31274. parentBone = result.bones[parentIndex];
  31275. }
  31276. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  31277. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  31278. }
  31279. if (this._ranges) {
  31280. result._ranges = {};
  31281. for (var rangeName in this._ranges) {
  31282. result._ranges[rangeName] = this._ranges[rangeName].clone();
  31283. }
  31284. }
  31285. this._isDirty = true;
  31286. return result;
  31287. };
  31288. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  31289. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  31290. this.bones.forEach(function (bone) {
  31291. bone.animations.forEach(function (animation) {
  31292. animation.enableBlending = true;
  31293. animation.blendingSpeed = blendingSpeed;
  31294. });
  31295. });
  31296. };
  31297. Skeleton.prototype.dispose = function () {
  31298. this._meshesWithPoseMatrix = [];
  31299. // Animations
  31300. this.getScene().stopAnimation(this);
  31301. // Remove from scene
  31302. this.getScene().removeSkeleton(this);
  31303. };
  31304. Skeleton.prototype.serialize = function () {
  31305. var serializationObject = {};
  31306. serializationObject.name = this.name;
  31307. serializationObject.id = this.id;
  31308. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  31309. serializationObject.bones = [];
  31310. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  31311. for (var index = 0; index < this.bones.length; index++) {
  31312. var bone = this.bones[index];
  31313. var serializedBone = {
  31314. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  31315. name: bone.name,
  31316. matrix: bone.getLocalMatrix().toArray(),
  31317. rest: bone.getRestPose().toArray()
  31318. };
  31319. serializationObject.bones.push(serializedBone);
  31320. if (bone.length) {
  31321. serializedBone.length = bone.length;
  31322. }
  31323. if (bone.animations && bone.animations.length > 0) {
  31324. serializedBone.animation = bone.animations[0].serialize();
  31325. }
  31326. serializationObject.ranges = [];
  31327. for (var name in this._ranges) {
  31328. var range = {};
  31329. range.name = name;
  31330. range.from = this._ranges[name].from;
  31331. range.to = this._ranges[name].to;
  31332. serializationObject.ranges.push(range);
  31333. }
  31334. }
  31335. return serializationObject;
  31336. };
  31337. Skeleton.Parse = function (parsedSkeleton, scene) {
  31338. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  31339. if (parsedSkeleton.dimensionsAtRest) {
  31340. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  31341. }
  31342. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  31343. var index;
  31344. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  31345. var parsedBone = parsedSkeleton.bones[index];
  31346. var parentBone = null;
  31347. if (parsedBone.parentBoneIndex > -1) {
  31348. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  31349. }
  31350. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  31351. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  31352. if (parsedBone.length) {
  31353. bone.length = parsedBone.length;
  31354. }
  31355. if (parsedBone.animation) {
  31356. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  31357. }
  31358. }
  31359. // placed after bones, so createAnimationRange can cascade down
  31360. if (parsedSkeleton.ranges) {
  31361. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  31362. var data = parsedSkeleton.ranges[index];
  31363. skeleton.createAnimationRange(data.name, data.from, data.to);
  31364. }
  31365. }
  31366. return skeleton;
  31367. };
  31368. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  31369. if (forceUpdate === void 0) { forceUpdate = false; }
  31370. var renderId = this._scene.getRenderId();
  31371. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  31372. this.bones[0].computeAbsoluteTransforms();
  31373. this._lastAbsoluteTransformsUpdateId = renderId;
  31374. }
  31375. };
  31376. Skeleton.prototype.getPoseMatrix = function () {
  31377. var poseMatrix;
  31378. if (this._meshesWithPoseMatrix.length > 0) {
  31379. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  31380. }
  31381. return poseMatrix;
  31382. };
  31383. return Skeleton;
  31384. }());
  31385. BABYLON.Skeleton = Skeleton;
  31386. })(BABYLON || (BABYLON = {}));
  31387. //# sourceMappingURL=babylon.skeleton.js.map
  31388. var BABYLON;
  31389. (function (BABYLON) {
  31390. var PostProcess = (function () {
  31391. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType) {
  31392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  31393. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  31394. this.name = name;
  31395. this.width = -1;
  31396. this.height = -1;
  31397. /*
  31398. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  31399. Can only be used on a single postprocess or on the last one of a chain.
  31400. */
  31401. this.enablePixelPerfectMode = false;
  31402. this._reusable = false;
  31403. this._textures = new BABYLON.SmartArray(2);
  31404. this._currentRenderTextureInd = 0;
  31405. this._scaleRatio = new BABYLON.Vector2(1, 1);
  31406. // Events
  31407. /**
  31408. * An event triggered when the postprocess is activated.
  31409. * @type {BABYLON.Observable}
  31410. */
  31411. this.onActivateObservable = new BABYLON.Observable();
  31412. /**
  31413. * An event triggered when the postprocess changes its size.
  31414. * @type {BABYLON.Observable}
  31415. */
  31416. this.onSizeChangedObservable = new BABYLON.Observable();
  31417. /**
  31418. * An event triggered when the postprocess applies its effect.
  31419. * @type {BABYLON.Observable}
  31420. */
  31421. this.onApplyObservable = new BABYLON.Observable();
  31422. /**
  31423. * An event triggered before rendering the postprocess
  31424. * @type {BABYLON.Observable}
  31425. */
  31426. this.onBeforeRenderObservable = new BABYLON.Observable();
  31427. /**
  31428. * An event triggered after rendering the postprocess
  31429. * @type {BABYLON.Observable}
  31430. */
  31431. this.onAfterRenderObservable = new BABYLON.Observable();
  31432. if (camera != null) {
  31433. this._camera = camera;
  31434. this._scene = camera.getScene();
  31435. camera.attachPostProcess(this);
  31436. this._engine = this._scene.getEngine();
  31437. }
  31438. else {
  31439. this._engine = engine;
  31440. }
  31441. this._options = options;
  31442. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  31443. this._reusable = reusable || false;
  31444. this._textureType = textureType;
  31445. this._samplers = samplers || [];
  31446. this._samplers.push("textureSampler");
  31447. this._fragmentUrl = fragmentUrl;
  31448. this._parameters = parameters || [];
  31449. this._parameters.push("scale");
  31450. this.updateEffect(defines);
  31451. }
  31452. Object.defineProperty(PostProcess.prototype, "onActivate", {
  31453. set: function (callback) {
  31454. if (this._onActivateObserver) {
  31455. this.onActivateObservable.remove(this._onActivateObserver);
  31456. }
  31457. this._onActivateObserver = this.onActivateObservable.add(callback);
  31458. },
  31459. enumerable: true,
  31460. configurable: true
  31461. });
  31462. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  31463. set: function (callback) {
  31464. if (this._onSizeChangedObserver) {
  31465. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  31466. }
  31467. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  31468. },
  31469. enumerable: true,
  31470. configurable: true
  31471. });
  31472. Object.defineProperty(PostProcess.prototype, "onApply", {
  31473. set: function (callback) {
  31474. if (this._onApplyObserver) {
  31475. this.onApplyObservable.remove(this._onApplyObserver);
  31476. }
  31477. this._onApplyObserver = this.onApplyObservable.add(callback);
  31478. },
  31479. enumerable: true,
  31480. configurable: true
  31481. });
  31482. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  31483. set: function (callback) {
  31484. if (this._onBeforeRenderObserver) {
  31485. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  31486. }
  31487. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  31488. },
  31489. enumerable: true,
  31490. configurable: true
  31491. });
  31492. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  31493. set: function (callback) {
  31494. if (this._onAfterRenderObserver) {
  31495. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  31496. }
  31497. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  31498. },
  31499. enumerable: true,
  31500. configurable: true
  31501. });
  31502. PostProcess.prototype.updateEffect = function (defines) {
  31503. this._effect = this._engine.createEffect({ vertex: "postprocess", fragment: this._fragmentUrl }, ["position"], this._parameters, this._samplers, defines !== undefined ? defines : "");
  31504. };
  31505. PostProcess.prototype.isReusable = function () {
  31506. return this._reusable;
  31507. };
  31508. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  31509. PostProcess.prototype.markTextureDirty = function () {
  31510. this.width = -1;
  31511. };
  31512. PostProcess.prototype.activate = function (camera, sourceTexture) {
  31513. camera = camera || this._camera;
  31514. var scene = camera.getScene();
  31515. var maxSize = camera.getEngine().getCaps().maxTextureSize;
  31516. var requiredWidth = ((sourceTexture ? sourceTexture._width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  31517. var requiredHeight = ((sourceTexture ? sourceTexture._height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  31518. var desiredWidth = this._options.width || requiredWidth;
  31519. var desiredHeight = this._options.height || requiredHeight;
  31520. if (this.renderTargetSamplingMode !== BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  31521. if (!this._options.width) {
  31522. desiredWidth = BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize);
  31523. }
  31524. if (!this._options.height) {
  31525. desiredHeight = BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize);
  31526. }
  31527. }
  31528. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  31529. if (this._textures.length > 0) {
  31530. for (var i = 0; i < this._textures.length; i++) {
  31531. this._engine._releaseTexture(this._textures.data[i]);
  31532. }
  31533. this._textures.reset();
  31534. }
  31535. this.width = desiredWidth;
  31536. this.height = desiredHeight;
  31537. var textureSize = { width: this.width, height: this.height };
  31538. var textureOptions = {
  31539. generateMipMaps: false,
  31540. generateDepthBuffer: camera._postProcesses.indexOf(this) === 0,
  31541. generateStencilBuffer: camera._postProcesses.indexOf(this) === 0 && this._engine.isStencilEnable,
  31542. samplingMode: this.renderTargetSamplingMode,
  31543. type: this._textureType
  31544. };
  31545. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31546. if (this._reusable) {
  31547. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  31548. }
  31549. this.onSizeChangedObservable.notifyObservers(this);
  31550. }
  31551. if (this.enablePixelPerfectMode) {
  31552. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  31553. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd], 0, requiredWidth, requiredHeight);
  31554. }
  31555. else {
  31556. this._scaleRatio.copyFromFloats(1, 1);
  31557. this._engine.bindFramebuffer(this._textures.data[this._currentRenderTextureInd]);
  31558. }
  31559. this.onActivateObservable.notifyObservers(camera);
  31560. // Clear
  31561. if (this.clearColor) {
  31562. this._engine.clear(this.clearColor, true, true, true);
  31563. }
  31564. else {
  31565. this._engine.clear(scene.clearColor, scene.autoClear || scene.forceWireframe, true, true);
  31566. }
  31567. if (this._reusable) {
  31568. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  31569. }
  31570. };
  31571. Object.defineProperty(PostProcess.prototype, "isSupported", {
  31572. get: function () {
  31573. return this._effect.isSupported;
  31574. },
  31575. enumerable: true,
  31576. configurable: true
  31577. });
  31578. PostProcess.prototype.apply = function () {
  31579. // Check
  31580. if (!this._effect.isReady())
  31581. return null;
  31582. // States
  31583. this._engine.enableEffect(this._effect);
  31584. this._engine.setState(false);
  31585. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  31586. this._engine.setDepthBuffer(false);
  31587. this._engine.setDepthWrite(false);
  31588. // Texture
  31589. this._effect._bindTexture("textureSampler", this._textures.data[this._currentRenderTextureInd]);
  31590. // Parameters
  31591. this._effect.setVector2("scale", this._scaleRatio);
  31592. this.onApplyObservable.notifyObservers(this._effect);
  31593. return this._effect;
  31594. };
  31595. PostProcess.prototype.dispose = function (camera) {
  31596. camera = camera || this._camera;
  31597. if (this._textures.length > 0) {
  31598. for (var i = 0; i < this._textures.length; i++) {
  31599. this._engine._releaseTexture(this._textures.data[i]);
  31600. }
  31601. this._textures.reset();
  31602. }
  31603. if (!camera) {
  31604. return;
  31605. }
  31606. camera.detachPostProcess(this);
  31607. var index = camera._postProcesses.indexOf(this);
  31608. if (index === 0 && camera._postProcesses.length > 0) {
  31609. this._camera._postProcesses[0].markTextureDirty();
  31610. }
  31611. this.onActivateObservable.clear();
  31612. this.onAfterRenderObservable.clear();
  31613. this.onApplyObservable.clear();
  31614. this.onBeforeRenderObservable.clear();
  31615. this.onSizeChangedObservable.clear();
  31616. };
  31617. return PostProcess;
  31618. }());
  31619. BABYLON.PostProcess = PostProcess;
  31620. })(BABYLON || (BABYLON = {}));
  31621. //# sourceMappingURL=babylon.postProcess.js.map
  31622. var BABYLON;
  31623. (function (BABYLON) {
  31624. var PostProcessManager = (function () {
  31625. function PostProcessManager(scene) {
  31626. this._vertexBuffers = {};
  31627. this._scene = scene;
  31628. }
  31629. PostProcessManager.prototype._prepareBuffers = function () {
  31630. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  31631. return;
  31632. }
  31633. // VBO
  31634. var vertices = [];
  31635. vertices.push(1, 1);
  31636. vertices.push(-1, 1);
  31637. vertices.push(-1, -1);
  31638. vertices.push(1, -1);
  31639. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  31640. // Indices
  31641. var indices = [];
  31642. indices.push(0);
  31643. indices.push(1);
  31644. indices.push(2);
  31645. indices.push(0);
  31646. indices.push(2);
  31647. indices.push(3);
  31648. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  31649. };
  31650. // Methods
  31651. PostProcessManager.prototype._prepareFrame = function (sourceTexture) {
  31652. var postProcesses = this._scene.activeCamera._postProcesses;
  31653. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31654. return false;
  31655. }
  31656. postProcesses[0].activate(this._scene.activeCamera, sourceTexture);
  31657. return true;
  31658. };
  31659. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture) {
  31660. var engine = this._scene.getEngine();
  31661. for (var index = 0; index < postProcesses.length; index++) {
  31662. if (index < postProcesses.length - 1) {
  31663. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31664. }
  31665. else {
  31666. if (targetTexture) {
  31667. engine.bindFramebuffer(targetTexture);
  31668. }
  31669. else {
  31670. engine.restoreDefaultFramebuffer();
  31671. }
  31672. }
  31673. var pp = postProcesses[index];
  31674. var effect = pp.apply();
  31675. if (effect) {
  31676. pp.onBeforeRenderObservable.notifyObservers(effect);
  31677. // VBOs
  31678. this._prepareBuffers();
  31679. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31680. // Draw order
  31681. engine.draw(true, 0, 6);
  31682. pp.onAfterRenderObservable.notifyObservers(effect);
  31683. }
  31684. }
  31685. // Restore depth buffer
  31686. engine.setDepthBuffer(true);
  31687. engine.setDepthWrite(true);
  31688. };
  31689. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  31690. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  31691. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  31692. return;
  31693. }
  31694. var engine = this._scene.getEngine();
  31695. for (var index = 0, len = postProcesses.length; index < len; index++) {
  31696. if (index < len - 1) {
  31697. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  31698. }
  31699. else {
  31700. if (targetTexture) {
  31701. engine.bindFramebuffer(targetTexture, faceIndex);
  31702. }
  31703. else {
  31704. engine.restoreDefaultFramebuffer();
  31705. }
  31706. }
  31707. if (doNotPresent) {
  31708. break;
  31709. }
  31710. var pp = postProcesses[index];
  31711. var effect = pp.apply();
  31712. if (effect) {
  31713. pp.onBeforeRenderObservable.notifyObservers(effect);
  31714. // VBOs
  31715. this._prepareBuffers();
  31716. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  31717. // Draw order
  31718. engine.draw(true, 0, 6);
  31719. pp.onAfterRenderObservable.notifyObservers(effect);
  31720. }
  31721. }
  31722. // Restore depth buffer
  31723. engine.setDepthBuffer(true);
  31724. engine.setDepthWrite(true);
  31725. };
  31726. PostProcessManager.prototype.dispose = function () {
  31727. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  31728. if (buffer) {
  31729. buffer.dispose();
  31730. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  31731. }
  31732. if (this._indexBuffer) {
  31733. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  31734. this._indexBuffer = null;
  31735. }
  31736. };
  31737. return PostProcessManager;
  31738. }());
  31739. BABYLON.PostProcessManager = PostProcessManager;
  31740. })(BABYLON || (BABYLON = {}));
  31741. //# sourceMappingURL=babylon.postProcessManager.js.map
  31742. var BABYLON;
  31743. (function (BABYLON) {
  31744. var PassPostProcess = (function (_super) {
  31745. __extends(PassPostProcess, _super);
  31746. function PassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  31747. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable) || this;
  31748. }
  31749. return PassPostProcess;
  31750. }(BABYLON.PostProcess));
  31751. BABYLON.PassPostProcess = PassPostProcess;
  31752. })(BABYLON || (BABYLON = {}));
  31753. //# sourceMappingURL=babylon.passPostProcess.js.map
  31754. var BABYLON;
  31755. (function (BABYLON) {
  31756. /**
  31757. * This is a holder class for the physics joint created by the physics plugin.
  31758. * It holds a set of functions to control the underlying joint.
  31759. */
  31760. var PhysicsJoint = (function () {
  31761. function PhysicsJoint(type, jointData) {
  31762. this.type = type;
  31763. this.jointData = jointData;
  31764. jointData.nativeParams = jointData.nativeParams || {};
  31765. }
  31766. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  31767. get: function () {
  31768. return this._physicsJoint;
  31769. },
  31770. set: function (newJoint) {
  31771. if (this._physicsJoint) {
  31772. }
  31773. this._physicsJoint = newJoint;
  31774. },
  31775. enumerable: true,
  31776. configurable: true
  31777. });
  31778. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  31779. set: function (physicsPlugin) {
  31780. this._physicsPlugin = physicsPlugin;
  31781. },
  31782. enumerable: true,
  31783. configurable: true
  31784. });
  31785. /**
  31786. * Execute a function that is physics-plugin specific.
  31787. * @param {Function} func the function that will be executed.
  31788. * It accepts two parameters: the physics world and the physics joint.
  31789. */
  31790. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  31791. func(this._physicsPlugin.world, this._physicsJoint);
  31792. };
  31793. return PhysicsJoint;
  31794. }());
  31795. //TODO check if the native joints are the same
  31796. //Joint Types
  31797. PhysicsJoint.DistanceJoint = 0;
  31798. PhysicsJoint.HingeJoint = 1;
  31799. PhysicsJoint.BallAndSocketJoint = 2;
  31800. PhysicsJoint.WheelJoint = 3;
  31801. PhysicsJoint.SliderJoint = 4;
  31802. //OIMO
  31803. PhysicsJoint.PrismaticJoint = 5;
  31804. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  31805. PhysicsJoint.UniversalJoint = 6;
  31806. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  31807. //Cannon
  31808. //Similar to a Ball-Joint. Different in params
  31809. PhysicsJoint.PointToPointJoint = 8;
  31810. //Cannon only at the moment
  31811. PhysicsJoint.SpringJoint = 9;
  31812. PhysicsJoint.LockJoint = 10;
  31813. BABYLON.PhysicsJoint = PhysicsJoint;
  31814. /**
  31815. * A class representing a physics distance joint.
  31816. */
  31817. var DistanceJoint = (function (_super) {
  31818. __extends(DistanceJoint, _super);
  31819. function DistanceJoint(jointData) {
  31820. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  31821. }
  31822. /**
  31823. * Update the predefined distance.
  31824. */
  31825. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  31826. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  31827. };
  31828. return DistanceJoint;
  31829. }(PhysicsJoint));
  31830. BABYLON.DistanceJoint = DistanceJoint;
  31831. var MotorEnabledJoint = (function (_super) {
  31832. __extends(MotorEnabledJoint, _super);
  31833. function MotorEnabledJoint(type, jointData) {
  31834. return _super.call(this, type, jointData) || this;
  31835. }
  31836. /**
  31837. * Set the motor values.
  31838. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31839. * @param {number} force the force to apply
  31840. * @param {number} maxForce max force for this motor.
  31841. */
  31842. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  31843. this._physicsPlugin.setMotor(this, force, maxForce);
  31844. };
  31845. /**
  31846. * Set the motor's limits.
  31847. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31848. */
  31849. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31850. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31851. };
  31852. return MotorEnabledJoint;
  31853. }(PhysicsJoint));
  31854. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  31855. /**
  31856. * This class represents a single hinge physics joint
  31857. */
  31858. var HingeJoint = (function (_super) {
  31859. __extends(HingeJoint, _super);
  31860. function HingeJoint(jointData) {
  31861. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  31862. }
  31863. /**
  31864. * Set the motor values.
  31865. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31866. * @param {number} force the force to apply
  31867. * @param {number} maxForce max force for this motor.
  31868. */
  31869. HingeJoint.prototype.setMotor = function (force, maxForce) {
  31870. this._physicsPlugin.setMotor(this, force, maxForce);
  31871. };
  31872. /**
  31873. * Set the motor's limits.
  31874. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31875. */
  31876. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  31877. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  31878. };
  31879. return HingeJoint;
  31880. }(MotorEnabledJoint));
  31881. BABYLON.HingeJoint = HingeJoint;
  31882. /**
  31883. * This class represents a dual hinge physics joint (same as wheel joint)
  31884. */
  31885. var Hinge2Joint = (function (_super) {
  31886. __extends(Hinge2Joint, _super);
  31887. function Hinge2Joint(jointData) {
  31888. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  31889. }
  31890. /**
  31891. * Set the motor values.
  31892. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31893. * @param {number} force the force to apply
  31894. * @param {number} maxForce max force for this motor.
  31895. * @param {motorIndex} the motor's index, 0 or 1.
  31896. */
  31897. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  31898. if (motorIndex === void 0) { motorIndex = 0; }
  31899. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  31900. };
  31901. /**
  31902. * Set the motor limits.
  31903. * Attention, this function is plugin specific. Engines won't react 100% the same.
  31904. * @param {number} upperLimit the upper limit
  31905. * @param {number} lowerLimit lower limit
  31906. * @param {motorIndex} the motor's index, 0 or 1.
  31907. */
  31908. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  31909. if (motorIndex === void 0) { motorIndex = 0; }
  31910. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  31911. };
  31912. return Hinge2Joint;
  31913. }(MotorEnabledJoint));
  31914. BABYLON.Hinge2Joint = Hinge2Joint;
  31915. })(BABYLON || (BABYLON = {}));
  31916. //# sourceMappingURL=babylon.physicsJoint.js.map
  31917. var BABYLON;
  31918. (function (BABYLON) {
  31919. var PhysicsImpostor = (function () {
  31920. function PhysicsImpostor(object, type, _options, _scene) {
  31921. if (_options === void 0) { _options = { mass: 0 }; }
  31922. var _this = this;
  31923. this.object = object;
  31924. this.type = type;
  31925. this._options = _options;
  31926. this._scene = _scene;
  31927. this._bodyUpdateRequired = false;
  31928. this._onBeforePhysicsStepCallbacks = new Array();
  31929. this._onAfterPhysicsStepCallbacks = new Array();
  31930. this._onPhysicsCollideCallbacks = [];
  31931. this._deltaPosition = BABYLON.Vector3.Zero();
  31932. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  31933. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  31934. /**
  31935. * this function is executed by the physics engine.
  31936. */
  31937. this.beforeStep = function () {
  31938. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  31939. //conjugate deltaRotation
  31940. if (_this._deltaRotationConjugated) {
  31941. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  31942. }
  31943. else {
  31944. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  31945. }
  31946. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  31947. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  31948. func(_this);
  31949. });
  31950. };
  31951. /**
  31952. * this function is executed by the physics engine.
  31953. */
  31954. this.afterStep = function () {
  31955. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  31956. func(_this);
  31957. });
  31958. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  31959. _this.object.position.addInPlace(_this._deltaPosition);
  31960. if (_this._deltaRotation) {
  31961. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  31962. }
  31963. };
  31964. //event and body object due to cannon's event-based architecture.
  31965. this.onCollide = function (e) {
  31966. if (!_this._onPhysicsCollideCallbacks.length)
  31967. return;
  31968. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  31969. if (otherImpostor) {
  31970. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  31971. return (obj.otherImpostors.length === 0 || obj.otherImpostors.indexOf(otherImpostor) !== -1);
  31972. }).forEach(function (obj) {
  31973. obj.callback(_this, otherImpostor);
  31974. });
  31975. }
  31976. };
  31977. //sanity check!
  31978. if (!this.object) {
  31979. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  31980. return;
  31981. }
  31982. //legacy support for old syntax.
  31983. if (!this._scene && object.getScene) {
  31984. this._scene = object.getScene();
  31985. }
  31986. this._physicsEngine = this._scene.getPhysicsEngine();
  31987. if (!this._physicsEngine) {
  31988. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  31989. }
  31990. else {
  31991. //set the object's quaternion, if not set
  31992. if (!this.object.rotationQuaternion) {
  31993. if (this.object.rotation) {
  31994. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  31995. }
  31996. else {
  31997. this.object.rotationQuaternion = new BABYLON.Quaternion();
  31998. }
  31999. }
  32000. //default options params
  32001. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  32002. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  32003. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  32004. this._joints = [];
  32005. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  32006. if (!this.object.parent) {
  32007. this._init();
  32008. }
  32009. }
  32010. }
  32011. /**
  32012. * This function will completly initialize this impostor.
  32013. * It will create a new body - but only if this mesh has no parent.
  32014. * If it has, this impostor will not be used other than to define the impostor
  32015. * of the child mesh.
  32016. */
  32017. PhysicsImpostor.prototype._init = function () {
  32018. this._physicsEngine.removeImpostor(this);
  32019. this.physicsBody = null;
  32020. this._parent = this._parent || this._getPhysicsParent();
  32021. if (!this.parent) {
  32022. this._physicsEngine.addImpostor(this);
  32023. }
  32024. };
  32025. PhysicsImpostor.prototype._getPhysicsParent = function () {
  32026. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  32027. var parentMesh = this.object.parent;
  32028. return parentMesh.physicsImpostor;
  32029. }
  32030. return;
  32031. };
  32032. /**
  32033. * Should a new body be generated.
  32034. */
  32035. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  32036. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  32037. };
  32038. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  32039. this.forceUpdate();
  32040. };
  32041. /**
  32042. * Force a regeneration of this or the parent's impostor's body.
  32043. * Use under cautious - This will remove all joints already implemented.
  32044. */
  32045. PhysicsImpostor.prototype.forceUpdate = function () {
  32046. this._init();
  32047. if (this.parent) {
  32048. this.parent.forceUpdate();
  32049. }
  32050. };
  32051. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  32052. /*public get mesh(): AbstractMesh {
  32053. return this._mesh;
  32054. }*/
  32055. /**
  32056. * Gets the body that holds this impostor. Either its own, or its parent.
  32057. */
  32058. get: function () {
  32059. return this._parent ? this._parent.physicsBody : this._physicsBody;
  32060. },
  32061. /**
  32062. * Set the physics body. Used mainly by the physics engine/plugin
  32063. */
  32064. set: function (physicsBody) {
  32065. if (this._physicsBody) {
  32066. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  32067. }
  32068. this._physicsBody = physicsBody;
  32069. this.resetUpdateFlags();
  32070. },
  32071. enumerable: true,
  32072. configurable: true
  32073. });
  32074. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  32075. get: function () {
  32076. return this._parent;
  32077. },
  32078. set: function (value) {
  32079. this._parent = value;
  32080. },
  32081. enumerable: true,
  32082. configurable: true
  32083. });
  32084. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  32085. this._bodyUpdateRequired = false;
  32086. };
  32087. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  32088. if (this.object.getBoundingInfo) {
  32089. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  32090. return this.object.getBoundingInfo().boundingBox.extendSize.scale(2).multiply(this.object.scaling);
  32091. }
  32092. else {
  32093. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  32094. }
  32095. };
  32096. PhysicsImpostor.prototype.getObjectCenter = function () {
  32097. if (this.object.getBoundingInfo) {
  32098. return this.object.getBoundingInfo().boundingBox.center;
  32099. }
  32100. else {
  32101. return this.object.position;
  32102. }
  32103. };
  32104. /**
  32105. * Get a specific parametes from the options parameter.
  32106. */
  32107. PhysicsImpostor.prototype.getParam = function (paramName) {
  32108. return this._options[paramName];
  32109. };
  32110. /**
  32111. * Sets a specific parameter in the options given to the physics plugin
  32112. */
  32113. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  32114. this._options[paramName] = value;
  32115. this._bodyUpdateRequired = true;
  32116. };
  32117. /**
  32118. * Specifically change the body's mass option. Won't recreate the physics body object
  32119. */
  32120. PhysicsImpostor.prototype.setMass = function (mass) {
  32121. if (this.getParam("mass") !== mass) {
  32122. this.setParam("mass", mass);
  32123. }
  32124. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  32125. };
  32126. PhysicsImpostor.prototype.getLinearVelocity = function () {
  32127. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  32128. };
  32129. /**
  32130. * Set the body's linear velocity.
  32131. */
  32132. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  32133. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  32134. };
  32135. PhysicsImpostor.prototype.getAngularVelocity = function () {
  32136. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  32137. };
  32138. /**
  32139. * Set the body's linear velocity.
  32140. */
  32141. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  32142. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  32143. };
  32144. /**
  32145. * Execute a function with the physics plugin native code.
  32146. * Provide a function the will have two variables - the world object and the physics body object.
  32147. */
  32148. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  32149. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  32150. };
  32151. /**
  32152. * Register a function that will be executed before the physics world is stepping forward.
  32153. */
  32154. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  32155. this._onBeforePhysicsStepCallbacks.push(func);
  32156. };
  32157. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  32158. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  32159. if (index > -1) {
  32160. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  32161. }
  32162. else {
  32163. BABYLON.Tools.Warn("Function to remove was not found");
  32164. }
  32165. };
  32166. /**
  32167. * Register a function that will be executed after the physics step
  32168. */
  32169. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  32170. this._onAfterPhysicsStepCallbacks.push(func);
  32171. };
  32172. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  32173. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  32174. if (index > -1) {
  32175. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  32176. }
  32177. else {
  32178. BABYLON.Tools.Warn("Function to remove was not found");
  32179. }
  32180. };
  32181. /**
  32182. * register a function that will be executed when this impostor collides against a different body.
  32183. */
  32184. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  32185. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32186. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  32187. };
  32188. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  32189. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  32190. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  32191. if (index > -1) {
  32192. this._onPhysicsCollideCallbacks.splice(index, 1);
  32193. }
  32194. else {
  32195. BABYLON.Tools.Warn("Function to remove was not found");
  32196. }
  32197. };
  32198. /**
  32199. * Apply a force
  32200. */
  32201. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  32202. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  32203. };
  32204. /**
  32205. * Apply an impulse
  32206. */
  32207. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  32208. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  32209. };
  32210. /**
  32211. * A help function to create a joint.
  32212. */
  32213. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  32214. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  32215. this.addJoint(otherImpostor, joint);
  32216. };
  32217. /**
  32218. * Add a joint to this impostor with a different impostor.
  32219. */
  32220. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  32221. this._joints.push({
  32222. otherImpostor: otherImpostor,
  32223. joint: joint
  32224. });
  32225. this._physicsEngine.addJoint(this, otherImpostor, joint);
  32226. };
  32227. /**
  32228. * Will keep this body still, in a sleep mode.
  32229. */
  32230. PhysicsImpostor.prototype.sleep = function () {
  32231. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  32232. };
  32233. /**
  32234. * Wake the body up.
  32235. */
  32236. PhysicsImpostor.prototype.wakeUp = function () {
  32237. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  32238. };
  32239. PhysicsImpostor.prototype.clone = function (newObject) {
  32240. if (!newObject)
  32241. return null;
  32242. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  32243. };
  32244. PhysicsImpostor.prototype.dispose = function () {
  32245. var _this = this;
  32246. //no dispose if no physics engine is available.
  32247. if (!this._physicsEngine) {
  32248. return;
  32249. }
  32250. this._joints.forEach(function (j) {
  32251. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  32252. });
  32253. //dispose the physics body
  32254. this._physicsEngine.removeImpostor(this);
  32255. if (this.parent) {
  32256. this.parent.forceUpdate();
  32257. }
  32258. else {
  32259. }
  32260. };
  32261. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  32262. this._deltaPosition.copyFrom(position);
  32263. };
  32264. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  32265. if (!this._deltaRotation) {
  32266. this._deltaRotation = new BABYLON.Quaternion();
  32267. }
  32268. this._deltaRotation.copyFrom(rotation);
  32269. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  32270. };
  32271. return PhysicsImpostor;
  32272. }());
  32273. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  32274. //Impostor types
  32275. PhysicsImpostor.NoImpostor = 0;
  32276. PhysicsImpostor.SphereImpostor = 1;
  32277. PhysicsImpostor.BoxImpostor = 2;
  32278. PhysicsImpostor.PlaneImpostor = 3;
  32279. PhysicsImpostor.MeshImpostor = 4;
  32280. PhysicsImpostor.CylinderImpostor = 7;
  32281. PhysicsImpostor.ParticleImpostor = 8;
  32282. PhysicsImpostor.HeightmapImpostor = 9;
  32283. BABYLON.PhysicsImpostor = PhysicsImpostor;
  32284. })(BABYLON || (BABYLON = {}));
  32285. //# sourceMappingURL=babylon.physicsImpostor.js.map
  32286. var BABYLON;
  32287. (function (BABYLON) {
  32288. var PhysicsEngine = (function () {
  32289. function PhysicsEngine(gravity, _physicsPlugin) {
  32290. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  32291. this._physicsPlugin = _physicsPlugin;
  32292. //new methods and parameters
  32293. this._impostors = [];
  32294. this._joints = [];
  32295. if (!this._physicsPlugin.isSupported()) {
  32296. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  32297. + "Please make sure it is included.");
  32298. }
  32299. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  32300. this.setGravity(gravity);
  32301. this.setTimeStep();
  32302. }
  32303. PhysicsEngine.prototype.setGravity = function (gravity) {
  32304. this.gravity = gravity;
  32305. this._physicsPlugin.setGravity(this.gravity);
  32306. };
  32307. /**
  32308. * Set the time step of the physics engine.
  32309. * default is 1/60.
  32310. * To slow it down, enter 1/600 for example.
  32311. * To speed it up, 1/30
  32312. * @param {number} newTimeStep the new timestep to apply to this world.
  32313. */
  32314. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  32315. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  32316. this._physicsPlugin.setTimeStep(newTimeStep);
  32317. };
  32318. PhysicsEngine.prototype.dispose = function () {
  32319. this._impostors.forEach(function (impostor) {
  32320. impostor.dispose();
  32321. });
  32322. this._physicsPlugin.dispose();
  32323. };
  32324. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  32325. return this._physicsPlugin.name;
  32326. };
  32327. /**
  32328. * Adding a new impostor for the impostor tracking.
  32329. * This will be done by the impostor itself.
  32330. * @param {PhysicsImpostor} impostor the impostor to add
  32331. */
  32332. PhysicsEngine.prototype.addImpostor = function (impostor) {
  32333. impostor.uniqueId = this._impostors.push(impostor);
  32334. //if no parent, generate the body
  32335. if (!impostor.parent) {
  32336. this._physicsPlugin.generatePhysicsBody(impostor);
  32337. }
  32338. };
  32339. /**
  32340. * Remove an impostor from the engine.
  32341. * This impostor and its mesh will not longer be updated by the physics engine.
  32342. * @param {PhysicsImpostor} impostor the impostor to remove
  32343. */
  32344. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  32345. var index = this._impostors.indexOf(impostor);
  32346. if (index > -1) {
  32347. var removed = this._impostors.splice(index, 1);
  32348. //Is it needed?
  32349. if (removed.length) {
  32350. //this will also remove it from the world.
  32351. removed[0].physicsBody = null;
  32352. }
  32353. }
  32354. };
  32355. /**
  32356. * Add a joint to the physics engine
  32357. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  32358. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  32359. * @param {PhysicsJoint} the joint that will connect both impostors.
  32360. */
  32361. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  32362. var impostorJoint = {
  32363. mainImpostor: mainImpostor,
  32364. connectedImpostor: connectedImpostor,
  32365. joint: joint
  32366. };
  32367. joint.physicsPlugin = this._physicsPlugin;
  32368. this._joints.push(impostorJoint);
  32369. this._physicsPlugin.generateJoint(impostorJoint);
  32370. };
  32371. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  32372. var matchingJoints = this._joints.filter(function (impostorJoint) {
  32373. return (impostorJoint.connectedImpostor === connectedImpostor
  32374. && impostorJoint.joint === joint
  32375. && impostorJoint.mainImpostor === mainImpostor);
  32376. });
  32377. if (matchingJoints.length) {
  32378. this._physicsPlugin.removeJoint(matchingJoints[0]);
  32379. }
  32380. };
  32381. /**
  32382. * Called by the scene. no need to call it.
  32383. */
  32384. PhysicsEngine.prototype._step = function (delta) {
  32385. var _this = this;
  32386. //check if any mesh has no body / requires an update
  32387. this._impostors.forEach(function (impostor) {
  32388. if (impostor.isBodyInitRequired()) {
  32389. _this._physicsPlugin.generatePhysicsBody(impostor);
  32390. }
  32391. });
  32392. if (delta > 0.1) {
  32393. delta = 0.1;
  32394. }
  32395. else if (delta <= 0) {
  32396. delta = 1.0 / 60.0;
  32397. }
  32398. this._physicsPlugin.executeStep(delta, this._impostors);
  32399. };
  32400. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  32401. return this._physicsPlugin;
  32402. };
  32403. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  32404. for (var i = 0; i < this._impostors.length; ++i) {
  32405. if (this._impostors[i].object === object) {
  32406. return this._impostors[i];
  32407. }
  32408. }
  32409. };
  32410. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  32411. for (var i = 0; i < this._impostors.length; ++i) {
  32412. if (this._impostors[i].physicsBody === body) {
  32413. return this._impostors[i];
  32414. }
  32415. }
  32416. };
  32417. return PhysicsEngine;
  32418. }());
  32419. // Statics, Legacy support.
  32420. /**
  32421. * @Deprecated
  32422. *
  32423. */
  32424. PhysicsEngine.NoImpostor = BABYLON.PhysicsImpostor.NoImpostor;
  32425. PhysicsEngine.SphereImpostor = BABYLON.PhysicsImpostor.SphereImpostor;
  32426. PhysicsEngine.BoxImpostor = BABYLON.PhysicsImpostor.BoxImpostor;
  32427. PhysicsEngine.PlaneImpostor = BABYLON.PhysicsImpostor.PlaneImpostor;
  32428. PhysicsEngine.MeshImpostor = BABYLON.PhysicsImpostor.MeshImpostor;
  32429. PhysicsEngine.CylinderImpostor = BABYLON.PhysicsImpostor.CylinderImpostor;
  32430. PhysicsEngine.HeightmapImpostor = BABYLON.PhysicsImpostor.HeightmapImpostor;
  32431. PhysicsEngine.CapsuleImpostor = -1;
  32432. PhysicsEngine.ConeImpostor = -1;
  32433. PhysicsEngine.ConvexHullImpostor = -1;
  32434. PhysicsEngine.Epsilon = 0.001;
  32435. BABYLON.PhysicsEngine = PhysicsEngine;
  32436. })(BABYLON || (BABYLON = {}));
  32437. //# sourceMappingURL=babylon.physicsEngine.js.map
  32438. var BABYLON;
  32439. (function (BABYLON) {
  32440. var VertexData = (function () {
  32441. function VertexData() {
  32442. }
  32443. VertexData.prototype.set = function (data, kind) {
  32444. switch (kind) {
  32445. case BABYLON.VertexBuffer.PositionKind:
  32446. this.positions = data;
  32447. break;
  32448. case BABYLON.VertexBuffer.NormalKind:
  32449. this.normals = data;
  32450. break;
  32451. case BABYLON.VertexBuffer.UVKind:
  32452. this.uvs = data;
  32453. break;
  32454. case BABYLON.VertexBuffer.UV2Kind:
  32455. this.uvs2 = data;
  32456. break;
  32457. case BABYLON.VertexBuffer.UV3Kind:
  32458. this.uvs3 = data;
  32459. break;
  32460. case BABYLON.VertexBuffer.UV4Kind:
  32461. this.uvs4 = data;
  32462. break;
  32463. case BABYLON.VertexBuffer.UV5Kind:
  32464. this.uvs5 = data;
  32465. break;
  32466. case BABYLON.VertexBuffer.UV6Kind:
  32467. this.uvs6 = data;
  32468. break;
  32469. case BABYLON.VertexBuffer.ColorKind:
  32470. this.colors = data;
  32471. break;
  32472. case BABYLON.VertexBuffer.MatricesIndicesKind:
  32473. this.matricesIndices = data;
  32474. break;
  32475. case BABYLON.VertexBuffer.MatricesWeightsKind:
  32476. this.matricesWeights = data;
  32477. break;
  32478. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  32479. this.matricesIndicesExtra = data;
  32480. break;
  32481. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  32482. this.matricesWeightsExtra = data;
  32483. break;
  32484. }
  32485. };
  32486. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  32487. this._applyTo(mesh, updatable);
  32488. };
  32489. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  32490. this._applyTo(geometry, updatable);
  32491. };
  32492. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  32493. this._update(mesh);
  32494. };
  32495. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  32496. this._update(geometry);
  32497. };
  32498. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  32499. if (this.positions) {
  32500. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  32501. }
  32502. if (this.normals) {
  32503. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  32504. }
  32505. if (this.uvs) {
  32506. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  32507. }
  32508. if (this.uvs2) {
  32509. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  32510. }
  32511. if (this.uvs3) {
  32512. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  32513. }
  32514. if (this.uvs4) {
  32515. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  32516. }
  32517. if (this.uvs5) {
  32518. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  32519. }
  32520. if (this.uvs6) {
  32521. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  32522. }
  32523. if (this.colors) {
  32524. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  32525. }
  32526. if (this.matricesIndices) {
  32527. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  32528. }
  32529. if (this.matricesWeights) {
  32530. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  32531. }
  32532. if (this.matricesIndicesExtra) {
  32533. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  32534. }
  32535. if (this.matricesWeightsExtra) {
  32536. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  32537. }
  32538. if (this.indices) {
  32539. meshOrGeometry.setIndices(this.indices);
  32540. }
  32541. };
  32542. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  32543. if (this.positions) {
  32544. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  32545. }
  32546. if (this.normals) {
  32547. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  32548. }
  32549. if (this.uvs) {
  32550. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  32551. }
  32552. if (this.uvs2) {
  32553. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  32554. }
  32555. if (this.uvs3) {
  32556. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  32557. }
  32558. if (this.uvs4) {
  32559. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  32560. }
  32561. if (this.uvs5) {
  32562. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  32563. }
  32564. if (this.uvs6) {
  32565. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  32566. }
  32567. if (this.colors) {
  32568. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  32569. }
  32570. if (this.matricesIndices) {
  32571. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  32572. }
  32573. if (this.matricesWeights) {
  32574. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  32575. }
  32576. if (this.matricesIndicesExtra) {
  32577. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  32578. }
  32579. if (this.matricesWeightsExtra) {
  32580. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  32581. }
  32582. if (this.indices) {
  32583. meshOrGeometry.setIndices(this.indices);
  32584. }
  32585. };
  32586. VertexData.prototype.transform = function (matrix) {
  32587. var transformed = BABYLON.Vector3.Zero();
  32588. var index;
  32589. if (this.positions) {
  32590. var position = BABYLON.Vector3.Zero();
  32591. for (index = 0; index < this.positions.length; index += 3) {
  32592. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  32593. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  32594. this.positions[index] = transformed.x;
  32595. this.positions[index + 1] = transformed.y;
  32596. this.positions[index + 2] = transformed.z;
  32597. }
  32598. }
  32599. if (this.normals) {
  32600. var normal = BABYLON.Vector3.Zero();
  32601. for (index = 0; index < this.normals.length; index += 3) {
  32602. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  32603. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  32604. this.normals[index] = transformed.x;
  32605. this.normals[index + 1] = transformed.y;
  32606. this.normals[index + 2] = transformed.z;
  32607. }
  32608. }
  32609. };
  32610. VertexData.prototype.merge = function (other) {
  32611. if (other.indices) {
  32612. if (!this.indices) {
  32613. this.indices = [];
  32614. }
  32615. var offset = this.positions ? this.positions.length / 3 : 0;
  32616. for (var index = 0; index < other.indices.length; index++) {
  32617. //TODO check type - if Int32Array!
  32618. this.indices.push(other.indices[index] + offset);
  32619. }
  32620. }
  32621. this.positions = this._mergeElement(this.positions, other.positions);
  32622. this.normals = this._mergeElement(this.normals, other.normals);
  32623. this.uvs = this._mergeElement(this.uvs, other.uvs);
  32624. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  32625. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  32626. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  32627. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  32628. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  32629. this.colors = this._mergeElement(this.colors, other.colors);
  32630. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  32631. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  32632. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  32633. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  32634. };
  32635. VertexData.prototype._mergeElement = function (source, other) {
  32636. if (!other)
  32637. return source;
  32638. if (!source)
  32639. return other;
  32640. var len = other.length + source.length;
  32641. var isSrcTypedArray = source instanceof Float32Array;
  32642. var isOthTypedArray = other instanceof Float32Array;
  32643. // use non-loop method when the source is Float32Array
  32644. if (isSrcTypedArray) {
  32645. var ret32 = new Float32Array(len);
  32646. ret32.set(source);
  32647. ret32.set(other, source.length);
  32648. return ret32;
  32649. }
  32650. else if (!isOthTypedArray) {
  32651. return source.concat(other);
  32652. }
  32653. else {
  32654. var ret = source.slice(0); // copy source to a separate array
  32655. for (var i = 0, len = other.length; i < len; i++) {
  32656. ret.push(other[i]);
  32657. }
  32658. return ret;
  32659. }
  32660. };
  32661. VertexData.prototype.serialize = function () {
  32662. var serializationObject = this.serialize();
  32663. if (this.positions) {
  32664. serializationObject.positions = this.positions;
  32665. }
  32666. if (this.normals) {
  32667. serializationObject.normals = this.normals;
  32668. }
  32669. if (this.uvs) {
  32670. serializationObject.uvs = this.uvs;
  32671. }
  32672. if (this.uvs2) {
  32673. serializationObject.uvs2 = this.uvs2;
  32674. }
  32675. if (this.uvs3) {
  32676. serializationObject.uvs3 = this.uvs3;
  32677. }
  32678. if (this.uvs4) {
  32679. serializationObject.uvs4 = this.uvs4;
  32680. }
  32681. if (this.uvs5) {
  32682. serializationObject.uvs5 = this.uvs5;
  32683. }
  32684. if (this.uvs6) {
  32685. serializationObject.uvs6 = this.uvs6;
  32686. }
  32687. if (this.colors) {
  32688. serializationObject.colors = this.colors;
  32689. }
  32690. if (this.matricesIndices) {
  32691. serializationObject.matricesIndices = this.matricesIndices;
  32692. serializationObject.matricesIndices._isExpanded = true;
  32693. }
  32694. if (this.matricesWeights) {
  32695. serializationObject.matricesWeights = this.matricesWeights;
  32696. }
  32697. if (this.matricesIndicesExtra) {
  32698. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  32699. serializationObject.matricesIndicesExtra._isExpanded = true;
  32700. }
  32701. if (this.matricesWeightsExtra) {
  32702. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  32703. }
  32704. serializationObject.indices = this.indices;
  32705. return serializationObject;
  32706. };
  32707. // Statics
  32708. VertexData.ExtractFromMesh = function (mesh, copyWhenShared) {
  32709. return VertexData._ExtractFrom(mesh, copyWhenShared);
  32710. };
  32711. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared) {
  32712. return VertexData._ExtractFrom(geometry, copyWhenShared);
  32713. };
  32714. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared) {
  32715. var result = new VertexData();
  32716. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32717. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared);
  32718. }
  32719. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32720. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared);
  32721. }
  32722. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32723. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared);
  32724. }
  32725. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  32726. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared);
  32727. }
  32728. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  32729. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared);
  32730. }
  32731. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  32732. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared);
  32733. }
  32734. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  32735. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared);
  32736. }
  32737. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  32738. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared);
  32739. }
  32740. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  32741. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared);
  32742. }
  32743. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  32744. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared);
  32745. }
  32746. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  32747. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared);
  32748. }
  32749. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  32750. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared);
  32751. }
  32752. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  32753. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared);
  32754. }
  32755. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  32756. return result;
  32757. };
  32758. VertexData.CreateRibbon = function (options) {
  32759. var pathArray = options.pathArray;
  32760. var closeArray = options.closeArray || false;
  32761. var closePath = options.closePath || false;
  32762. var invertUV = options.invertUV || false;
  32763. var defaultOffset = Math.floor(pathArray[0].length / 2);
  32764. var offset = options.offset || defaultOffset;
  32765. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  32766. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32767. var positions = [];
  32768. var indices = [];
  32769. var normals = [];
  32770. var uvs = [];
  32771. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  32772. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  32773. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  32774. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  32775. var minlg; // minimal length among all paths from pathArray
  32776. var lg = []; // array of path lengths : nb of vertex per path
  32777. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  32778. var p; // path iterator
  32779. var i; // point iterator
  32780. var j; // point iterator
  32781. // if single path in pathArray
  32782. if (pathArray.length < 2) {
  32783. var ar1 = [];
  32784. var ar2 = [];
  32785. for (i = 0; i < pathArray[0].length - offset; i++) {
  32786. ar1.push(pathArray[0][i]);
  32787. ar2.push(pathArray[0][i + offset]);
  32788. }
  32789. pathArray = [ar1, ar2];
  32790. }
  32791. // positions and horizontal distances (u)
  32792. var idc = 0;
  32793. var closePathCorr = (closePath) ? 1 : 0;
  32794. var path;
  32795. var l;
  32796. minlg = pathArray[0].length;
  32797. var vectlg;
  32798. var dist;
  32799. for (p = 0; p < pathArray.length; p++) {
  32800. uTotalDistance[p] = 0;
  32801. us[p] = [0];
  32802. path = pathArray[p];
  32803. l = path.length;
  32804. minlg = (minlg < l) ? minlg : l;
  32805. j = 0;
  32806. while (j < l) {
  32807. positions.push(path[j].x, path[j].y, path[j].z);
  32808. if (j > 0) {
  32809. vectlg = path[j].subtract(path[j - 1]).length();
  32810. dist = vectlg + uTotalDistance[p];
  32811. us[p].push(dist);
  32812. uTotalDistance[p] = dist;
  32813. }
  32814. j++;
  32815. }
  32816. if (closePath) {
  32817. j--;
  32818. positions.push(path[0].x, path[0].y, path[0].z);
  32819. vectlg = path[j].subtract(path[0]).length();
  32820. dist = vectlg + uTotalDistance[p];
  32821. us[p].push(dist);
  32822. uTotalDistance[p] = dist;
  32823. }
  32824. lg[p] = l + closePathCorr;
  32825. idx[p] = idc;
  32826. idc += (l + closePathCorr);
  32827. }
  32828. // vertical distances (v)
  32829. var path1;
  32830. var path2;
  32831. var vertex1;
  32832. var vertex2;
  32833. for (i = 0; i < minlg + closePathCorr; i++) {
  32834. vTotalDistance[i] = 0;
  32835. vs[i] = [0];
  32836. for (p = 0; p < pathArray.length - 1; p++) {
  32837. path1 = pathArray[p];
  32838. path2 = pathArray[p + 1];
  32839. if (i === minlg) {
  32840. vertex1 = path1[0];
  32841. vertex2 = path2[0];
  32842. }
  32843. else {
  32844. vertex1 = path1[i];
  32845. vertex2 = path2[i];
  32846. }
  32847. vectlg = vertex2.subtract(vertex1).length();
  32848. dist = vectlg + vTotalDistance[i];
  32849. vs[i].push(dist);
  32850. vTotalDistance[i] = dist;
  32851. }
  32852. if (closeArray) {
  32853. path1 = pathArray[p];
  32854. path2 = pathArray[0];
  32855. if (i === minlg) {
  32856. vertex2 = path2[0];
  32857. }
  32858. vectlg = vertex2.subtract(vertex1).length();
  32859. dist = vectlg + vTotalDistance[i];
  32860. vTotalDistance[i] = dist;
  32861. }
  32862. }
  32863. // uvs
  32864. var u;
  32865. var v;
  32866. for (p = 0; p < pathArray.length; p++) {
  32867. for (i = 0; i < minlg + closePathCorr; i++) {
  32868. u = us[p][i] / uTotalDistance[p];
  32869. v = vs[i][p] / vTotalDistance[i];
  32870. if (invertUV) {
  32871. uvs.push(v, u);
  32872. }
  32873. else {
  32874. uvs.push(u, v);
  32875. }
  32876. }
  32877. }
  32878. // indices
  32879. p = 0; // path index
  32880. var pi = 0; // positions array index
  32881. var l1 = lg[p] - 1; // path1 length
  32882. var l2 = lg[p + 1] - 1; // path2 length
  32883. var min = (l1 < l2) ? l1 : l2; // current path stop index
  32884. var shft = idx[1] - idx[0]; // shift
  32885. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  32886. while (pi <= min && p < path1nb) {
  32887. // 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
  32888. indices.push(pi, pi + shft, pi + 1);
  32889. indices.push(pi + shft + 1, pi + 1, pi + shft);
  32890. pi += 1;
  32891. if (pi === min) {
  32892. p++;
  32893. if (p === lg.length - 1) {
  32894. shft = idx[0] - idx[p];
  32895. l1 = lg[p] - 1;
  32896. l2 = lg[0] - 1;
  32897. }
  32898. else {
  32899. shft = idx[p + 1] - idx[p];
  32900. l1 = lg[p] - 1;
  32901. l2 = lg[p + 1] - 1;
  32902. }
  32903. pi = idx[p];
  32904. min = (l1 < l2) ? l1 + pi : l2 + pi;
  32905. }
  32906. }
  32907. // normals
  32908. VertexData.ComputeNormals(positions, indices, normals);
  32909. if (closePath) {
  32910. var indexFirst = 0;
  32911. var indexLast = 0;
  32912. for (p = 0; p < pathArray.length; p++) {
  32913. indexFirst = idx[p] * 3;
  32914. if (p + 1 < pathArray.length) {
  32915. indexLast = (idx[p + 1] - 1) * 3;
  32916. }
  32917. else {
  32918. indexLast = normals.length - 3;
  32919. }
  32920. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  32921. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  32922. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  32923. normals[indexLast] = normals[indexFirst];
  32924. normals[indexLast + 1] = normals[indexFirst + 1];
  32925. normals[indexLast + 2] = normals[indexFirst + 2];
  32926. }
  32927. }
  32928. // sides
  32929. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  32930. // Result
  32931. var vertexData = new VertexData();
  32932. vertexData.indices = indices;
  32933. vertexData.positions = positions;
  32934. vertexData.normals = normals;
  32935. vertexData.uvs = uvs;
  32936. if (closePath) {
  32937. vertexData._idx = idx;
  32938. }
  32939. return vertexData;
  32940. };
  32941. VertexData.CreateBox = function (options) {
  32942. var normalsSource = [
  32943. new BABYLON.Vector3(0, 0, 1),
  32944. new BABYLON.Vector3(0, 0, -1),
  32945. new BABYLON.Vector3(1, 0, 0),
  32946. new BABYLON.Vector3(-1, 0, 0),
  32947. new BABYLON.Vector3(0, 1, 0),
  32948. new BABYLON.Vector3(0, -1, 0)
  32949. ];
  32950. var indices = [];
  32951. var positions = [];
  32952. var normals = [];
  32953. var uvs = [];
  32954. var width = options.width || options.size || 1;
  32955. var height = options.height || options.size || 1;
  32956. var depth = options.depth || options.size || 1;
  32957. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  32958. var faceUV = options.faceUV || new Array(6);
  32959. var faceColors = options.faceColors;
  32960. var colors = [];
  32961. // default face colors and UV if undefined
  32962. for (var f = 0; f < 6; f++) {
  32963. if (faceUV[f] === undefined) {
  32964. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  32965. }
  32966. if (faceColors && faceColors[f] === undefined) {
  32967. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  32968. }
  32969. }
  32970. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  32971. // Create each face in turn.
  32972. for (var index = 0; index < normalsSource.length; index++) {
  32973. var normal = normalsSource[index];
  32974. // Get two vectors perpendicular to the face normal and to each other.
  32975. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  32976. var side2 = BABYLON.Vector3.Cross(normal, side1);
  32977. // Six indices (two triangles) per face.
  32978. var verticesLength = positions.length / 3;
  32979. indices.push(verticesLength);
  32980. indices.push(verticesLength + 1);
  32981. indices.push(verticesLength + 2);
  32982. indices.push(verticesLength);
  32983. indices.push(verticesLength + 2);
  32984. indices.push(verticesLength + 3);
  32985. // Four vertices per face.
  32986. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  32987. positions.push(vertex.x, vertex.y, vertex.z);
  32988. normals.push(normal.x, normal.y, normal.z);
  32989. uvs.push(faceUV[index].z, faceUV[index].w);
  32990. if (faceColors) {
  32991. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32992. }
  32993. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  32994. positions.push(vertex.x, vertex.y, vertex.z);
  32995. normals.push(normal.x, normal.y, normal.z);
  32996. uvs.push(faceUV[index].x, faceUV[index].w);
  32997. if (faceColors) {
  32998. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  32999. }
  33000. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  33001. positions.push(vertex.x, vertex.y, vertex.z);
  33002. normals.push(normal.x, normal.y, normal.z);
  33003. uvs.push(faceUV[index].x, faceUV[index].y);
  33004. if (faceColors) {
  33005. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33006. }
  33007. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  33008. positions.push(vertex.x, vertex.y, vertex.z);
  33009. normals.push(normal.x, normal.y, normal.z);
  33010. uvs.push(faceUV[index].z, faceUV[index].y);
  33011. if (faceColors) {
  33012. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  33013. }
  33014. }
  33015. // sides
  33016. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33017. // Result
  33018. var vertexData = new VertexData();
  33019. vertexData.indices = indices;
  33020. vertexData.positions = positions;
  33021. vertexData.normals = normals;
  33022. vertexData.uvs = uvs;
  33023. if (faceColors) {
  33024. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  33025. vertexData.colors = totalColors;
  33026. }
  33027. return vertexData;
  33028. };
  33029. VertexData.CreateSphere = function (options) {
  33030. var segments = options.segments || 32;
  33031. var diameterX = options.diameterX || options.diameter || 1;
  33032. var diameterY = options.diameterY || options.diameter || 1;
  33033. var diameterZ = options.diameterZ || options.diameter || 1;
  33034. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33035. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  33036. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33037. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  33038. var totalZRotationSteps = 2 + segments;
  33039. var totalYRotationSteps = 2 * totalZRotationSteps;
  33040. var indices = [];
  33041. var positions = [];
  33042. var normals = [];
  33043. var uvs = [];
  33044. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  33045. var normalizedZ = zRotationStep / totalZRotationSteps;
  33046. var angleZ = normalizedZ * Math.PI * slice;
  33047. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  33048. var normalizedY = yRotationStep / totalYRotationSteps;
  33049. var angleY = normalizedY * Math.PI * 2 * arc;
  33050. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  33051. var rotationY = BABYLON.Matrix.RotationY(angleY);
  33052. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  33053. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  33054. var vertex = complete.multiply(radius);
  33055. var normal = complete.divide(radius).normalize();
  33056. positions.push(vertex.x, vertex.y, vertex.z);
  33057. normals.push(normal.x, normal.y, normal.z);
  33058. uvs.push(normalizedY, normalizedZ);
  33059. }
  33060. if (zRotationStep > 0) {
  33061. var verticesCount = positions.length / 3;
  33062. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  33063. indices.push((firstIndex));
  33064. indices.push((firstIndex + 1));
  33065. indices.push(firstIndex + totalYRotationSteps + 1);
  33066. indices.push((firstIndex + totalYRotationSteps + 1));
  33067. indices.push((firstIndex + 1));
  33068. indices.push((firstIndex + totalYRotationSteps + 2));
  33069. }
  33070. }
  33071. }
  33072. // Sides
  33073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33074. // Result
  33075. var vertexData = new VertexData();
  33076. vertexData.indices = indices;
  33077. vertexData.positions = positions;
  33078. vertexData.normals = normals;
  33079. vertexData.uvs = uvs;
  33080. return vertexData;
  33081. };
  33082. // Cylinder and cone
  33083. VertexData.CreateCylinder = function (options) {
  33084. var height = options.height || 2;
  33085. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  33086. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  33087. var tessellation = options.tessellation || 24;
  33088. var subdivisions = options.subdivisions || 1;
  33089. var hasRings = options.hasRings;
  33090. var enclose = options.enclose;
  33091. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33092. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33093. var faceUV = options.faceUV || new Array(3);
  33094. var faceColors = options.faceColors;
  33095. // default face colors and UV if undefined
  33096. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  33097. var ringNb = (hasRings) ? subdivisions : 1;
  33098. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  33099. var f;
  33100. for (f = 0; f < surfaceNb; f++) {
  33101. if (faceColors && faceColors[f] === undefined) {
  33102. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33103. }
  33104. }
  33105. for (f = 0; f < surfaceNb; f++) {
  33106. if (faceUV && faceUV[f] === undefined) {
  33107. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33108. }
  33109. }
  33110. var indices = [];
  33111. var positions = [];
  33112. var normals = [];
  33113. var uvs = [];
  33114. var colors = [];
  33115. var angle_step = Math.PI * 2 * arc / tessellation;
  33116. var angle;
  33117. var h;
  33118. var radius;
  33119. var tan = (diameterBottom - diameterTop) / 2 / height;
  33120. var ringVertex = BABYLON.Vector3.Zero();
  33121. var ringNormal = BABYLON.Vector3.Zero();
  33122. var ringFirstVertex = BABYLON.Vector3.Zero();
  33123. var ringFirstNormal = BABYLON.Vector3.Zero();
  33124. var quadNormal = BABYLON.Vector3.Zero();
  33125. var Y = BABYLON.Axis.Y;
  33126. // positions, normals, uvs
  33127. var i;
  33128. var j;
  33129. var r;
  33130. var ringIdx = 1;
  33131. var s = 1; // surface index
  33132. var cs = 0;
  33133. var v = 0;
  33134. for (i = 0; i <= subdivisions; i++) {
  33135. h = i / subdivisions;
  33136. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  33137. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  33138. for (r = 0; r < ringIdx; r++) {
  33139. if (hasRings) {
  33140. s += r;
  33141. }
  33142. if (enclose) {
  33143. s += 2 * r;
  33144. }
  33145. for (j = 0; j <= tessellation; j++) {
  33146. angle = j * angle_step;
  33147. // position
  33148. ringVertex.x = Math.cos(-angle) * radius;
  33149. ringVertex.y = -height / 2 + h * height;
  33150. ringVertex.z = Math.sin(-angle) * radius;
  33151. // normal
  33152. if (diameterTop === 0 && i === subdivisions) {
  33153. // if no top cap, reuse former normals
  33154. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  33155. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  33156. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  33157. }
  33158. else {
  33159. ringNormal.x = ringVertex.x;
  33160. ringNormal.z = ringVertex.z;
  33161. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  33162. ringNormal.normalize();
  33163. }
  33164. // keep first ring vertex values for enclose
  33165. if (j === 0) {
  33166. ringFirstVertex.copyFrom(ringVertex);
  33167. ringFirstNormal.copyFrom(ringNormal);
  33168. }
  33169. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33170. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  33171. if (hasRings) {
  33172. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  33173. }
  33174. else {
  33175. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  33176. }
  33177. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  33178. if (faceColors) {
  33179. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  33180. }
  33181. }
  33182. // if enclose, add four vertices and their dedicated normals
  33183. if (arc !== 1 && enclose) {
  33184. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  33185. positions.push(0, ringVertex.y, 0);
  33186. positions.push(0, ringVertex.y, 0);
  33187. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  33188. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  33189. quadNormal.normalize();
  33190. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33191. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  33192. quadNormal.normalize();
  33193. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  33194. if (hasRings) {
  33195. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  33196. }
  33197. else {
  33198. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  33199. }
  33200. uvs.push(faceUV[s + 1].x, v);
  33201. uvs.push(faceUV[s + 1].z, v);
  33202. if (hasRings) {
  33203. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  33204. }
  33205. else {
  33206. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  33207. }
  33208. uvs.push(faceUV[s + 2].x, v);
  33209. uvs.push(faceUV[s + 2].z, v);
  33210. if (faceColors) {
  33211. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33212. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  33213. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33214. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  33215. }
  33216. }
  33217. if (cs !== s) {
  33218. cs = s;
  33219. }
  33220. }
  33221. }
  33222. // indices
  33223. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  33224. var s;
  33225. i = 0;
  33226. for (s = 0; s < subdivisions; s++) {
  33227. for (j = 0; j < tessellation; j++) {
  33228. var i0 = i * (e + 1) + j;
  33229. var i1 = (i + 1) * (e + 1) + j;
  33230. var i2 = i * (e + 1) + (j + 1);
  33231. var i3 = (i + 1) * (e + 1) + (j + 1);
  33232. indices.push(i0, i1, i2);
  33233. indices.push(i3, i2, i1);
  33234. }
  33235. if (arc !== 1 && enclose) {
  33236. indices.push(i0 + 2, i1 + 2, i2 + 2);
  33237. indices.push(i3 + 2, i2 + 2, i1 + 2);
  33238. indices.push(i0 + 4, i1 + 4, i2 + 4);
  33239. indices.push(i3 + 4, i2 + 4, i1 + 4);
  33240. }
  33241. i = (hasRings) ? (i + 2) : (i + 1);
  33242. }
  33243. // Caps
  33244. var createCylinderCap = function (isTop) {
  33245. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  33246. if (radius === 0) {
  33247. return;
  33248. }
  33249. // Cap positions, normals & uvs
  33250. var angle;
  33251. var circleVector;
  33252. var i;
  33253. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  33254. var c;
  33255. if (faceColors) {
  33256. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  33257. }
  33258. // cap center
  33259. var vbase = positions.length / 3;
  33260. var offset = isTop ? height / 2 : -height / 2;
  33261. var center = new BABYLON.Vector3(0, offset, 0);
  33262. positions.push(center.x, center.y, center.z);
  33263. normals.push(0, isTop ? 1 : -1, 0);
  33264. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  33265. if (faceColors) {
  33266. colors.push(c.r, c.g, c.b, c.a);
  33267. }
  33268. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  33269. for (i = 0; i <= tessellation; i++) {
  33270. angle = Math.PI * 2 * i * arc / tessellation;
  33271. var cos = Math.cos(-angle);
  33272. var sin = Math.sin(-angle);
  33273. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  33274. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  33275. positions.push(circleVector.x, circleVector.y, circleVector.z);
  33276. normals.push(0, isTop ? 1 : -1, 0);
  33277. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  33278. if (faceColors) {
  33279. colors.push(c.r, c.g, c.b, c.a);
  33280. }
  33281. }
  33282. // Cap indices
  33283. for (i = 0; i < tessellation; i++) {
  33284. if (!isTop) {
  33285. indices.push(vbase);
  33286. indices.push(vbase + (i + 1));
  33287. indices.push(vbase + (i + 2));
  33288. }
  33289. else {
  33290. indices.push(vbase);
  33291. indices.push(vbase + (i + 2));
  33292. indices.push(vbase + (i + 1));
  33293. }
  33294. }
  33295. };
  33296. // add caps to geometry
  33297. createCylinderCap(false);
  33298. createCylinderCap(true);
  33299. // Sides
  33300. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33301. var vertexData = new VertexData();
  33302. vertexData.indices = indices;
  33303. vertexData.positions = positions;
  33304. vertexData.normals = normals;
  33305. vertexData.uvs = uvs;
  33306. if (faceColors) {
  33307. vertexData.colors = colors;
  33308. }
  33309. return vertexData;
  33310. };
  33311. VertexData.CreateTorus = function (options) {
  33312. var indices = [];
  33313. var positions = [];
  33314. var normals = [];
  33315. var uvs = [];
  33316. var diameter = options.diameter || 1;
  33317. var thickness = options.thickness || 0.5;
  33318. var tessellation = options.tessellation || 16;
  33319. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33320. var stride = tessellation + 1;
  33321. for (var i = 0; i <= tessellation; i++) {
  33322. var u = i / tessellation;
  33323. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  33324. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  33325. for (var j = 0; j <= tessellation; j++) {
  33326. var v = 1 - j / tessellation;
  33327. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  33328. var dx = Math.cos(innerAngle);
  33329. var dy = Math.sin(innerAngle);
  33330. // Create a vertex.
  33331. var normal = new BABYLON.Vector3(dx, dy, 0);
  33332. var position = normal.scale(thickness / 2);
  33333. var textureCoordinate = new BABYLON.Vector2(u, v);
  33334. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  33335. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  33336. positions.push(position.x, position.y, position.z);
  33337. normals.push(normal.x, normal.y, normal.z);
  33338. uvs.push(textureCoordinate.x, textureCoordinate.y);
  33339. // And create indices for two triangles.
  33340. var nextI = (i + 1) % stride;
  33341. var nextJ = (j + 1) % stride;
  33342. indices.push(i * stride + j);
  33343. indices.push(i * stride + nextJ);
  33344. indices.push(nextI * stride + j);
  33345. indices.push(i * stride + nextJ);
  33346. indices.push(nextI * stride + nextJ);
  33347. indices.push(nextI * stride + j);
  33348. }
  33349. }
  33350. // Sides
  33351. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33352. // Result
  33353. var vertexData = new VertexData();
  33354. vertexData.indices = indices;
  33355. vertexData.positions = positions;
  33356. vertexData.normals = normals;
  33357. vertexData.uvs = uvs;
  33358. return vertexData;
  33359. };
  33360. VertexData.CreateLineSystem = function (options) {
  33361. var indices = [];
  33362. var positions = [];
  33363. var lines = options.lines;
  33364. var idx = 0;
  33365. for (var l = 0; l < lines.length; l++) {
  33366. var points = lines[l];
  33367. for (var index = 0; index < points.length; index++) {
  33368. positions.push(points[index].x, points[index].y, points[index].z);
  33369. if (index > 0) {
  33370. indices.push(idx - 1);
  33371. indices.push(idx);
  33372. }
  33373. idx++;
  33374. }
  33375. }
  33376. var vertexData = new VertexData();
  33377. vertexData.indices = indices;
  33378. vertexData.positions = positions;
  33379. return vertexData;
  33380. };
  33381. VertexData.CreateDashedLines = function (options) {
  33382. var dashSize = options.dashSize || 3;
  33383. var gapSize = options.gapSize || 1;
  33384. var dashNb = options.dashNb || 200;
  33385. var points = options.points;
  33386. var positions = new Array();
  33387. var indices = new Array();
  33388. var curvect = BABYLON.Vector3.Zero();
  33389. var lg = 0;
  33390. var nb = 0;
  33391. var shft = 0;
  33392. var dashshft = 0;
  33393. var curshft = 0;
  33394. var idx = 0;
  33395. var i = 0;
  33396. for (i = 0; i < points.length - 1; i++) {
  33397. points[i + 1].subtractToRef(points[i], curvect);
  33398. lg += curvect.length();
  33399. }
  33400. shft = lg / dashNb;
  33401. dashshft = dashSize * shft / (dashSize + gapSize);
  33402. for (i = 0; i < points.length - 1; i++) {
  33403. points[i + 1].subtractToRef(points[i], curvect);
  33404. nb = Math.floor(curvect.length() / shft);
  33405. curvect.normalize();
  33406. for (var j = 0; j < nb; j++) {
  33407. curshft = shft * j;
  33408. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  33409. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  33410. indices.push(idx, idx + 1);
  33411. idx += 2;
  33412. }
  33413. }
  33414. // Result
  33415. var vertexData = new VertexData();
  33416. vertexData.positions = positions;
  33417. vertexData.indices = indices;
  33418. return vertexData;
  33419. };
  33420. VertexData.CreateGround = function (options) {
  33421. var indices = [];
  33422. var positions = [];
  33423. var normals = [];
  33424. var uvs = [];
  33425. var row, col;
  33426. var width = options.width || 1;
  33427. var height = options.height || 1;
  33428. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  33429. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  33430. for (row = 0; row <= subdivisionsY; row++) {
  33431. for (col = 0; col <= subdivisionsX; col++) {
  33432. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  33433. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33434. positions.push(position.x, position.y, position.z);
  33435. normals.push(normal.x, normal.y, normal.z);
  33436. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsX);
  33437. }
  33438. }
  33439. for (row = 0; row < subdivisionsY; row++) {
  33440. for (col = 0; col < subdivisionsX; col++) {
  33441. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33442. indices.push(col + 1 + row * (subdivisionsX + 1));
  33443. indices.push(col + row * (subdivisionsX + 1));
  33444. indices.push(col + (row + 1) * (subdivisionsX + 1));
  33445. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  33446. indices.push(col + row * (subdivisionsX + 1));
  33447. }
  33448. }
  33449. // Result
  33450. var vertexData = new VertexData();
  33451. vertexData.indices = indices;
  33452. vertexData.positions = positions;
  33453. vertexData.normals = normals;
  33454. vertexData.uvs = uvs;
  33455. return vertexData;
  33456. };
  33457. VertexData.CreateTiledGround = function (options) {
  33458. var xmin = options.xmin || -1.0;
  33459. var zmin = options.zmin || -1.0;
  33460. var xmax = options.xmax || 1.0;
  33461. var zmax = options.zmax || 1.0;
  33462. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  33463. var precision = options.precision || { w: 1, h: 1 };
  33464. var indices = [];
  33465. var positions = [];
  33466. var normals = [];
  33467. var uvs = [];
  33468. var row, col, tileRow, tileCol;
  33469. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  33470. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  33471. precision.w = (precision.w < 1) ? 1 : precision.w;
  33472. precision.h = (precision.h < 1) ? 1 : precision.h;
  33473. var tileSize = {
  33474. 'w': (xmax - xmin) / subdivisions.w,
  33475. 'h': (zmax - zmin) / subdivisions.h
  33476. };
  33477. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  33478. // Indices
  33479. var base = positions.length / 3;
  33480. var rowLength = precision.w + 1;
  33481. for (row = 0; row < precision.h; row++) {
  33482. for (col = 0; col < precision.w; col++) {
  33483. var square = [
  33484. base + col + row * rowLength,
  33485. base + (col + 1) + row * rowLength,
  33486. base + (col + 1) + (row + 1) * rowLength,
  33487. base + col + (row + 1) * rowLength
  33488. ];
  33489. indices.push(square[1]);
  33490. indices.push(square[2]);
  33491. indices.push(square[3]);
  33492. indices.push(square[0]);
  33493. indices.push(square[1]);
  33494. indices.push(square[3]);
  33495. }
  33496. }
  33497. // Position, normals and uvs
  33498. var position = BABYLON.Vector3.Zero();
  33499. var normal = new BABYLON.Vector3(0, 1.0, 0);
  33500. for (row = 0; row <= precision.h; row++) {
  33501. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  33502. for (col = 0; col <= precision.w; col++) {
  33503. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  33504. position.y = 0;
  33505. positions.push(position.x, position.y, position.z);
  33506. normals.push(normal.x, normal.y, normal.z);
  33507. uvs.push(col / precision.w, row / precision.h);
  33508. }
  33509. }
  33510. }
  33511. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  33512. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  33513. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  33514. }
  33515. }
  33516. // Result
  33517. var vertexData = new VertexData();
  33518. vertexData.indices = indices;
  33519. vertexData.positions = positions;
  33520. vertexData.normals = normals;
  33521. vertexData.uvs = uvs;
  33522. return vertexData;
  33523. };
  33524. VertexData.CreateGroundFromHeightMap = function (options) {
  33525. var indices = [];
  33526. var positions = [];
  33527. var normals = [];
  33528. var uvs = [];
  33529. var row, col;
  33530. // Vertices
  33531. for (row = 0; row <= options.subdivisions; row++) {
  33532. for (col = 0; col <= options.subdivisions; col++) {
  33533. 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));
  33534. // Compute height
  33535. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  33536. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  33537. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  33538. var r = options.buffer[pos] / 255.0;
  33539. var g = options.buffer[pos + 1] / 255.0;
  33540. var b = options.buffer[pos + 2] / 255.0;
  33541. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33542. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  33543. // Add vertex
  33544. positions.push(position.x, position.y, position.z);
  33545. normals.push(0, 0, 0);
  33546. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  33547. }
  33548. }
  33549. // Indices
  33550. for (row = 0; row < options.subdivisions; row++) {
  33551. for (col = 0; col < options.subdivisions; col++) {
  33552. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33553. indices.push(col + 1 + row * (options.subdivisions + 1));
  33554. indices.push(col + row * (options.subdivisions + 1));
  33555. indices.push(col + (row + 1) * (options.subdivisions + 1));
  33556. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  33557. indices.push(col + row * (options.subdivisions + 1));
  33558. }
  33559. }
  33560. // Normals
  33561. VertexData.ComputeNormals(positions, indices, normals);
  33562. // Result
  33563. var vertexData = new VertexData();
  33564. vertexData.indices = indices;
  33565. vertexData.positions = positions;
  33566. vertexData.normals = normals;
  33567. vertexData.uvs = uvs;
  33568. return vertexData;
  33569. };
  33570. VertexData.CreatePlane = function (options) {
  33571. var indices = [];
  33572. var positions = [];
  33573. var normals = [];
  33574. var uvs = [];
  33575. var width = options.width || options.size || 1;
  33576. var height = options.height || options.size || 1;
  33577. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33578. // Vertices
  33579. var halfWidth = width / 2.0;
  33580. var halfHeight = height / 2.0;
  33581. positions.push(-halfWidth, -halfHeight, 0);
  33582. normals.push(0, 0, -1.0);
  33583. uvs.push(0.0, 0.0);
  33584. positions.push(halfWidth, -halfHeight, 0);
  33585. normals.push(0, 0, -1.0);
  33586. uvs.push(1.0, 0.0);
  33587. positions.push(halfWidth, halfHeight, 0);
  33588. normals.push(0, 0, -1.0);
  33589. uvs.push(1.0, 1.0);
  33590. positions.push(-halfWidth, halfHeight, 0);
  33591. normals.push(0, 0, -1.0);
  33592. uvs.push(0.0, 1.0);
  33593. // Indices
  33594. indices.push(0);
  33595. indices.push(1);
  33596. indices.push(2);
  33597. indices.push(0);
  33598. indices.push(2);
  33599. indices.push(3);
  33600. // Sides
  33601. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33602. // Result
  33603. var vertexData = new VertexData();
  33604. vertexData.indices = indices;
  33605. vertexData.positions = positions;
  33606. vertexData.normals = normals;
  33607. vertexData.uvs = uvs;
  33608. return vertexData;
  33609. };
  33610. VertexData.CreateDisc = function (options) {
  33611. var positions = [];
  33612. var indices = [];
  33613. var normals = [];
  33614. var uvs = [];
  33615. var radius = options.radius || 0.5;
  33616. var tessellation = options.tessellation || 64;
  33617. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  33618. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33619. // positions and uvs
  33620. positions.push(0, 0, 0); // disc center first
  33621. uvs.push(0.5, 0.5);
  33622. var theta = Math.PI * 2 * arc;
  33623. var step = theta / tessellation;
  33624. for (var a = 0; a < theta; a += step) {
  33625. var x = Math.cos(a);
  33626. var y = Math.sin(a);
  33627. var u = (x + 1) / 2;
  33628. var v = (1 - y) / 2;
  33629. positions.push(radius * x, radius * y, 0);
  33630. uvs.push(u, v);
  33631. }
  33632. if (arc === 1) {
  33633. positions.push(positions[3], positions[4], positions[5]); // close the circle
  33634. uvs.push(uvs[2], uvs[3]);
  33635. }
  33636. //indices
  33637. var vertexNb = positions.length / 3;
  33638. for (var i = 1; i < vertexNb - 1; i++) {
  33639. indices.push(i + 1, 0, i);
  33640. }
  33641. // result
  33642. VertexData.ComputeNormals(positions, indices, normals);
  33643. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33644. var vertexData = new VertexData();
  33645. vertexData.indices = indices;
  33646. vertexData.positions = positions;
  33647. vertexData.normals = normals;
  33648. vertexData.uvs = uvs;
  33649. return vertexData;
  33650. };
  33651. VertexData.CreateIcoSphere = function (options) {
  33652. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33653. var radius = options.radius || 1;
  33654. var flat = (options.flat === undefined) ? true : options.flat;
  33655. var subdivisions = options.subdivisions || 4;
  33656. var radiusX = options.radiusX || radius;
  33657. var radiusY = options.radiusY || radius;
  33658. var radiusZ = options.radiusZ || radius;
  33659. var t = (1 + Math.sqrt(5)) / 2;
  33660. // 12 vertex x,y,z
  33661. var ico_vertices = [
  33662. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  33663. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  33664. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  33665. ];
  33666. // index of 3 vertex makes a face of icopshere
  33667. var ico_indices = [
  33668. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  33669. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  33670. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  33671. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  33672. ];
  33673. // vertex for uv have aliased position, not for UV
  33674. var vertices_unalias_id = [
  33675. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  33676. // vertex alias
  33677. 0,
  33678. 2,
  33679. 3,
  33680. 3,
  33681. 3,
  33682. 4,
  33683. 7,
  33684. 8,
  33685. 9,
  33686. 9,
  33687. 10,
  33688. 11 // 23: B + 12
  33689. ];
  33690. // uv as integer step (not pixels !)
  33691. var ico_vertexuv = [
  33692. 5, 1, 3, 1, 6, 4, 0, 0,
  33693. 5, 3, 4, 2, 2, 2, 4, 0,
  33694. 2, 0, 1, 1, 6, 0, 6, 2,
  33695. // vertex alias (for same vertex on different faces)
  33696. 0, 4,
  33697. 3, 3,
  33698. 4, 4,
  33699. 3, 1,
  33700. 4, 2,
  33701. 4, 4,
  33702. 0, 2,
  33703. 1, 1,
  33704. 2, 2,
  33705. 3, 3,
  33706. 1, 3,
  33707. 2, 4 // 23: B + 12
  33708. ];
  33709. // Vertices[0, 1, ...9, A, B] : position on UV plane
  33710. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  33711. // First island of uv mapping
  33712. // v = 4h 3+ 2
  33713. // v = 3h 9+ 4
  33714. // v = 2h 9+ 5 B
  33715. // v = 1h 9 1 0
  33716. // v = 0h 3 8 7 A
  33717. // u = 0 1 2 3 4 5 6 *a
  33718. // Second island of uv mapping
  33719. // v = 4h 0+ B+ 4+
  33720. // v = 3h A+ 2+
  33721. // v = 2h 7+ 6 3+
  33722. // v = 1h 8+ 3+
  33723. // v = 0h
  33724. // u = 0 1 2 3 4 5 6 *a
  33725. // Face layout on texture UV mapping
  33726. // ============
  33727. // \ 4 /\ 16 / ======
  33728. // \ / \ / /\ 11 /
  33729. // \/ 7 \/ / \ /
  33730. // ======= / 10 \/
  33731. // /\ 17 /\ =======
  33732. // / \ / \ \ 15 /\
  33733. // / 8 \/ 12 \ \ / \
  33734. // ============ \/ 6 \
  33735. // \ 18 /\ ============
  33736. // \ / \ \ 5 /\ 0 /
  33737. // \/ 13 \ \ / \ /
  33738. // ======= \/ 1 \/
  33739. // =============
  33740. // /\ 19 /\ 2 /\
  33741. // / \ / \ / \
  33742. // / 14 \/ 9 \/ 3 \
  33743. // ===================
  33744. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  33745. var ustep = 138 / 1024;
  33746. var vstep = 239 / 1024;
  33747. var uoffset = 60 / 1024;
  33748. var voffset = 26 / 1024;
  33749. // Second island should have margin, not to touch the first island
  33750. // avoid any borderline artefact in pixel rounding
  33751. var island_u_offset = -40 / 1024;
  33752. var island_v_offset = +20 / 1024;
  33753. // face is either island 0 or 1 :
  33754. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  33755. var island = [
  33756. 0, 0, 0, 0, 1,
  33757. 0, 0, 1, 1, 0,
  33758. 0, 0, 1, 1, 0,
  33759. 0, 1, 1, 1, 0 // 15 - 19
  33760. ];
  33761. var indices = [];
  33762. var positions = [];
  33763. var normals = [];
  33764. var uvs = [];
  33765. var current_indice = 0;
  33766. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  33767. var face_vertex_pos = new Array(3);
  33768. var face_vertex_uv = new Array(3);
  33769. var v012;
  33770. for (v012 = 0; v012 < 3; v012++) {
  33771. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  33772. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  33773. }
  33774. // create all with normals
  33775. for (var face = 0; face < 20; face++) {
  33776. // 3 vertex per face
  33777. for (v012 = 0; v012 < 3; v012++) {
  33778. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  33779. var v_id = ico_indices[3 * face + v012];
  33780. // vertex have 3D position (x,y,z)
  33781. 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]);
  33782. // Normalize to get normal, then scale to radius
  33783. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  33784. // uv Coordinates from vertex ID
  33785. 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);
  33786. }
  33787. // Subdivide the face (interpolate pos, norm, uv)
  33788. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  33789. // - norm is linear interpolation of vertex corner normal
  33790. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  33791. // - uv is linear interpolation
  33792. //
  33793. // Topology is as below for sub-divide by 2
  33794. // vertex shown as v0,v1,v2
  33795. // interp index is i1 to progress in range [v0,v1[
  33796. // interp index is i2 to progress in range [v0,v2[
  33797. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  33798. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33799. //
  33800. //
  33801. // i2 v2
  33802. // ^ ^
  33803. // / / \
  33804. // / / \
  33805. // / / \
  33806. // / / (0,1) \
  33807. // / #---------\
  33808. // / / \ (0,0)'/ \
  33809. // / / \ / \
  33810. // / / \ / \
  33811. // / / (0,0) \ / (1,0) \
  33812. // / #---------#---------\
  33813. // v0 v1
  33814. //
  33815. // --------------------> i1
  33816. //
  33817. // interp of (i1,i2):
  33818. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  33819. // along i1 : lerp(x0,x1, i1/(S-i2))
  33820. //
  33821. // centroid of triangle is needed to get help normal computation
  33822. // (c1,c2) are used for centroid location
  33823. var interp_vertex = function (i1, i2, c1, c2) {
  33824. // vertex is interpolated from
  33825. // - face_vertex_pos[0..2]
  33826. // - face_vertex_uv[0..2]
  33827. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  33828. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  33829. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  33830. pos_interp.normalize();
  33831. var vertex_normal;
  33832. if (flat) {
  33833. // in flat mode, recalculate normal as face centroid normal
  33834. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  33835. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  33836. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  33837. }
  33838. else {
  33839. // in smooth mode, recalculate normal from each single vertex position
  33840. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  33841. }
  33842. // Vertex normal need correction due to X,Y,Z radius scaling
  33843. vertex_normal.x /= radiusX;
  33844. vertex_normal.y /= radiusY;
  33845. vertex_normal.z /= radiusZ;
  33846. vertex_normal.normalize();
  33847. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  33848. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  33849. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  33850. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  33851. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  33852. uvs.push(uv_interp.x, uv_interp.y);
  33853. // push each vertex has member of a face
  33854. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  33855. indices.push(current_indice);
  33856. current_indice++;
  33857. };
  33858. for (var i2 = 0; i2 < subdivisions; i2++) {
  33859. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  33860. // face : (i1,i2) for /\ :
  33861. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  33862. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33863. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33864. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  33865. if (i1 + i2 + 1 < subdivisions) {
  33866. // face : (i1,i2)' for \/ :
  33867. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  33868. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33869. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33870. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  33871. }
  33872. }
  33873. }
  33874. }
  33875. // Sides
  33876. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33877. // Result
  33878. var vertexData = new VertexData();
  33879. vertexData.indices = indices;
  33880. vertexData.positions = positions;
  33881. vertexData.normals = normals;
  33882. vertexData.uvs = uvs;
  33883. return vertexData;
  33884. };
  33885. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  33886. VertexData.CreatePolyhedron = function (options) {
  33887. // provided polyhedron types :
  33888. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  33889. // 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)
  33890. var polyhedra = [];
  33891. 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]] };
  33892. 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]] };
  33893. polyhedra[2] = {
  33894. 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]],
  33895. 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]]
  33896. };
  33897. polyhedra[3] = {
  33898. 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]],
  33899. 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]]
  33900. };
  33901. polyhedra[4] = {
  33902. 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]],
  33903. 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]]
  33904. };
  33905. 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]] };
  33906. 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]] };
  33907. 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]] };
  33908. 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]] };
  33909. 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]] };
  33910. 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]] };
  33911. 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]] };
  33912. 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]] };
  33913. 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]] };
  33914. polyhedra[14] = {
  33915. 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]],
  33916. 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]]
  33917. };
  33918. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  33919. var size = options.size;
  33920. var sizeX = options.sizeX || size || 1;
  33921. var sizeY = options.sizeY || size || 1;
  33922. var sizeZ = options.sizeZ || size || 1;
  33923. var data = options.custom || polyhedra[type];
  33924. var nbfaces = data.face.length;
  33925. var faceUV = options.faceUV || new Array(nbfaces);
  33926. var faceColors = options.faceColors;
  33927. var flat = (options.flat === undefined) ? true : options.flat;
  33928. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  33929. var positions = [];
  33930. var indices = [];
  33931. var normals = [];
  33932. var uvs = [];
  33933. var colors = [];
  33934. var index = 0;
  33935. var faceIdx = 0; // face cursor in the array "indexes"
  33936. var indexes = [];
  33937. var i = 0;
  33938. var f = 0;
  33939. var u, v, ang, x, y, tmp;
  33940. // default face colors and UV if undefined
  33941. if (flat) {
  33942. for (f = 0; f < nbfaces; f++) {
  33943. if (faceColors && faceColors[f] === undefined) {
  33944. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  33945. }
  33946. if (faceUV && faceUV[f] === undefined) {
  33947. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  33948. }
  33949. }
  33950. }
  33951. if (!flat) {
  33952. for (i = 0; i < data.vertex.length; i++) {
  33953. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  33954. uvs.push(0, 0);
  33955. }
  33956. for (f = 0; f < nbfaces; f++) {
  33957. for (i = 0; i < data.face[f].length - 2; i++) {
  33958. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  33959. }
  33960. }
  33961. }
  33962. else {
  33963. for (f = 0; f < nbfaces; f++) {
  33964. var fl = data.face[f].length; // number of vertices of the current face
  33965. ang = 2 * Math.PI / fl;
  33966. x = 0.5 * Math.tan(ang / 2);
  33967. y = 0.5;
  33968. // positions, uvs, colors
  33969. for (i = 0; i < fl; i++) {
  33970. // positions
  33971. 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);
  33972. indexes.push(index);
  33973. index++;
  33974. // uvs
  33975. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  33976. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  33977. uvs.push(u, v);
  33978. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  33979. y = x * Math.sin(ang) + y * Math.cos(ang);
  33980. x = tmp;
  33981. // colors
  33982. if (faceColors) {
  33983. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  33984. }
  33985. }
  33986. // indices from indexes
  33987. for (i = 0; i < fl - 2; i++) {
  33988. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  33989. }
  33990. faceIdx += fl;
  33991. }
  33992. }
  33993. VertexData.ComputeNormals(positions, indices, normals);
  33994. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  33995. var vertexData = new VertexData();
  33996. vertexData.positions = positions;
  33997. vertexData.indices = indices;
  33998. vertexData.normals = normals;
  33999. vertexData.uvs = uvs;
  34000. if (faceColors && flat) {
  34001. vertexData.colors = colors;
  34002. }
  34003. return vertexData;
  34004. };
  34005. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  34006. VertexData.CreateTorusKnot = function (options) {
  34007. var indices = [];
  34008. var positions = [];
  34009. var normals = [];
  34010. var uvs = [];
  34011. var radius = options.radius || 2;
  34012. var tube = options.tube || 0.5;
  34013. var radialSegments = options.radialSegments || 32;
  34014. var tubularSegments = options.tubularSegments || 32;
  34015. var p = options.p || 2;
  34016. var q = options.q || 3;
  34017. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34018. // Helper
  34019. var getPos = function (angle) {
  34020. var cu = Math.cos(angle);
  34021. var su = Math.sin(angle);
  34022. var quOverP = q / p * angle;
  34023. var cs = Math.cos(quOverP);
  34024. var tx = radius * (2 + cs) * 0.5 * cu;
  34025. var ty = radius * (2 + cs) * su * 0.5;
  34026. var tz = radius * Math.sin(quOverP) * 0.5;
  34027. return new BABYLON.Vector3(tx, ty, tz);
  34028. };
  34029. // Vertices
  34030. var i;
  34031. var j;
  34032. for (i = 0; i <= radialSegments; i++) {
  34033. var modI = i % radialSegments;
  34034. var u = modI / radialSegments * 2 * p * Math.PI;
  34035. var p1 = getPos(u);
  34036. var p2 = getPos(u + 0.01);
  34037. var tang = p2.subtract(p1);
  34038. var n = p2.add(p1);
  34039. var bitan = BABYLON.Vector3.Cross(tang, n);
  34040. n = BABYLON.Vector3.Cross(bitan, tang);
  34041. bitan.normalize();
  34042. n.normalize();
  34043. for (j = 0; j < tubularSegments; j++) {
  34044. var modJ = j % tubularSegments;
  34045. var v = modJ / tubularSegments * 2 * Math.PI;
  34046. var cx = -tube * Math.cos(v);
  34047. var cy = tube * Math.sin(v);
  34048. positions.push(p1.x + cx * n.x + cy * bitan.x);
  34049. positions.push(p1.y + cx * n.y + cy * bitan.y);
  34050. positions.push(p1.z + cx * n.z + cy * bitan.z);
  34051. uvs.push(i / radialSegments);
  34052. uvs.push(j / tubularSegments);
  34053. }
  34054. }
  34055. for (i = 0; i < radialSegments; i++) {
  34056. for (j = 0; j < tubularSegments; j++) {
  34057. var jNext = (j + 1) % tubularSegments;
  34058. var a = i * tubularSegments + j;
  34059. var b = (i + 1) * tubularSegments + j;
  34060. var c = (i + 1) * tubularSegments + jNext;
  34061. var d = i * tubularSegments + jNext;
  34062. indices.push(d);
  34063. indices.push(b);
  34064. indices.push(a);
  34065. indices.push(d);
  34066. indices.push(c);
  34067. indices.push(b);
  34068. }
  34069. }
  34070. // Normals
  34071. VertexData.ComputeNormals(positions, indices, normals);
  34072. // Sides
  34073. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs);
  34074. // Result
  34075. var vertexData = new VertexData();
  34076. vertexData.indices = indices;
  34077. vertexData.positions = positions;
  34078. vertexData.normals = normals;
  34079. vertexData.uvs = uvs;
  34080. return vertexData;
  34081. };
  34082. // Tools
  34083. /**
  34084. * @param {any} - positions (number[] or Float32Array)
  34085. * @param {any} - indices (number[] or Uint16Array)
  34086. * @param {any} - normals (number[] or Float32Array)
  34087. */
  34088. VertexData.ComputeNormals = function (positions, indices, normals) {
  34089. var index = 0;
  34090. var p1p2x = 0.0;
  34091. var p1p2y = 0.0;
  34092. var p1p2z = 0.0;
  34093. var p3p2x = 0.0;
  34094. var p3p2y = 0.0;
  34095. var p3p2z = 0.0;
  34096. var faceNormalx = 0.0;
  34097. var faceNormaly = 0.0;
  34098. var faceNormalz = 0.0;
  34099. var length = 0.0;
  34100. var i1 = 0;
  34101. var i2 = 0;
  34102. var i3 = 0;
  34103. for (index = 0; index < positions.length; index++) {
  34104. normals[index] = 0.0;
  34105. }
  34106. // indice triplet = 1 face
  34107. var nbFaces = indices.length / 3;
  34108. for (index = 0; index < nbFaces; index++) {
  34109. i1 = indices[index * 3]; // get the indexes of each vertex of the face
  34110. i2 = indices[index * 3 + 1];
  34111. i3 = indices[index * 3 + 2];
  34112. p1p2x = positions[i1 * 3] - positions[i2 * 3]; // compute two vectors per face
  34113. p1p2y = positions[i1 * 3 + 1] - positions[i2 * 3 + 1];
  34114. p1p2z = positions[i1 * 3 + 2] - positions[i2 * 3 + 2];
  34115. p3p2x = positions[i3 * 3] - positions[i2 * 3];
  34116. p3p2y = positions[i3 * 3 + 1] - positions[i2 * 3 + 1];
  34117. p3p2z = positions[i3 * 3 + 2] - positions[i2 * 3 + 2];
  34118. faceNormalx = p1p2y * p3p2z - p1p2z * p3p2y; // compute the face normal with cross product
  34119. faceNormaly = p1p2z * p3p2x - p1p2x * p3p2z;
  34120. faceNormalz = p1p2x * p3p2y - p1p2y * p3p2x;
  34121. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34122. length = (length === 0) ? 1.0 : length;
  34123. faceNormalx /= length; // normalize this normal
  34124. faceNormaly /= length;
  34125. faceNormalz /= length;
  34126. normals[i1 * 3] += faceNormalx; // accumulate all the normals per face
  34127. normals[i1 * 3 + 1] += faceNormaly;
  34128. normals[i1 * 3 + 2] += faceNormalz;
  34129. normals[i2 * 3] += faceNormalx;
  34130. normals[i2 * 3 + 1] += faceNormaly;
  34131. normals[i2 * 3 + 2] += faceNormalz;
  34132. normals[i3 * 3] += faceNormalx;
  34133. normals[i3 * 3 + 1] += faceNormaly;
  34134. normals[i3 * 3 + 2] += faceNormalz;
  34135. }
  34136. // last normalization of each normal
  34137. for (index = 0; index < normals.length / 3; index++) {
  34138. faceNormalx = normals[index * 3];
  34139. faceNormaly = normals[index * 3 + 1];
  34140. faceNormalz = normals[index * 3 + 2];
  34141. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  34142. length = (length === 0) ? 1.0 : length;
  34143. faceNormalx /= length;
  34144. faceNormaly /= length;
  34145. faceNormalz /= length;
  34146. normals[index * 3] = faceNormalx;
  34147. normals[index * 3 + 1] = faceNormaly;
  34148. normals[index * 3 + 2] = faceNormalz;
  34149. }
  34150. };
  34151. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs) {
  34152. var li = indices.length;
  34153. var ln = normals.length;
  34154. var i;
  34155. var n;
  34156. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  34157. switch (sideOrientation) {
  34158. case BABYLON.Mesh.FRONTSIDE:
  34159. // nothing changed
  34160. break;
  34161. case BABYLON.Mesh.BACKSIDE:
  34162. var tmp;
  34163. // indices
  34164. for (i = 0; i < li; i += 3) {
  34165. tmp = indices[i];
  34166. indices[i] = indices[i + 2];
  34167. indices[i + 2] = tmp;
  34168. }
  34169. // normals
  34170. for (n = 0; n < ln; n++) {
  34171. normals[n] = -normals[n];
  34172. }
  34173. break;
  34174. case BABYLON.Mesh.DOUBLESIDE:
  34175. // positions
  34176. var lp = positions.length;
  34177. var l = lp / 3;
  34178. for (var p = 0; p < lp; p++) {
  34179. positions[lp + p] = positions[p];
  34180. }
  34181. // indices
  34182. for (i = 0; i < li; i += 3) {
  34183. indices[i + li] = indices[i + 2] + l;
  34184. indices[i + 1 + li] = indices[i + 1] + l;
  34185. indices[i + 2 + li] = indices[i] + l;
  34186. }
  34187. // normals
  34188. for (n = 0; n < ln; n++) {
  34189. normals[ln + n] = -normals[n];
  34190. }
  34191. // uvs
  34192. var lu = uvs.length;
  34193. for (var u = 0; u < lu; u++) {
  34194. uvs[u + lu] = uvs[u];
  34195. }
  34196. break;
  34197. }
  34198. };
  34199. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  34200. var vertexData = new VertexData();
  34201. // positions
  34202. var positions = parsedVertexData.positions;
  34203. if (positions) {
  34204. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  34205. }
  34206. // normals
  34207. var normals = parsedVertexData.normals;
  34208. if (normals) {
  34209. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  34210. }
  34211. // uvs
  34212. var uvs = parsedVertexData.uvs;
  34213. if (uvs) {
  34214. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  34215. }
  34216. // uv2s
  34217. var uv2s = parsedVertexData.uv2s;
  34218. if (uv2s) {
  34219. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  34220. }
  34221. // uv3s
  34222. var uv3s = parsedVertexData.uv3s;
  34223. if (uv3s) {
  34224. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  34225. }
  34226. // uv4s
  34227. var uv4s = parsedVertexData.uv4s;
  34228. if (uv4s) {
  34229. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  34230. }
  34231. // uv5s
  34232. var uv5s = parsedVertexData.uv5s;
  34233. if (uv5s) {
  34234. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  34235. }
  34236. // uv6s
  34237. var uv6s = parsedVertexData.uv6s;
  34238. if (uv6s) {
  34239. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  34240. }
  34241. // colors
  34242. var colors = parsedVertexData.colors;
  34243. if (colors) {
  34244. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  34245. }
  34246. // matricesIndices
  34247. var matricesIndices = parsedVertexData.matricesIndices;
  34248. if (matricesIndices) {
  34249. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  34250. }
  34251. // matricesWeights
  34252. var matricesWeights = parsedVertexData.matricesWeights;
  34253. if (matricesWeights) {
  34254. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  34255. }
  34256. // indices
  34257. var indices = parsedVertexData.indices;
  34258. if (indices) {
  34259. vertexData.indices = indices;
  34260. }
  34261. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  34262. };
  34263. return VertexData;
  34264. }());
  34265. BABYLON.VertexData = VertexData;
  34266. })(BABYLON || (BABYLON = {}));
  34267. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  34268. var BABYLON;
  34269. (function (BABYLON) {
  34270. var Tags = (function () {
  34271. function Tags() {
  34272. }
  34273. Tags.EnableFor = function (obj) {
  34274. obj._tags = obj._tags || {};
  34275. obj.hasTags = function () {
  34276. return Tags.HasTags(obj);
  34277. };
  34278. obj.addTags = function (tagsString) {
  34279. return Tags.AddTagsTo(obj, tagsString);
  34280. };
  34281. obj.removeTags = function (tagsString) {
  34282. return Tags.RemoveTagsFrom(obj, tagsString);
  34283. };
  34284. obj.matchesTagsQuery = function (tagsQuery) {
  34285. return Tags.MatchesQuery(obj, tagsQuery);
  34286. };
  34287. };
  34288. Tags.DisableFor = function (obj) {
  34289. delete obj._tags;
  34290. delete obj.hasTags;
  34291. delete obj.addTags;
  34292. delete obj.removeTags;
  34293. delete obj.matchesTagsQuery;
  34294. };
  34295. Tags.HasTags = function (obj) {
  34296. if (!obj._tags) {
  34297. return false;
  34298. }
  34299. return !BABYLON.Tools.IsEmpty(obj._tags);
  34300. };
  34301. Tags.GetTags = function (obj, asString) {
  34302. if (asString === void 0) { asString = true; }
  34303. if (!obj._tags) {
  34304. return null;
  34305. }
  34306. if (asString) {
  34307. var tagsArray = [];
  34308. for (var tag in obj._tags) {
  34309. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  34310. tagsArray.push(tag);
  34311. }
  34312. }
  34313. return tagsArray.join(" ");
  34314. }
  34315. else {
  34316. return obj._tags;
  34317. }
  34318. };
  34319. // the tags 'true' and 'false' are reserved and cannot be used as tags
  34320. // a tag cannot start with '||', '&&', and '!'
  34321. // it cannot contain whitespaces
  34322. Tags.AddTagsTo = function (obj, tagsString) {
  34323. if (!tagsString) {
  34324. return;
  34325. }
  34326. if (typeof tagsString !== "string") {
  34327. return;
  34328. }
  34329. var tags = tagsString.split(" ");
  34330. tags.forEach(function (tag, index, array) {
  34331. Tags._AddTagTo(obj, tag);
  34332. });
  34333. };
  34334. Tags._AddTagTo = function (obj, tag) {
  34335. tag = tag.trim();
  34336. if (tag === "" || tag === "true" || tag === "false") {
  34337. return;
  34338. }
  34339. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  34340. return;
  34341. }
  34342. Tags.EnableFor(obj);
  34343. obj._tags[tag] = true;
  34344. };
  34345. Tags.RemoveTagsFrom = function (obj, tagsString) {
  34346. if (!Tags.HasTags(obj)) {
  34347. return;
  34348. }
  34349. var tags = tagsString.split(" ");
  34350. for (var t in tags) {
  34351. Tags._RemoveTagFrom(obj, tags[t]);
  34352. }
  34353. };
  34354. Tags._RemoveTagFrom = function (obj, tag) {
  34355. delete obj._tags[tag];
  34356. };
  34357. Tags.MatchesQuery = function (obj, tagsQuery) {
  34358. if (tagsQuery === undefined) {
  34359. return true;
  34360. }
  34361. if (tagsQuery === "") {
  34362. return Tags.HasTags(obj);
  34363. }
  34364. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  34365. };
  34366. return Tags;
  34367. }());
  34368. BABYLON.Tags = Tags;
  34369. })(BABYLON || (BABYLON = {}));
  34370. //# sourceMappingURL=babylon.tags.js.map
  34371. var BABYLON;
  34372. (function (BABYLON) {
  34373. var Internals;
  34374. (function (Internals) {
  34375. var AndOrNotEvaluator = (function () {
  34376. function AndOrNotEvaluator() {
  34377. }
  34378. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  34379. if (!query.match(/\([^\(\)]*\)/g)) {
  34380. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  34381. }
  34382. else {
  34383. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  34384. // remove parenthesis
  34385. r = r.slice(1, r.length - 1);
  34386. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  34387. });
  34388. }
  34389. if (query === "true") {
  34390. return true;
  34391. }
  34392. if (query === "false") {
  34393. return false;
  34394. }
  34395. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  34396. };
  34397. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  34398. evaluateCallback = evaluateCallback || (function (r) {
  34399. return r === "true" ? true : false;
  34400. });
  34401. var result;
  34402. var or = parenthesisContent.split("||");
  34403. for (var i in or) {
  34404. if (or.hasOwnProperty(i)) {
  34405. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  34406. var and = ori.split("&&");
  34407. if (and.length > 1) {
  34408. for (var j = 0; j < and.length; ++j) {
  34409. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  34410. if (andj !== "true" && andj !== "false") {
  34411. if (andj[0] === "!") {
  34412. result = !evaluateCallback(andj.substring(1));
  34413. }
  34414. else {
  34415. result = evaluateCallback(andj);
  34416. }
  34417. }
  34418. else {
  34419. result = andj === "true" ? true : false;
  34420. }
  34421. if (!result) {
  34422. ori = "false";
  34423. break;
  34424. }
  34425. }
  34426. }
  34427. if (result || ori === "true") {
  34428. result = true;
  34429. break;
  34430. }
  34431. // result equals false (or undefined)
  34432. if (ori !== "true" && ori !== "false") {
  34433. if (ori[0] === "!") {
  34434. result = !evaluateCallback(ori.substring(1));
  34435. }
  34436. else {
  34437. result = evaluateCallback(ori);
  34438. }
  34439. }
  34440. else {
  34441. result = ori === "true" ? true : false;
  34442. }
  34443. }
  34444. }
  34445. // the whole parenthesis scope is replaced by 'true' or 'false'
  34446. return result ? "true" : "false";
  34447. };
  34448. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  34449. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  34450. // remove whitespaces
  34451. r = r.replace(/[\s]/g, function () { return ""; });
  34452. return r.length % 2 ? "!" : "";
  34453. });
  34454. booleanString = booleanString.trim();
  34455. if (booleanString === "!true") {
  34456. booleanString = "false";
  34457. }
  34458. else if (booleanString === "!false") {
  34459. booleanString = "true";
  34460. }
  34461. return booleanString;
  34462. };
  34463. return AndOrNotEvaluator;
  34464. }());
  34465. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  34466. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  34467. })(BABYLON || (BABYLON = {}));
  34468. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  34469. var BABYLON;
  34470. (function (BABYLON) {
  34471. var PostProcessRenderPass = (function () {
  34472. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  34473. this._enabled = true;
  34474. this._refCount = 0;
  34475. this._name = name;
  34476. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  34477. this.setRenderList(renderList);
  34478. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  34479. this._renderTexture.onAfterRenderObservable.add(afterRender);
  34480. this._scene = scene;
  34481. this._renderList = renderList;
  34482. }
  34483. // private
  34484. PostProcessRenderPass.prototype._incRefCount = function () {
  34485. if (this._refCount === 0) {
  34486. this._scene.customRenderTargets.push(this._renderTexture);
  34487. }
  34488. return ++this._refCount;
  34489. };
  34490. PostProcessRenderPass.prototype._decRefCount = function () {
  34491. this._refCount--;
  34492. if (this._refCount <= 0) {
  34493. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  34494. }
  34495. return this._refCount;
  34496. };
  34497. PostProcessRenderPass.prototype._update = function () {
  34498. this.setRenderList(this._renderList);
  34499. };
  34500. // public
  34501. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  34502. this._renderTexture.renderList = renderList;
  34503. };
  34504. PostProcessRenderPass.prototype.getRenderTexture = function () {
  34505. return this._renderTexture;
  34506. };
  34507. return PostProcessRenderPass;
  34508. }());
  34509. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  34510. })(BABYLON || (BABYLON = {}));
  34511. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  34512. var BABYLON;
  34513. (function (BABYLON) {
  34514. var PostProcessRenderEffect = (function () {
  34515. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  34516. this._engine = engine;
  34517. this._name = name;
  34518. this._singleInstance = singleInstance || true;
  34519. this._getPostProcess = getPostProcess;
  34520. this._cameras = [];
  34521. this._indicesForCamera = [];
  34522. this._postProcesses = {};
  34523. this._renderPasses = {};
  34524. this._renderEffectAsPasses = {};
  34525. }
  34526. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  34527. get: function () {
  34528. for (var index in this._postProcesses) {
  34529. if (!this._postProcesses[index].isSupported) {
  34530. return false;
  34531. }
  34532. }
  34533. return true;
  34534. },
  34535. enumerable: true,
  34536. configurable: true
  34537. });
  34538. PostProcessRenderEffect.prototype._update = function () {
  34539. for (var renderPassName in this._renderPasses) {
  34540. this._renderPasses[renderPassName]._update();
  34541. }
  34542. };
  34543. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  34544. this._renderPasses[renderPass._name] = renderPass;
  34545. this._linkParameters();
  34546. };
  34547. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  34548. delete this._renderPasses[renderPass._name];
  34549. this._linkParameters();
  34550. };
  34551. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  34552. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  34553. this._linkParameters();
  34554. };
  34555. PostProcessRenderEffect.prototype.getPass = function (passName) {
  34556. for (var renderPassName in this._renderPasses) {
  34557. if (renderPassName === passName) {
  34558. return this._renderPasses[passName];
  34559. }
  34560. }
  34561. };
  34562. PostProcessRenderEffect.prototype.emptyPasses = function () {
  34563. this._renderPasses = {};
  34564. this._linkParameters();
  34565. };
  34566. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  34567. var cameraKey;
  34568. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34569. for (var i = 0; i < _cam.length; i++) {
  34570. var camera = _cam[i];
  34571. var cameraName = camera.name;
  34572. if (this._singleInstance) {
  34573. cameraKey = 0;
  34574. }
  34575. else {
  34576. cameraKey = cameraName;
  34577. }
  34578. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  34579. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  34580. if (!this._indicesForCamera[cameraName]) {
  34581. this._indicesForCamera[cameraName] = [];
  34582. }
  34583. this._indicesForCamera[cameraName].push(index);
  34584. if (this._cameras.indexOf(camera) === -1) {
  34585. this._cameras[cameraName] = camera;
  34586. }
  34587. for (var passName in this._renderPasses) {
  34588. this._renderPasses[passName]._incRefCount();
  34589. }
  34590. }
  34591. this._linkParameters();
  34592. };
  34593. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  34594. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34595. for (var i = 0; i < _cam.length; i++) {
  34596. var camera = _cam[i];
  34597. var cameraName = camera.name;
  34598. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34599. var index = this._cameras.indexOf(cameraName);
  34600. this._indicesForCamera.splice(index, 1);
  34601. this._cameras.splice(index, 1);
  34602. for (var passName in this._renderPasses) {
  34603. this._renderPasses[passName]._decRefCount();
  34604. }
  34605. }
  34606. };
  34607. PostProcessRenderEffect.prototype._enable = function (cameras) {
  34608. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34609. for (var i = 0; i < _cam.length; i++) {
  34610. var camera = _cam[i];
  34611. var cameraName = camera.name;
  34612. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  34613. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  34614. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  34615. }
  34616. }
  34617. for (var passName in this._renderPasses) {
  34618. this._renderPasses[passName]._incRefCount();
  34619. }
  34620. }
  34621. };
  34622. PostProcessRenderEffect.prototype._disable = function (cameras) {
  34623. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34624. for (var i = 0; i < _cam.length; i++) {
  34625. var camera = _cam[i];
  34626. var cameraName = camera.Name;
  34627. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  34628. for (var passName in this._renderPasses) {
  34629. this._renderPasses[passName]._decRefCount();
  34630. }
  34631. }
  34632. };
  34633. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  34634. if (this._singleInstance) {
  34635. return this._postProcesses[0];
  34636. }
  34637. else {
  34638. return this._postProcesses[camera.name];
  34639. }
  34640. };
  34641. PostProcessRenderEffect.prototype._linkParameters = function () {
  34642. var _this = this;
  34643. for (var index in this._postProcesses) {
  34644. if (this.applyParameters) {
  34645. this.applyParameters(this._postProcesses[index]);
  34646. }
  34647. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  34648. _this._linkTextures(effect);
  34649. });
  34650. }
  34651. };
  34652. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  34653. for (var renderPassName in this._renderPasses) {
  34654. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  34655. }
  34656. for (var renderEffectName in this._renderEffectAsPasses) {
  34657. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  34658. }
  34659. };
  34660. return PostProcessRenderEffect;
  34661. }());
  34662. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  34663. })(BABYLON || (BABYLON = {}));
  34664. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  34665. var BABYLON;
  34666. (function (BABYLON) {
  34667. var PostProcessRenderPipeline = (function () {
  34668. function PostProcessRenderPipeline(engine, name) {
  34669. this._engine = engine;
  34670. this._name = name;
  34671. this._renderEffects = {};
  34672. this._renderEffectsForIsolatedPass = {};
  34673. this._cameras = [];
  34674. }
  34675. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  34676. get: function () {
  34677. for (var renderEffectName in this._renderEffects) {
  34678. if (!this._renderEffects[renderEffectName].isSupported) {
  34679. return false;
  34680. }
  34681. }
  34682. return true;
  34683. },
  34684. enumerable: true,
  34685. configurable: true
  34686. });
  34687. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  34688. this._renderEffects[renderEffect._name] = renderEffect;
  34689. };
  34690. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  34691. var renderEffects = this._renderEffects[renderEffectName];
  34692. if (!renderEffects) {
  34693. return;
  34694. }
  34695. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34696. };
  34697. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  34698. var renderEffects = this._renderEffects[renderEffectName];
  34699. if (!renderEffects) {
  34700. return;
  34701. }
  34702. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  34703. };
  34704. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  34705. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34706. var indicesToDelete = [];
  34707. var i;
  34708. for (i = 0; i < _cam.length; i++) {
  34709. var camera = _cam[i];
  34710. var cameraName = camera.name;
  34711. if (this._cameras.indexOf(camera) === -1) {
  34712. this._cameras[cameraName] = camera;
  34713. }
  34714. else if (unique) {
  34715. indicesToDelete.push(i);
  34716. }
  34717. }
  34718. for (i = 0; i < indicesToDelete.length; i++) {
  34719. cameras.splice(indicesToDelete[i], 1);
  34720. }
  34721. for (var renderEffectName in this._renderEffects) {
  34722. this._renderEffects[renderEffectName]._attachCameras(_cam);
  34723. }
  34724. };
  34725. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  34726. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34727. for (var renderEffectName in this._renderEffects) {
  34728. this._renderEffects[renderEffectName]._detachCameras(_cam);
  34729. }
  34730. for (var i = 0; i < _cam.length; i++) {
  34731. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  34732. }
  34733. };
  34734. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  34735. var _this = this;
  34736. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34737. var pass = null;
  34738. var renderEffectName;
  34739. for (renderEffectName in this._renderEffects) {
  34740. pass = this._renderEffects[renderEffectName].getPass(passName);
  34741. if (pass != null) {
  34742. break;
  34743. }
  34744. }
  34745. if (pass === null) {
  34746. return;
  34747. }
  34748. for (renderEffectName in this._renderEffects) {
  34749. this._renderEffects[renderEffectName]._disable(_cam);
  34750. }
  34751. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  34752. for (var i = 0; i < _cam.length; i++) {
  34753. var camera = _cam[i];
  34754. var cameraName = camera.name;
  34755. 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); });
  34756. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  34757. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  34758. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  34759. }
  34760. };
  34761. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  34762. var _this = this;
  34763. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  34764. for (var i = 0; i < _cam.length; i++) {
  34765. var camera = _cam[i];
  34766. var cameraName = camera.name;
  34767. 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); });
  34768. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  34769. }
  34770. for (var renderEffectName in this._renderEffects) {
  34771. this._renderEffects[renderEffectName]._enable(_cam);
  34772. }
  34773. };
  34774. PostProcessRenderPipeline.prototype._update = function () {
  34775. for (var renderEffectName in this._renderEffects) {
  34776. this._renderEffects[renderEffectName]._update();
  34777. }
  34778. for (var i = 0; i < this._cameras.length; i++) {
  34779. var cameraName = this._cameras[i].name;
  34780. if (this._renderEffectsForIsolatedPass[cameraName]) {
  34781. this._renderEffectsForIsolatedPass[cameraName]._update();
  34782. }
  34783. }
  34784. };
  34785. PostProcessRenderPipeline.prototype.dispose = function () {
  34786. // Must be implemented by children
  34787. };
  34788. return PostProcessRenderPipeline;
  34789. }());
  34790. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  34791. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  34792. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  34793. })(BABYLON || (BABYLON = {}));
  34794. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  34795. var BABYLON;
  34796. (function (BABYLON) {
  34797. var PostProcessRenderPipelineManager = (function () {
  34798. function PostProcessRenderPipelineManager() {
  34799. this._renderPipelines = {};
  34800. }
  34801. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  34802. this._renderPipelines[renderPipeline._name] = renderPipeline;
  34803. };
  34804. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  34805. var renderPipeline = this._renderPipelines[renderPipelineName];
  34806. if (!renderPipeline) {
  34807. return;
  34808. }
  34809. renderPipeline._attachCameras(cameras, unique);
  34810. };
  34811. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  34812. var renderPipeline = this._renderPipelines[renderPipelineName];
  34813. if (!renderPipeline) {
  34814. return;
  34815. }
  34816. renderPipeline._detachCameras(cameras);
  34817. };
  34818. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34819. var renderPipeline = this._renderPipelines[renderPipelineName];
  34820. if (!renderPipeline) {
  34821. return;
  34822. }
  34823. renderPipeline._enableEffect(renderEffectName, cameras);
  34824. };
  34825. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  34826. var renderPipeline = this._renderPipelines[renderPipelineName];
  34827. if (!renderPipeline) {
  34828. return;
  34829. }
  34830. renderPipeline._disableEffect(renderEffectName, cameras);
  34831. };
  34832. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  34833. var renderPipeline = this._renderPipelines[renderPipelineName];
  34834. if (!renderPipeline) {
  34835. return;
  34836. }
  34837. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  34838. };
  34839. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  34840. var renderPipeline = this._renderPipelines[renderPipelineName];
  34841. if (!renderPipeline) {
  34842. return;
  34843. }
  34844. renderPipeline._disableDisplayOnlyPass(cameras);
  34845. };
  34846. PostProcessRenderPipelineManager.prototype.update = function () {
  34847. for (var renderPipelineName in this._renderPipelines) {
  34848. var pipeline = this._renderPipelines[renderPipelineName];
  34849. if (!pipeline.isSupported) {
  34850. pipeline.dispose();
  34851. delete this._renderPipelines[renderPipelineName];
  34852. }
  34853. else {
  34854. pipeline._update();
  34855. }
  34856. }
  34857. };
  34858. return PostProcessRenderPipelineManager;
  34859. }());
  34860. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  34861. })(BABYLON || (BABYLON = {}));
  34862. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  34863. var BABYLON;
  34864. (function (BABYLON) {
  34865. var BoundingBoxRenderer = (function () {
  34866. function BoundingBoxRenderer(scene) {
  34867. this.frontColor = new BABYLON.Color3(1, 1, 1);
  34868. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  34869. this.showBackLines = true;
  34870. this.renderList = new BABYLON.SmartArray(32);
  34871. this._vertexBuffers = {};
  34872. this._scene = scene;
  34873. }
  34874. BoundingBoxRenderer.prototype._prepareRessources = function () {
  34875. if (this._colorShader) {
  34876. return;
  34877. }
  34878. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  34879. attributes: [BABYLON.VertexBuffer.PositionKind],
  34880. uniforms: ["worldViewProjection", "color"]
  34881. });
  34882. var engine = this._scene.getEngine();
  34883. var boxdata = BABYLON.VertexData.CreateBox(1.0);
  34884. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  34885. this._indexBuffer = 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]);
  34886. };
  34887. BoundingBoxRenderer.prototype.reset = function () {
  34888. this.renderList.reset();
  34889. };
  34890. BoundingBoxRenderer.prototype.render = function () {
  34891. if (this.renderList.length === 0) {
  34892. return;
  34893. }
  34894. this._prepareRessources();
  34895. if (!this._colorShader.isReady()) {
  34896. return;
  34897. }
  34898. var engine = this._scene.getEngine();
  34899. engine.setDepthWrite(false);
  34900. this._colorShader._preBind();
  34901. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  34902. var boundingBox = this.renderList.data[boundingBoxIndex];
  34903. var min = boundingBox.minimum;
  34904. var max = boundingBox.maximum;
  34905. var diff = max.subtract(min);
  34906. var median = min.add(diff.scale(0.5));
  34907. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  34908. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  34909. .multiply(boundingBox.getWorldMatrix());
  34910. // VBOs
  34911. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  34912. if (this.showBackLines) {
  34913. // Back
  34914. engine.setDepthFunctionToGreaterOrEqual();
  34915. this._scene.resetCachedMaterial();
  34916. this._colorShader.setColor4("color", this.backColor.toColor4());
  34917. this._colorShader.bind(worldMatrix);
  34918. // Draw order
  34919. engine.draw(false, 0, 24);
  34920. }
  34921. // Front
  34922. engine.setDepthFunctionToLess();
  34923. this._scene.resetCachedMaterial();
  34924. this._colorShader.setColor4("color", this.frontColor.toColor4());
  34925. this._colorShader.bind(worldMatrix);
  34926. // Draw order
  34927. engine.draw(false, 0, 24);
  34928. }
  34929. this._colorShader.unbind();
  34930. engine.setDepthFunctionToLessOrEqual();
  34931. engine.setDepthWrite(true);
  34932. };
  34933. BoundingBoxRenderer.prototype.dispose = function () {
  34934. if (!this._colorShader) {
  34935. return;
  34936. }
  34937. this._colorShader.dispose();
  34938. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  34939. if (buffer) {
  34940. buffer.dispose();
  34941. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  34942. }
  34943. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  34944. };
  34945. return BoundingBoxRenderer;
  34946. }());
  34947. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  34948. })(BABYLON || (BABYLON = {}));
  34949. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  34950. var BABYLON;
  34951. (function (BABYLON) {
  34952. var Condition = (function () {
  34953. function Condition(actionManager) {
  34954. this._actionManager = actionManager;
  34955. }
  34956. Condition.prototype.isValid = function () {
  34957. return true;
  34958. };
  34959. Condition.prototype._getProperty = function (propertyPath) {
  34960. return this._actionManager._getProperty(propertyPath);
  34961. };
  34962. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  34963. return this._actionManager._getEffectiveTarget(target, propertyPath);
  34964. };
  34965. Condition.prototype.serialize = function () {
  34966. };
  34967. Condition.prototype._serialize = function (serializedCondition) {
  34968. return {
  34969. type: 2,
  34970. children: [],
  34971. name: serializedCondition.name,
  34972. properties: serializedCondition.properties
  34973. };
  34974. };
  34975. return Condition;
  34976. }());
  34977. BABYLON.Condition = Condition;
  34978. var ValueCondition = (function (_super) {
  34979. __extends(ValueCondition, _super);
  34980. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  34981. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  34982. var _this = _super.call(this, actionManager) || this;
  34983. _this.propertyPath = propertyPath;
  34984. _this.value = value;
  34985. _this.operator = operator;
  34986. _this._target = target;
  34987. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  34988. _this._property = _this._getProperty(_this.propertyPath);
  34989. return _this;
  34990. }
  34991. Object.defineProperty(ValueCondition, "IsEqual", {
  34992. get: function () {
  34993. return ValueCondition._IsEqual;
  34994. },
  34995. enumerable: true,
  34996. configurable: true
  34997. });
  34998. Object.defineProperty(ValueCondition, "IsDifferent", {
  34999. get: function () {
  35000. return ValueCondition._IsDifferent;
  35001. },
  35002. enumerable: true,
  35003. configurable: true
  35004. });
  35005. Object.defineProperty(ValueCondition, "IsGreater", {
  35006. get: function () {
  35007. return ValueCondition._IsGreater;
  35008. },
  35009. enumerable: true,
  35010. configurable: true
  35011. });
  35012. Object.defineProperty(ValueCondition, "IsLesser", {
  35013. get: function () {
  35014. return ValueCondition._IsLesser;
  35015. },
  35016. enumerable: true,
  35017. configurable: true
  35018. });
  35019. // Methods
  35020. ValueCondition.prototype.isValid = function () {
  35021. switch (this.operator) {
  35022. case ValueCondition.IsGreater:
  35023. return this._effectiveTarget[this._property] > this.value;
  35024. case ValueCondition.IsLesser:
  35025. return this._effectiveTarget[this._property] < this.value;
  35026. case ValueCondition.IsEqual:
  35027. case ValueCondition.IsDifferent:
  35028. var check;
  35029. if (this.value.equals) {
  35030. check = this.value.equals(this._effectiveTarget[this._property]);
  35031. }
  35032. else {
  35033. check = this.value === this._effectiveTarget[this._property];
  35034. }
  35035. return this.operator === ValueCondition.IsEqual ? check : !check;
  35036. }
  35037. return false;
  35038. };
  35039. ValueCondition.prototype.serialize = function () {
  35040. return this._serialize({
  35041. name: "ValueCondition",
  35042. properties: [
  35043. BABYLON.Action._GetTargetProperty(this._target),
  35044. { name: "propertyPath", value: this.propertyPath },
  35045. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35046. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  35047. ]
  35048. });
  35049. };
  35050. ValueCondition.GetOperatorName = function (operator) {
  35051. switch (operator) {
  35052. case ValueCondition._IsEqual: return "IsEqual";
  35053. case ValueCondition._IsDifferent: return "IsDifferent";
  35054. case ValueCondition._IsGreater: return "IsGreater";
  35055. case ValueCondition._IsLesser: return "IsLesser";
  35056. default: return "";
  35057. }
  35058. };
  35059. return ValueCondition;
  35060. }(Condition));
  35061. // Statics
  35062. ValueCondition._IsEqual = 0;
  35063. ValueCondition._IsDifferent = 1;
  35064. ValueCondition._IsGreater = 2;
  35065. ValueCondition._IsLesser = 3;
  35066. BABYLON.ValueCondition = ValueCondition;
  35067. var PredicateCondition = (function (_super) {
  35068. __extends(PredicateCondition, _super);
  35069. function PredicateCondition(actionManager, predicate) {
  35070. var _this = _super.call(this, actionManager) || this;
  35071. _this.predicate = predicate;
  35072. return _this;
  35073. }
  35074. PredicateCondition.prototype.isValid = function () {
  35075. return this.predicate();
  35076. };
  35077. return PredicateCondition;
  35078. }(Condition));
  35079. BABYLON.PredicateCondition = PredicateCondition;
  35080. var StateCondition = (function (_super) {
  35081. __extends(StateCondition, _super);
  35082. function StateCondition(actionManager, target, value) {
  35083. var _this = _super.call(this, actionManager) || this;
  35084. _this.value = value;
  35085. _this._target = target;
  35086. return _this;
  35087. }
  35088. // Methods
  35089. StateCondition.prototype.isValid = function () {
  35090. return this._target.state === this.value;
  35091. };
  35092. StateCondition.prototype.serialize = function () {
  35093. return this._serialize({
  35094. name: "StateCondition",
  35095. properties: [
  35096. BABYLON.Action._GetTargetProperty(this._target),
  35097. { name: "value", value: this.value }
  35098. ]
  35099. });
  35100. };
  35101. return StateCondition;
  35102. }(Condition));
  35103. BABYLON.StateCondition = StateCondition;
  35104. })(BABYLON || (BABYLON = {}));
  35105. //# sourceMappingURL=babylon.condition.js.map
  35106. var BABYLON;
  35107. (function (BABYLON) {
  35108. var Action = (function () {
  35109. function Action(triggerOptions, condition) {
  35110. this.triggerOptions = triggerOptions;
  35111. if (triggerOptions.parameter) {
  35112. this.trigger = triggerOptions.trigger;
  35113. this._triggerParameter = triggerOptions.parameter;
  35114. }
  35115. else {
  35116. this.trigger = triggerOptions;
  35117. }
  35118. this._nextActiveAction = this;
  35119. this._condition = condition;
  35120. }
  35121. // Methods
  35122. Action.prototype._prepare = function () {
  35123. };
  35124. Action.prototype.getTriggerParameter = function () {
  35125. return this._triggerParameter;
  35126. };
  35127. Action.prototype._executeCurrent = function (evt) {
  35128. if (this._nextActiveAction._condition) {
  35129. var condition = this._nextActiveAction._condition;
  35130. var currentRenderId = this._actionManager.getScene().getRenderId();
  35131. // We cache the current evaluation for the current frame
  35132. if (condition._evaluationId === currentRenderId) {
  35133. if (!condition._currentResult) {
  35134. return;
  35135. }
  35136. }
  35137. else {
  35138. condition._evaluationId = currentRenderId;
  35139. if (!condition.isValid()) {
  35140. condition._currentResult = false;
  35141. return;
  35142. }
  35143. condition._currentResult = true;
  35144. }
  35145. }
  35146. this._nextActiveAction.execute(evt);
  35147. this.skipToNextActiveAction();
  35148. };
  35149. Action.prototype.execute = function (evt) {
  35150. };
  35151. Action.prototype.skipToNextActiveAction = function () {
  35152. if (this._nextActiveAction._child) {
  35153. if (!this._nextActiveAction._child._actionManager) {
  35154. this._nextActiveAction._child._actionManager = this._actionManager;
  35155. }
  35156. this._nextActiveAction = this._nextActiveAction._child;
  35157. }
  35158. else {
  35159. this._nextActiveAction = this;
  35160. }
  35161. };
  35162. Action.prototype.then = function (action) {
  35163. this._child = action;
  35164. action._actionManager = this._actionManager;
  35165. action._prepare();
  35166. return action;
  35167. };
  35168. Action.prototype._getProperty = function (propertyPath) {
  35169. return this._actionManager._getProperty(propertyPath);
  35170. };
  35171. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  35172. return this._actionManager._getEffectiveTarget(target, propertyPath);
  35173. };
  35174. Action.prototype.serialize = function (parent) {
  35175. };
  35176. // Called by BABYLON.Action objects in serialize(...). Internal use
  35177. Action.prototype._serialize = function (serializedAction, parent) {
  35178. var serializationObject = {
  35179. type: 1,
  35180. children: [],
  35181. name: serializedAction.name,
  35182. properties: serializedAction.properties || []
  35183. };
  35184. // Serialize child
  35185. if (this._child) {
  35186. this._child.serialize(serializationObject);
  35187. }
  35188. // Check if "this" has a condition
  35189. if (this._condition) {
  35190. var serializedCondition = this._condition.serialize();
  35191. serializedCondition.children.push(serializationObject);
  35192. if (parent) {
  35193. parent.children.push(serializedCondition);
  35194. }
  35195. return serializedCondition;
  35196. }
  35197. if (parent) {
  35198. parent.children.push(serializationObject);
  35199. }
  35200. return serializationObject;
  35201. };
  35202. return Action;
  35203. }());
  35204. Action._SerializeValueAsString = function (value) {
  35205. if (typeof value === "number") {
  35206. return value.toString();
  35207. }
  35208. if (typeof value === "boolean") {
  35209. return value ? "true" : "false";
  35210. }
  35211. if (value instanceof BABYLON.Vector2) {
  35212. return value.x + ", " + value.y;
  35213. }
  35214. if (value instanceof BABYLON.Vector3) {
  35215. return value.x + ", " + value.y + ", " + value.z;
  35216. }
  35217. if (value instanceof BABYLON.Color3) {
  35218. return value.r + ", " + value.g + ", " + value.b;
  35219. }
  35220. if (value instanceof BABYLON.Color4) {
  35221. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  35222. }
  35223. return value; // string
  35224. };
  35225. Action._GetTargetProperty = function (target) {
  35226. return {
  35227. name: "target",
  35228. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  35229. : target instanceof BABYLON.Light ? "LightProperties"
  35230. : target instanceof BABYLON.Camera ? "CameraProperties"
  35231. : "SceneProperties",
  35232. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  35233. };
  35234. };
  35235. BABYLON.Action = Action;
  35236. })(BABYLON || (BABYLON = {}));
  35237. //# sourceMappingURL=babylon.action.js.map
  35238. var BABYLON;
  35239. (function (BABYLON) {
  35240. /**
  35241. * ActionEvent is the event beint sent when an action is triggered.
  35242. */
  35243. var ActionEvent = (function () {
  35244. /**
  35245. * @constructor
  35246. * @param source The mesh or sprite that triggered the action.
  35247. * @param pointerX The X mouse cursor position at the time of the event
  35248. * @param pointerY The Y mouse cursor position at the time of the event
  35249. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  35250. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  35251. */
  35252. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  35253. this.source = source;
  35254. this.pointerX = pointerX;
  35255. this.pointerY = pointerY;
  35256. this.meshUnderPointer = meshUnderPointer;
  35257. this.sourceEvent = sourceEvent;
  35258. this.additionalData = additionalData;
  35259. }
  35260. /**
  35261. * Helper function to auto-create an ActionEvent from a source mesh.
  35262. * @param source The source mesh that triggered the event
  35263. * @param evt {Event} The original (browser) event
  35264. */
  35265. ActionEvent.CreateNew = function (source, evt, additionalData) {
  35266. var scene = source.getScene();
  35267. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35268. };
  35269. /**
  35270. * Helper function to auto-create an ActionEvent from a source mesh.
  35271. * @param source The source sprite that triggered the event
  35272. * @param scene Scene associated with the sprite
  35273. * @param evt {Event} The original (browser) event
  35274. */
  35275. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  35276. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  35277. };
  35278. /**
  35279. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  35280. * @param scene the scene where the event occurred
  35281. * @param evt {Event} The original (browser) event
  35282. */
  35283. ActionEvent.CreateNewFromScene = function (scene, evt) {
  35284. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  35285. };
  35286. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  35287. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  35288. };
  35289. return ActionEvent;
  35290. }());
  35291. BABYLON.ActionEvent = ActionEvent;
  35292. /**
  35293. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  35294. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  35295. */
  35296. var ActionManager = (function () {
  35297. function ActionManager(scene) {
  35298. // Members
  35299. this.actions = new Array();
  35300. this.hoverCursor = '';
  35301. this._scene = scene;
  35302. scene._actionManagers.push(this);
  35303. }
  35304. Object.defineProperty(ActionManager, "NothingTrigger", {
  35305. get: function () {
  35306. return ActionManager._NothingTrigger;
  35307. },
  35308. enumerable: true,
  35309. configurable: true
  35310. });
  35311. Object.defineProperty(ActionManager, "OnPickTrigger", {
  35312. get: function () {
  35313. return ActionManager._OnPickTrigger;
  35314. },
  35315. enumerable: true,
  35316. configurable: true
  35317. });
  35318. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  35319. get: function () {
  35320. return ActionManager._OnLeftPickTrigger;
  35321. },
  35322. enumerable: true,
  35323. configurable: true
  35324. });
  35325. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  35326. get: function () {
  35327. return ActionManager._OnRightPickTrigger;
  35328. },
  35329. enumerable: true,
  35330. configurable: true
  35331. });
  35332. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  35333. get: function () {
  35334. return ActionManager._OnCenterPickTrigger;
  35335. },
  35336. enumerable: true,
  35337. configurable: true
  35338. });
  35339. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  35340. get: function () {
  35341. return ActionManager._OnPickDownTrigger;
  35342. },
  35343. enumerable: true,
  35344. configurable: true
  35345. });
  35346. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  35347. get: function () {
  35348. return ActionManager._OnPickUpTrigger;
  35349. },
  35350. enumerable: true,
  35351. configurable: true
  35352. });
  35353. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  35354. /// This trigger will only be raised if you also declared a OnPickDown
  35355. get: function () {
  35356. return ActionManager._OnPickOutTrigger;
  35357. },
  35358. enumerable: true,
  35359. configurable: true
  35360. });
  35361. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  35362. get: function () {
  35363. return ActionManager._OnLongPressTrigger;
  35364. },
  35365. enumerable: true,
  35366. configurable: true
  35367. });
  35368. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  35369. get: function () {
  35370. return ActionManager._OnPointerOverTrigger;
  35371. },
  35372. enumerable: true,
  35373. configurable: true
  35374. });
  35375. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  35376. get: function () {
  35377. return ActionManager._OnPointerOutTrigger;
  35378. },
  35379. enumerable: true,
  35380. configurable: true
  35381. });
  35382. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  35383. get: function () {
  35384. return ActionManager._OnEveryFrameTrigger;
  35385. },
  35386. enumerable: true,
  35387. configurable: true
  35388. });
  35389. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  35390. get: function () {
  35391. return ActionManager._OnIntersectionEnterTrigger;
  35392. },
  35393. enumerable: true,
  35394. configurable: true
  35395. });
  35396. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  35397. get: function () {
  35398. return ActionManager._OnIntersectionExitTrigger;
  35399. },
  35400. enumerable: true,
  35401. configurable: true
  35402. });
  35403. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  35404. get: function () {
  35405. return ActionManager._OnKeyDownTrigger;
  35406. },
  35407. enumerable: true,
  35408. configurable: true
  35409. });
  35410. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  35411. get: function () {
  35412. return ActionManager._OnKeyUpTrigger;
  35413. },
  35414. enumerable: true,
  35415. configurable: true
  35416. });
  35417. // Methods
  35418. ActionManager.prototype.dispose = function () {
  35419. var index = this._scene._actionManagers.indexOf(this);
  35420. if (index > -1) {
  35421. this._scene._actionManagers.splice(index, 1);
  35422. }
  35423. };
  35424. ActionManager.prototype.getScene = function () {
  35425. return this._scene;
  35426. };
  35427. /**
  35428. * Does this action manager handles actions of any of the given triggers
  35429. * @param {number[]} triggers - the triggers to be tested
  35430. * @return {boolean} whether one (or more) of the triggers is handeled
  35431. */
  35432. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  35433. for (var index = 0; index < this.actions.length; index++) {
  35434. var action = this.actions[index];
  35435. if (triggers.indexOf(action.trigger) > -1) {
  35436. return true;
  35437. }
  35438. }
  35439. return false;
  35440. };
  35441. /**
  35442. * Does this action manager handles actions of a given trigger
  35443. * @param {number} trigger - the trigger to be tested
  35444. * @return {boolean} whether the trigger is handeled
  35445. */
  35446. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  35447. for (var index = 0; index < this.actions.length; index++) {
  35448. var action = this.actions[index];
  35449. if (action.trigger === trigger) {
  35450. return true;
  35451. }
  35452. }
  35453. return false;
  35454. };
  35455. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  35456. /**
  35457. * Does this action manager has pointer triggers
  35458. * @return {boolean} whether or not it has pointer triggers
  35459. */
  35460. get: function () {
  35461. for (var index = 0; index < this.actions.length; index++) {
  35462. var action = this.actions[index];
  35463. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  35464. return true;
  35465. }
  35466. }
  35467. return false;
  35468. },
  35469. enumerable: true,
  35470. configurable: true
  35471. });
  35472. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  35473. /**
  35474. * Does this action manager has pick triggers
  35475. * @return {boolean} whether or not it has pick triggers
  35476. */
  35477. get: function () {
  35478. for (var index = 0; index < this.actions.length; index++) {
  35479. var action = this.actions[index];
  35480. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  35481. return true;
  35482. }
  35483. }
  35484. return false;
  35485. },
  35486. enumerable: true,
  35487. configurable: true
  35488. });
  35489. /**
  35490. * Registers an action to this action manager
  35491. * @param {BABYLON.Action} action - the action to be registered
  35492. * @return {BABYLON.Action} the action amended (prepared) after registration
  35493. */
  35494. ActionManager.prototype.registerAction = function (action) {
  35495. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  35496. if (this.getScene().actionManager !== this) {
  35497. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  35498. return null;
  35499. }
  35500. }
  35501. this.actions.push(action);
  35502. action._actionManager = this;
  35503. action._prepare();
  35504. return action;
  35505. };
  35506. /**
  35507. * Process a specific trigger
  35508. * @param {number} trigger - the trigger to process
  35509. * @param evt {BABYLON.ActionEvent} the event details to be processed
  35510. */
  35511. ActionManager.prototype.processTrigger = function (trigger, evt) {
  35512. for (var index = 0; index < this.actions.length; index++) {
  35513. var action = this.actions[index];
  35514. if (action.trigger === trigger) {
  35515. if (trigger === ActionManager.OnKeyUpTrigger
  35516. || trigger === ActionManager.OnKeyDownTrigger) {
  35517. var parameter = action.getTriggerParameter();
  35518. if (parameter) {
  35519. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  35520. var actualkey = String.fromCharCode(unicode).toLowerCase();
  35521. if (actualkey !== parameter.toLowerCase()) {
  35522. continue;
  35523. }
  35524. }
  35525. }
  35526. action._executeCurrent(evt);
  35527. }
  35528. }
  35529. };
  35530. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  35531. var properties = propertyPath.split(".");
  35532. for (var index = 0; index < properties.length - 1; index++) {
  35533. target = target[properties[index]];
  35534. }
  35535. return target;
  35536. };
  35537. ActionManager.prototype._getProperty = function (propertyPath) {
  35538. var properties = propertyPath.split(".");
  35539. return properties[properties.length - 1];
  35540. };
  35541. ActionManager.prototype.serialize = function (name) {
  35542. var root = {
  35543. children: [],
  35544. name: name,
  35545. type: 3,
  35546. properties: [] // Empty for root but required
  35547. };
  35548. for (var i = 0; i < this.actions.length; i++) {
  35549. var triggerObject = {
  35550. type: 0,
  35551. children: [],
  35552. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  35553. properties: []
  35554. };
  35555. var triggerOptions = this.actions[i].triggerOptions;
  35556. if (triggerOptions && typeof triggerOptions !== "number") {
  35557. if (triggerOptions.parameter instanceof BABYLON.Node) {
  35558. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  35559. }
  35560. else {
  35561. var parameter = {};
  35562. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  35563. if (triggerOptions.parameter.mesh) {
  35564. parameter._meshId = triggerOptions.parameter.mesh.id;
  35565. }
  35566. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  35567. }
  35568. }
  35569. // Serialize child action, recursively
  35570. this.actions[i].serialize(triggerObject);
  35571. // Add serialized trigger
  35572. root.children.push(triggerObject);
  35573. }
  35574. return root;
  35575. };
  35576. ActionManager.Parse = function (parsedActions, object, scene) {
  35577. var actionManager = new BABYLON.ActionManager(scene);
  35578. if (object === null)
  35579. scene.actionManager = actionManager;
  35580. else
  35581. object.actionManager = actionManager;
  35582. // instanciate a new object
  35583. var instanciate = function (name, params) {
  35584. var newInstance = Object.create(BABYLON[name].prototype);
  35585. newInstance.constructor.apply(newInstance, params);
  35586. return newInstance;
  35587. };
  35588. var parseParameter = function (name, value, target, propertyPath) {
  35589. if (propertyPath === null) {
  35590. // String, boolean or float
  35591. var floatValue = parseFloat(value);
  35592. if (value === "true" || value === "false")
  35593. return value === "true";
  35594. else
  35595. return isNaN(floatValue) ? value : floatValue;
  35596. }
  35597. var effectiveTarget = propertyPath.split(".");
  35598. var values = value.split(",");
  35599. // Get effective Target
  35600. for (var i = 0; i < effectiveTarget.length; i++) {
  35601. target = target[effectiveTarget[i]];
  35602. }
  35603. // Return appropriate value with its type
  35604. if (typeof (target) === "boolean")
  35605. return values[0] === "true";
  35606. if (typeof (target) === "string")
  35607. return values[0];
  35608. // Parameters with multiple values such as Vector3 etc.
  35609. var split = new Array();
  35610. for (var i = 0; i < values.length; i++)
  35611. split.push(parseFloat(values[i]));
  35612. if (target instanceof BABYLON.Vector3)
  35613. return BABYLON.Vector3.FromArray(split);
  35614. if (target instanceof BABYLON.Vector4)
  35615. return BABYLON.Vector4.FromArray(split);
  35616. if (target instanceof BABYLON.Color3)
  35617. return BABYLON.Color3.FromArray(split);
  35618. if (target instanceof BABYLON.Color4)
  35619. return BABYLON.Color4.FromArray(split);
  35620. return parseFloat(values[0]);
  35621. };
  35622. // traverse graph per trigger
  35623. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  35624. if (combineArray === void 0) { combineArray = null; }
  35625. if (parsedAction.detached)
  35626. return;
  35627. var parameters = new Array();
  35628. var target = null;
  35629. var propertyPath = null;
  35630. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  35631. // Parameters
  35632. if (parsedAction.type === 2)
  35633. parameters.push(actionManager);
  35634. else
  35635. parameters.push(trigger);
  35636. if (combine) {
  35637. var actions = new Array();
  35638. for (var j = 0; j < parsedAction.combine.length; j++) {
  35639. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  35640. }
  35641. parameters.push(actions);
  35642. }
  35643. else {
  35644. for (var i = 0; i < parsedAction.properties.length; i++) {
  35645. var value = parsedAction.properties[i].value;
  35646. var name = parsedAction.properties[i].name;
  35647. var targetType = parsedAction.properties[i].targetType;
  35648. if (name === "target")
  35649. if (targetType !== null && targetType === "SceneProperties")
  35650. value = target = scene;
  35651. else
  35652. value = target = scene.getNodeByName(value);
  35653. else if (name === "parent")
  35654. value = scene.getNodeByName(value);
  35655. else if (name === "sound")
  35656. value = scene.getSoundByName(value);
  35657. else if (name !== "propertyPath") {
  35658. if (parsedAction.type === 2 && name === "operator")
  35659. value = BABYLON.ValueCondition[value];
  35660. else
  35661. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  35662. }
  35663. else {
  35664. propertyPath = value;
  35665. }
  35666. parameters.push(value);
  35667. }
  35668. }
  35669. if (combineArray === null) {
  35670. parameters.push(condition);
  35671. }
  35672. else {
  35673. parameters.push(null);
  35674. }
  35675. // If interpolate value action
  35676. if (parsedAction.name === "InterpolateValueAction") {
  35677. var param = parameters[parameters.length - 2];
  35678. parameters[parameters.length - 1] = param;
  35679. parameters[parameters.length - 2] = condition;
  35680. }
  35681. // Action or condition(s) and not CombineAction
  35682. var newAction = instanciate(parsedAction.name, parameters);
  35683. if (newAction instanceof BABYLON.Condition && condition !== null) {
  35684. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  35685. if (action)
  35686. action.then(nothing);
  35687. else
  35688. actionManager.registerAction(nothing);
  35689. action = nothing;
  35690. }
  35691. if (combineArray === null) {
  35692. if (newAction instanceof BABYLON.Condition) {
  35693. condition = newAction;
  35694. newAction = action;
  35695. }
  35696. else {
  35697. condition = null;
  35698. if (action)
  35699. action.then(newAction);
  35700. else
  35701. actionManager.registerAction(newAction);
  35702. }
  35703. }
  35704. else {
  35705. combineArray.push(newAction);
  35706. }
  35707. for (var i = 0; i < parsedAction.children.length; i++)
  35708. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  35709. };
  35710. // triggers
  35711. for (var i = 0; i < parsedActions.children.length; i++) {
  35712. var triggerParams;
  35713. var trigger = parsedActions.children[i];
  35714. if (trigger.properties.length > 0) {
  35715. var param = trigger.properties[0].value;
  35716. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  35717. if (value._meshId) {
  35718. value.mesh = scene.getMeshByID(value._meshId);
  35719. }
  35720. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  35721. }
  35722. else
  35723. triggerParams = BABYLON.ActionManager[trigger.name];
  35724. for (var j = 0; j < trigger.children.length; j++) {
  35725. if (!trigger.detached)
  35726. traverse(trigger.children[j], triggerParams, null, null);
  35727. }
  35728. }
  35729. };
  35730. ActionManager.GetTriggerName = function (trigger) {
  35731. switch (trigger) {
  35732. case 0: return "NothingTrigger";
  35733. case 1: return "OnPickTrigger";
  35734. case 2: return "OnLeftPickTrigger";
  35735. case 3: return "OnRightPickTrigger";
  35736. case 4: return "OnCenterPickTrigger";
  35737. case 5: return "OnPickDownTrigger";
  35738. case 6: return "OnPickUpTrigger";
  35739. case 7: return "OnLongPressTrigger";
  35740. case 8: return "OnPointerOverTrigger";
  35741. case 9: return "OnPointerOutTrigger";
  35742. case 10: return "OnEveryFrameTrigger";
  35743. case 11: return "OnIntersectionEnterTrigger";
  35744. case 12: return "OnIntersectionExitTrigger";
  35745. case 13: return "OnKeyDownTrigger";
  35746. case 14: return "OnKeyUpTrigger";
  35747. case 15: return "OnPickOutTrigger";
  35748. default: return "";
  35749. }
  35750. };
  35751. return ActionManager;
  35752. }());
  35753. // Statics
  35754. ActionManager._NothingTrigger = 0;
  35755. ActionManager._OnPickTrigger = 1;
  35756. ActionManager._OnLeftPickTrigger = 2;
  35757. ActionManager._OnRightPickTrigger = 3;
  35758. ActionManager._OnCenterPickTrigger = 4;
  35759. ActionManager._OnPickDownTrigger = 5;
  35760. ActionManager._OnPickUpTrigger = 6;
  35761. ActionManager._OnLongPressTrigger = 7;
  35762. ActionManager._OnPointerOverTrigger = 8;
  35763. ActionManager._OnPointerOutTrigger = 9;
  35764. ActionManager._OnEveryFrameTrigger = 10;
  35765. ActionManager._OnIntersectionEnterTrigger = 11;
  35766. ActionManager._OnIntersectionExitTrigger = 12;
  35767. ActionManager._OnKeyDownTrigger = 13;
  35768. ActionManager._OnKeyUpTrigger = 14;
  35769. ActionManager._OnPickOutTrigger = 15;
  35770. ActionManager.DragMovementThreshold = 10; // in pixels
  35771. ActionManager.LongPressDelay = 500; // in milliseconds
  35772. BABYLON.ActionManager = ActionManager;
  35773. })(BABYLON || (BABYLON = {}));
  35774. //# sourceMappingURL=babylon.actionManager.js.map
  35775. var BABYLON;
  35776. (function (BABYLON) {
  35777. var InterpolateValueAction = (function (_super) {
  35778. __extends(InterpolateValueAction, _super);
  35779. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  35780. if (duration === void 0) { duration = 1000; }
  35781. var _this = _super.call(this, triggerOptions, condition) || this;
  35782. _this.propertyPath = propertyPath;
  35783. _this.value = value;
  35784. _this.duration = duration;
  35785. _this.stopOtherAnimations = stopOtherAnimations;
  35786. _this.onInterpolationDone = onInterpolationDone;
  35787. _this._target = _this._effectiveTarget = target;
  35788. return _this;
  35789. }
  35790. InterpolateValueAction.prototype._prepare = function () {
  35791. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35792. this._property = this._getProperty(this.propertyPath);
  35793. };
  35794. InterpolateValueAction.prototype.execute = function () {
  35795. var scene = this._actionManager.getScene();
  35796. var keys = [
  35797. {
  35798. frame: 0,
  35799. value: this._effectiveTarget[this._property]
  35800. }, {
  35801. frame: 100,
  35802. value: this.value
  35803. }
  35804. ];
  35805. var dataType;
  35806. if (typeof this.value === "number") {
  35807. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  35808. }
  35809. else if (this.value instanceof BABYLON.Color3) {
  35810. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  35811. }
  35812. else if (this.value instanceof BABYLON.Vector3) {
  35813. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  35814. }
  35815. else if (this.value instanceof BABYLON.Matrix) {
  35816. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  35817. }
  35818. else if (this.value instanceof BABYLON.Quaternion) {
  35819. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  35820. }
  35821. else {
  35822. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  35823. return;
  35824. }
  35825. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  35826. animation.setKeys(keys);
  35827. if (this.stopOtherAnimations) {
  35828. scene.stopAnimation(this._effectiveTarget);
  35829. }
  35830. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  35831. };
  35832. InterpolateValueAction.prototype.serialize = function (parent) {
  35833. return _super.prototype._serialize.call(this, {
  35834. name: "InterpolateValueAction",
  35835. properties: [
  35836. BABYLON.Action._GetTargetProperty(this._target),
  35837. { name: "propertyPath", value: this.propertyPath },
  35838. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  35839. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  35840. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  35841. ]
  35842. }, parent);
  35843. };
  35844. return InterpolateValueAction;
  35845. }(BABYLON.Action));
  35846. BABYLON.InterpolateValueAction = InterpolateValueAction;
  35847. })(BABYLON || (BABYLON = {}));
  35848. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  35849. var BABYLON;
  35850. (function (BABYLON) {
  35851. var SwitchBooleanAction = (function (_super) {
  35852. __extends(SwitchBooleanAction, _super);
  35853. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  35854. var _this = _super.call(this, triggerOptions, condition) || this;
  35855. _this.propertyPath = propertyPath;
  35856. _this._target = _this._effectiveTarget = target;
  35857. return _this;
  35858. }
  35859. SwitchBooleanAction.prototype._prepare = function () {
  35860. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35861. this._property = this._getProperty(this.propertyPath);
  35862. };
  35863. SwitchBooleanAction.prototype.execute = function () {
  35864. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  35865. };
  35866. SwitchBooleanAction.prototype.serialize = function (parent) {
  35867. return _super.prototype._serialize.call(this, {
  35868. name: "SwitchBooleanAction",
  35869. properties: [
  35870. BABYLON.Action._GetTargetProperty(this._target),
  35871. { name: "propertyPath", value: this.propertyPath }
  35872. ]
  35873. }, parent);
  35874. };
  35875. return SwitchBooleanAction;
  35876. }(BABYLON.Action));
  35877. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  35878. var SetStateAction = (function (_super) {
  35879. __extends(SetStateAction, _super);
  35880. function SetStateAction(triggerOptions, target, value, condition) {
  35881. var _this = _super.call(this, triggerOptions, condition) || this;
  35882. _this.value = value;
  35883. _this._target = target;
  35884. return _this;
  35885. }
  35886. SetStateAction.prototype.execute = function () {
  35887. this._target.state = this.value;
  35888. };
  35889. SetStateAction.prototype.serialize = function (parent) {
  35890. return _super.prototype._serialize.call(this, {
  35891. name: "SetStateAction",
  35892. properties: [
  35893. BABYLON.Action._GetTargetProperty(this._target),
  35894. { name: "value", value: this.value }
  35895. ]
  35896. }, parent);
  35897. };
  35898. return SetStateAction;
  35899. }(BABYLON.Action));
  35900. BABYLON.SetStateAction = SetStateAction;
  35901. var SetValueAction = (function (_super) {
  35902. __extends(SetValueAction, _super);
  35903. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  35904. var _this = _super.call(this, triggerOptions, condition) || this;
  35905. _this.propertyPath = propertyPath;
  35906. _this.value = value;
  35907. _this._target = _this._effectiveTarget = target;
  35908. return _this;
  35909. }
  35910. SetValueAction.prototype._prepare = function () {
  35911. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35912. this._property = this._getProperty(this.propertyPath);
  35913. };
  35914. SetValueAction.prototype.execute = function () {
  35915. this._effectiveTarget[this._property] = this.value;
  35916. if (this._target.markAsDirty) {
  35917. this._target.markAsDirty(this._property);
  35918. }
  35919. };
  35920. SetValueAction.prototype.serialize = function (parent) {
  35921. return _super.prototype._serialize.call(this, {
  35922. name: "SetValueAction",
  35923. properties: [
  35924. BABYLON.Action._GetTargetProperty(this._target),
  35925. { name: "propertyPath", value: this.propertyPath },
  35926. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35927. ]
  35928. }, parent);
  35929. };
  35930. return SetValueAction;
  35931. }(BABYLON.Action));
  35932. BABYLON.SetValueAction = SetValueAction;
  35933. var IncrementValueAction = (function (_super) {
  35934. __extends(IncrementValueAction, _super);
  35935. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  35936. var _this = _super.call(this, triggerOptions, condition) || this;
  35937. _this.propertyPath = propertyPath;
  35938. _this.value = value;
  35939. _this._target = _this._effectiveTarget = target;
  35940. return _this;
  35941. }
  35942. IncrementValueAction.prototype._prepare = function () {
  35943. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  35944. this._property = this._getProperty(this.propertyPath);
  35945. if (typeof this._effectiveTarget[this._property] !== "number") {
  35946. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  35947. }
  35948. };
  35949. IncrementValueAction.prototype.execute = function () {
  35950. this._effectiveTarget[this._property] += this.value;
  35951. if (this._target.markAsDirty) {
  35952. this._target.markAsDirty(this._property);
  35953. }
  35954. };
  35955. IncrementValueAction.prototype.serialize = function (parent) {
  35956. return _super.prototype._serialize.call(this, {
  35957. name: "IncrementValueAction",
  35958. properties: [
  35959. BABYLON.Action._GetTargetProperty(this._target),
  35960. { name: "propertyPath", value: this.propertyPath },
  35961. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  35962. ]
  35963. }, parent);
  35964. };
  35965. return IncrementValueAction;
  35966. }(BABYLON.Action));
  35967. BABYLON.IncrementValueAction = IncrementValueAction;
  35968. var PlayAnimationAction = (function (_super) {
  35969. __extends(PlayAnimationAction, _super);
  35970. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  35971. var _this = _super.call(this, triggerOptions, condition) || this;
  35972. _this.from = from;
  35973. _this.to = to;
  35974. _this.loop = loop;
  35975. _this._target = target;
  35976. return _this;
  35977. }
  35978. PlayAnimationAction.prototype._prepare = function () {
  35979. };
  35980. PlayAnimationAction.prototype.execute = function () {
  35981. var scene = this._actionManager.getScene();
  35982. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  35983. };
  35984. PlayAnimationAction.prototype.serialize = function (parent) {
  35985. return _super.prototype._serialize.call(this, {
  35986. name: "PlayAnimationAction",
  35987. properties: [
  35988. BABYLON.Action._GetTargetProperty(this._target),
  35989. { name: "from", value: String(this.from) },
  35990. { name: "to", value: String(this.to) },
  35991. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  35992. ]
  35993. }, parent);
  35994. };
  35995. return PlayAnimationAction;
  35996. }(BABYLON.Action));
  35997. BABYLON.PlayAnimationAction = PlayAnimationAction;
  35998. var StopAnimationAction = (function (_super) {
  35999. __extends(StopAnimationAction, _super);
  36000. function StopAnimationAction(triggerOptions, target, condition) {
  36001. var _this = _super.call(this, triggerOptions, condition) || this;
  36002. _this._target = target;
  36003. return _this;
  36004. }
  36005. StopAnimationAction.prototype._prepare = function () {
  36006. };
  36007. StopAnimationAction.prototype.execute = function () {
  36008. var scene = this._actionManager.getScene();
  36009. scene.stopAnimation(this._target);
  36010. };
  36011. StopAnimationAction.prototype.serialize = function (parent) {
  36012. return _super.prototype._serialize.call(this, {
  36013. name: "StopAnimationAction",
  36014. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  36015. }, parent);
  36016. };
  36017. return StopAnimationAction;
  36018. }(BABYLON.Action));
  36019. BABYLON.StopAnimationAction = StopAnimationAction;
  36020. var DoNothingAction = (function (_super) {
  36021. __extends(DoNothingAction, _super);
  36022. function DoNothingAction(triggerOptions, condition) {
  36023. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  36024. return _super.call(this, triggerOptions, condition) || this;
  36025. }
  36026. DoNothingAction.prototype.execute = function () {
  36027. };
  36028. DoNothingAction.prototype.serialize = function (parent) {
  36029. return _super.prototype._serialize.call(this, {
  36030. name: "DoNothingAction",
  36031. properties: []
  36032. }, parent);
  36033. };
  36034. return DoNothingAction;
  36035. }(BABYLON.Action));
  36036. BABYLON.DoNothingAction = DoNothingAction;
  36037. var CombineAction = (function (_super) {
  36038. __extends(CombineAction, _super);
  36039. function CombineAction(triggerOptions, children, condition) {
  36040. var _this = _super.call(this, triggerOptions, condition) || this;
  36041. _this.children = children;
  36042. return _this;
  36043. }
  36044. CombineAction.prototype._prepare = function () {
  36045. for (var index = 0; index < this.children.length; index++) {
  36046. this.children[index]._actionManager = this._actionManager;
  36047. this.children[index]._prepare();
  36048. }
  36049. };
  36050. CombineAction.prototype.execute = function (evt) {
  36051. for (var index = 0; index < this.children.length; index++) {
  36052. this.children[index].execute(evt);
  36053. }
  36054. };
  36055. CombineAction.prototype.serialize = function (parent) {
  36056. var serializationObject = _super.prototype._serialize.call(this, {
  36057. name: "CombineAction",
  36058. properties: [],
  36059. combine: []
  36060. }, parent);
  36061. for (var i = 0; i < this.children.length; i++) {
  36062. serializationObject.combine.push(this.children[i].serialize(null));
  36063. }
  36064. return serializationObject;
  36065. };
  36066. return CombineAction;
  36067. }(BABYLON.Action));
  36068. BABYLON.CombineAction = CombineAction;
  36069. var ExecuteCodeAction = (function (_super) {
  36070. __extends(ExecuteCodeAction, _super);
  36071. function ExecuteCodeAction(triggerOptions, func, condition) {
  36072. var _this = _super.call(this, triggerOptions, condition) || this;
  36073. _this.func = func;
  36074. return _this;
  36075. }
  36076. ExecuteCodeAction.prototype.execute = function (evt) {
  36077. this.func(evt);
  36078. };
  36079. return ExecuteCodeAction;
  36080. }(BABYLON.Action));
  36081. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  36082. var SetParentAction = (function (_super) {
  36083. __extends(SetParentAction, _super);
  36084. function SetParentAction(triggerOptions, target, parent, condition) {
  36085. var _this = _super.call(this, triggerOptions, condition) || this;
  36086. _this._target = target;
  36087. _this._parent = parent;
  36088. return _this;
  36089. }
  36090. SetParentAction.prototype._prepare = function () {
  36091. };
  36092. SetParentAction.prototype.execute = function () {
  36093. if (this._target.parent === this._parent) {
  36094. return;
  36095. }
  36096. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  36097. invertParentWorldMatrix.invert();
  36098. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  36099. this._target.parent = this._parent;
  36100. };
  36101. SetParentAction.prototype.serialize = function (parent) {
  36102. return _super.prototype._serialize.call(this, {
  36103. name: "SetParentAction",
  36104. properties: [
  36105. BABYLON.Action._GetTargetProperty(this._target),
  36106. BABYLON.Action._GetTargetProperty(this._parent),
  36107. ]
  36108. }, parent);
  36109. };
  36110. return SetParentAction;
  36111. }(BABYLON.Action));
  36112. BABYLON.SetParentAction = SetParentAction;
  36113. var PlaySoundAction = (function (_super) {
  36114. __extends(PlaySoundAction, _super);
  36115. function PlaySoundAction(triggerOptions, sound, condition) {
  36116. var _this = _super.call(this, triggerOptions, condition) || this;
  36117. _this._sound = sound;
  36118. return _this;
  36119. }
  36120. PlaySoundAction.prototype._prepare = function () {
  36121. };
  36122. PlaySoundAction.prototype.execute = function () {
  36123. if (this._sound !== undefined)
  36124. this._sound.play();
  36125. };
  36126. PlaySoundAction.prototype.serialize = function (parent) {
  36127. return _super.prototype._serialize.call(this, {
  36128. name: "PlaySoundAction",
  36129. properties: [{ name: "sound", value: this._sound.name }]
  36130. }, parent);
  36131. };
  36132. return PlaySoundAction;
  36133. }(BABYLON.Action));
  36134. BABYLON.PlaySoundAction = PlaySoundAction;
  36135. var StopSoundAction = (function (_super) {
  36136. __extends(StopSoundAction, _super);
  36137. function StopSoundAction(triggerOptions, sound, condition) {
  36138. var _this = _super.call(this, triggerOptions, condition) || this;
  36139. _this._sound = sound;
  36140. return _this;
  36141. }
  36142. StopSoundAction.prototype._prepare = function () {
  36143. };
  36144. StopSoundAction.prototype.execute = function () {
  36145. if (this._sound !== undefined)
  36146. this._sound.stop();
  36147. };
  36148. StopSoundAction.prototype.serialize = function (parent) {
  36149. return _super.prototype._serialize.call(this, {
  36150. name: "StopSoundAction",
  36151. properties: [{ name: "sound", value: this._sound.name }]
  36152. }, parent);
  36153. };
  36154. return StopSoundAction;
  36155. }(BABYLON.Action));
  36156. BABYLON.StopSoundAction = StopSoundAction;
  36157. })(BABYLON || (BABYLON = {}));
  36158. //# sourceMappingURL=babylon.directActions.js.map
  36159. var BABYLON;
  36160. (function (BABYLON) {
  36161. var Geometry = (function () {
  36162. function Geometry(id, scene, vertexData, updatable, mesh) {
  36163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36164. this._totalVertices = 0;
  36165. this._isDisposed = false;
  36166. this.id = id;
  36167. this._engine = scene.getEngine();
  36168. this._meshes = [];
  36169. this._scene = scene;
  36170. //Init vertex buffer cache
  36171. this._vertexBuffers = {};
  36172. this._indices = [];
  36173. // vertexData
  36174. if (vertexData) {
  36175. this.setAllVerticesData(vertexData, updatable);
  36176. }
  36177. else {
  36178. this._totalVertices = 0;
  36179. this._indices = [];
  36180. }
  36181. // applyToMesh
  36182. if (mesh) {
  36183. if (mesh instanceof BABYLON.LinesMesh) {
  36184. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  36185. this.updateExtend();
  36186. }
  36187. this.applyToMesh(mesh);
  36188. mesh.computeWorldMatrix(true);
  36189. }
  36190. }
  36191. Object.defineProperty(Geometry.prototype, "boundingBias", {
  36192. /**
  36193. * The Bias Vector to apply on the bounding elements (box/sphere), the max extend is computed as v += v * bias.x + bias.y, the min is computed as v -= v * bias.x + bias.y
  36194. * @returns The Bias Vector
  36195. */
  36196. get: function () {
  36197. return this._boundingBias;
  36198. },
  36199. set: function (value) {
  36200. if (this._boundingBias && this._boundingBias.equals(value)) {
  36201. return;
  36202. }
  36203. this._boundingBias = value.clone();
  36204. this.updateBoundingInfo(true, null);
  36205. },
  36206. enumerable: true,
  36207. configurable: true
  36208. });
  36209. Object.defineProperty(Geometry.prototype, "extend", {
  36210. get: function () {
  36211. return this._extend;
  36212. },
  36213. enumerable: true,
  36214. configurable: true
  36215. });
  36216. Geometry.prototype.getScene = function () {
  36217. return this._scene;
  36218. };
  36219. Geometry.prototype.getEngine = function () {
  36220. return this._engine;
  36221. };
  36222. Geometry.prototype.isReady = function () {
  36223. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  36224. };
  36225. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  36226. get: function () {
  36227. for (var index = 0; index < this._meshes.length; index++) {
  36228. if (!this._meshes[index].doNotSerialize) {
  36229. return false;
  36230. }
  36231. }
  36232. return true;
  36233. },
  36234. enumerable: true,
  36235. configurable: true
  36236. });
  36237. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  36238. vertexData.applyToGeometry(this, updatable);
  36239. this.notifyUpdate();
  36240. };
  36241. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  36242. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  36243. this.setVerticesBuffer(buffer);
  36244. };
  36245. Geometry.prototype.setVerticesBuffer = function (buffer) {
  36246. var kind = buffer.getKind();
  36247. if (this._vertexBuffers[kind]) {
  36248. this._vertexBuffers[kind].dispose();
  36249. }
  36250. this._vertexBuffers[kind] = buffer;
  36251. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36252. var data = buffer.getData();
  36253. var stride = buffer.getStrideSize();
  36254. this._totalVertices = data.length / stride;
  36255. this.updateExtend(data, stride);
  36256. var meshes = this._meshes;
  36257. var numOfMeshes = meshes.length;
  36258. for (var index = 0; index < numOfMeshes; index++) {
  36259. var mesh = meshes[index];
  36260. mesh._resetPointsArrayCache();
  36261. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36262. mesh._createGlobalSubMesh();
  36263. mesh.computeWorldMatrix(true);
  36264. }
  36265. }
  36266. this.notifyUpdate(kind);
  36267. };
  36268. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  36269. var vertexBuffer = this.getVertexBuffer(kind);
  36270. if (!vertexBuffer) {
  36271. return;
  36272. }
  36273. vertexBuffer.updateDirectly(data, offset);
  36274. this.notifyUpdate(kind);
  36275. };
  36276. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  36277. var vertexBuffer = this.getVertexBuffer(kind);
  36278. if (!vertexBuffer) {
  36279. return;
  36280. }
  36281. vertexBuffer.update(data);
  36282. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36283. var stride = vertexBuffer.getStrideSize();
  36284. this._totalVertices = data.length / stride;
  36285. this.updateBoundingInfo(updateExtends, data);
  36286. }
  36287. this.notifyUpdate(kind);
  36288. };
  36289. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  36290. if (updateExtends) {
  36291. this.updateExtend(data);
  36292. }
  36293. var meshes = this._meshes;
  36294. var numOfMeshes = meshes.length;
  36295. for (var index = 0; index < numOfMeshes; index++) {
  36296. var mesh = meshes[index];
  36297. mesh._resetPointsArrayCache();
  36298. if (updateExtends) {
  36299. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36300. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  36301. var subMesh = mesh.subMeshes[subIndex];
  36302. subMesh.refreshBoundingInfo();
  36303. }
  36304. }
  36305. }
  36306. };
  36307. Geometry.prototype.getTotalVertices = function () {
  36308. if (!this.isReady()) {
  36309. return 0;
  36310. }
  36311. return this._totalVertices;
  36312. };
  36313. Geometry.prototype.getVerticesData = function (kind, copyWhenShared) {
  36314. var vertexBuffer = this.getVertexBuffer(kind);
  36315. if (!vertexBuffer) {
  36316. return null;
  36317. }
  36318. var orig = vertexBuffer.getData();
  36319. if (!copyWhenShared || this._meshes.length === 1) {
  36320. return orig;
  36321. }
  36322. else {
  36323. var len = orig.length;
  36324. var copy = [];
  36325. for (var i = 0; i < len; i++) {
  36326. copy.push(orig[i]);
  36327. }
  36328. return copy;
  36329. }
  36330. };
  36331. Geometry.prototype.getVertexBuffer = function (kind) {
  36332. if (!this.isReady()) {
  36333. return null;
  36334. }
  36335. return this._vertexBuffers[kind];
  36336. };
  36337. Geometry.prototype.getVertexBuffers = function () {
  36338. if (!this.isReady()) {
  36339. return null;
  36340. }
  36341. return this._vertexBuffers;
  36342. };
  36343. Geometry.prototype.isVerticesDataPresent = function (kind) {
  36344. if (!this._vertexBuffers) {
  36345. if (this._delayInfo) {
  36346. return this._delayInfo.indexOf(kind) !== -1;
  36347. }
  36348. return false;
  36349. }
  36350. return this._vertexBuffers[kind] !== undefined;
  36351. };
  36352. Geometry.prototype.getVerticesDataKinds = function () {
  36353. var result = [];
  36354. var kind;
  36355. if (!this._vertexBuffers && this._delayInfo) {
  36356. for (kind in this._delayInfo) {
  36357. result.push(kind);
  36358. }
  36359. }
  36360. else {
  36361. for (kind in this._vertexBuffers) {
  36362. result.push(kind);
  36363. }
  36364. }
  36365. return result;
  36366. };
  36367. Geometry.prototype.setIndices = function (indices, totalVertices) {
  36368. if (this._indexBuffer) {
  36369. this._engine._releaseBuffer(this._indexBuffer);
  36370. }
  36371. this._indices = indices;
  36372. if (this._meshes.length !== 0 && this._indices) {
  36373. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36374. }
  36375. if (totalVertices !== undefined) {
  36376. this._totalVertices = totalVertices;
  36377. }
  36378. var meshes = this._meshes;
  36379. var numOfMeshes = meshes.length;
  36380. for (var index = 0; index < numOfMeshes; index++) {
  36381. meshes[index]._createGlobalSubMesh();
  36382. }
  36383. this.notifyUpdate();
  36384. };
  36385. Geometry.prototype.getTotalIndices = function () {
  36386. if (!this.isReady()) {
  36387. return 0;
  36388. }
  36389. return this._indices.length;
  36390. };
  36391. Geometry.prototype.getIndices = function (copyWhenShared) {
  36392. if (!this.isReady()) {
  36393. return null;
  36394. }
  36395. var orig = this._indices;
  36396. if (!copyWhenShared || this._meshes.length === 1) {
  36397. return orig;
  36398. }
  36399. else {
  36400. var len = orig.length;
  36401. var copy = [];
  36402. for (var i = 0; i < len; i++) {
  36403. copy.push(orig[i]);
  36404. }
  36405. return copy;
  36406. }
  36407. };
  36408. Geometry.prototype.getIndexBuffer = function () {
  36409. if (!this.isReady()) {
  36410. return null;
  36411. }
  36412. return this._indexBuffer;
  36413. };
  36414. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  36415. var meshes = this._meshes;
  36416. var index = meshes.indexOf(mesh);
  36417. if (index === -1) {
  36418. return;
  36419. }
  36420. for (var kind in this._vertexBuffers) {
  36421. this._vertexBuffers[kind].dispose();
  36422. }
  36423. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  36424. this._indexBuffer = null;
  36425. }
  36426. meshes.splice(index, 1);
  36427. mesh._geometry = null;
  36428. if (meshes.length === 0 && shouldDispose) {
  36429. this.dispose();
  36430. }
  36431. };
  36432. Geometry.prototype.applyToMesh = function (mesh) {
  36433. if (mesh._geometry === this) {
  36434. return;
  36435. }
  36436. var previousGeometry = mesh._geometry;
  36437. if (previousGeometry) {
  36438. previousGeometry.releaseForMesh(mesh);
  36439. }
  36440. var meshes = this._meshes;
  36441. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  36442. mesh._geometry = this;
  36443. this._scene.pushGeometry(this);
  36444. meshes.push(mesh);
  36445. if (this.isReady()) {
  36446. this._applyToMesh(mesh);
  36447. }
  36448. else {
  36449. mesh._boundingInfo = this._boundingInfo;
  36450. }
  36451. };
  36452. Geometry.prototype.updateExtend = function (data, stride) {
  36453. if (data === void 0) { data = null; }
  36454. if (!data) {
  36455. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  36456. }
  36457. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  36458. };
  36459. Geometry.prototype._applyToMesh = function (mesh) {
  36460. var numOfMeshes = this._meshes.length;
  36461. // vertexBuffers
  36462. for (var kind in this._vertexBuffers) {
  36463. if (numOfMeshes === 1) {
  36464. this._vertexBuffers[kind].create();
  36465. }
  36466. this._vertexBuffers[kind].getBuffer().references = numOfMeshes;
  36467. if (kind === BABYLON.VertexBuffer.PositionKind) {
  36468. mesh._resetPointsArrayCache();
  36469. if (!this._extend) {
  36470. this.updateExtend(this._vertexBuffers[kind].getData());
  36471. }
  36472. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36473. mesh._createGlobalSubMesh();
  36474. //bounding info was just created again, world matrix should be applied again.
  36475. mesh._updateBoundingInfo();
  36476. }
  36477. }
  36478. // indexBuffer
  36479. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  36480. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  36481. }
  36482. if (this._indexBuffer) {
  36483. this._indexBuffer.references = numOfMeshes;
  36484. }
  36485. };
  36486. Geometry.prototype.notifyUpdate = function (kind) {
  36487. if (this.onGeometryUpdated) {
  36488. this.onGeometryUpdated(this, kind);
  36489. }
  36490. };
  36491. Geometry.prototype.load = function (scene, onLoaded) {
  36492. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  36493. return;
  36494. }
  36495. if (this.isReady()) {
  36496. if (onLoaded) {
  36497. onLoaded();
  36498. }
  36499. return;
  36500. }
  36501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  36502. this._queueLoad(scene, onLoaded);
  36503. };
  36504. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  36505. var _this = this;
  36506. scene._addPendingData(this);
  36507. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  36508. _this._delayLoadingFunction(JSON.parse(data), _this);
  36509. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  36510. _this._delayInfo = [];
  36511. scene._removePendingData(_this);
  36512. var meshes = _this._meshes;
  36513. var numOfMeshes = meshes.length;
  36514. for (var index = 0; index < numOfMeshes; index++) {
  36515. _this._applyToMesh(meshes[index]);
  36516. }
  36517. if (onLoaded) {
  36518. onLoaded();
  36519. }
  36520. }, function () { }, scene.database);
  36521. };
  36522. /**
  36523. * Invert the geometry to move from a right handed system to a left handed one.
  36524. */
  36525. Geometry.prototype.toLeftHanded = function () {
  36526. // Flip faces
  36527. var tIndices = this.getIndices(false);
  36528. if (tIndices != null && tIndices.length > 0) {
  36529. for (var i = 0; i < tIndices.length; i += 3) {
  36530. var tTemp = tIndices[i + 0];
  36531. tIndices[i + 0] = tIndices[i + 2];
  36532. tIndices[i + 2] = tTemp;
  36533. }
  36534. this.setIndices(tIndices);
  36535. }
  36536. // Negate position.z
  36537. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  36538. if (tPositions != null && tPositions.length > 0) {
  36539. for (var i = 0; i < tPositions.length; i += 3) {
  36540. tPositions[i + 2] = -tPositions[i + 2];
  36541. }
  36542. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  36543. }
  36544. // Negate normal.z
  36545. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  36546. if (tNormals != null && tNormals.length > 0) {
  36547. for (var i = 0; i < tNormals.length; i += 3) {
  36548. tNormals[i + 2] = -tNormals[i + 2];
  36549. }
  36550. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  36551. }
  36552. };
  36553. Geometry.prototype.isDisposed = function () {
  36554. return this._isDisposed;
  36555. };
  36556. Geometry.prototype.dispose = function () {
  36557. var meshes = this._meshes;
  36558. var numOfMeshes = meshes.length;
  36559. var index;
  36560. for (index = 0; index < numOfMeshes; index++) {
  36561. this.releaseForMesh(meshes[index]);
  36562. }
  36563. this._meshes = [];
  36564. for (var kind in this._vertexBuffers) {
  36565. this._vertexBuffers[kind].dispose();
  36566. }
  36567. this._vertexBuffers = {};
  36568. this._totalVertices = 0;
  36569. if (this._indexBuffer) {
  36570. this._engine._releaseBuffer(this._indexBuffer);
  36571. }
  36572. this._indexBuffer = null;
  36573. this._indices = [];
  36574. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  36575. this.delayLoadingFile = null;
  36576. this._delayLoadingFunction = null;
  36577. this._delayInfo = [];
  36578. this._boundingInfo = null;
  36579. this._scene.removeGeometry(this);
  36580. this._isDisposed = true;
  36581. };
  36582. Geometry.prototype.copy = function (id) {
  36583. var vertexData = new BABYLON.VertexData();
  36584. vertexData.indices = [];
  36585. var indices = this.getIndices();
  36586. for (var index = 0; index < indices.length; index++) {
  36587. vertexData.indices.push(indices[index]);
  36588. }
  36589. var updatable = false;
  36590. var stopChecking = false;
  36591. var kind;
  36592. for (kind in this._vertexBuffers) {
  36593. // using slice() to make a copy of the array and not just reference it
  36594. var data = this.getVerticesData(kind);
  36595. if (data instanceof Float32Array) {
  36596. vertexData.set(new Float32Array(data), kind);
  36597. }
  36598. else {
  36599. vertexData.set(data.slice(0), kind);
  36600. }
  36601. if (!stopChecking) {
  36602. updatable = this.getVertexBuffer(kind).isUpdatable();
  36603. stopChecking = !updatable;
  36604. }
  36605. }
  36606. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  36607. geometry.delayLoadState = this.delayLoadState;
  36608. geometry.delayLoadingFile = this.delayLoadingFile;
  36609. geometry._delayLoadingFunction = this._delayLoadingFunction;
  36610. for (kind in this._delayInfo) {
  36611. geometry._delayInfo = geometry._delayInfo || [];
  36612. geometry._delayInfo.push(kind);
  36613. }
  36614. // Bounding info
  36615. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  36616. return geometry;
  36617. };
  36618. Geometry.prototype.serialize = function () {
  36619. var serializationObject = {};
  36620. serializationObject.id = this.id;
  36621. if (BABYLON.Tags.HasTags(this)) {
  36622. serializationObject.tags = BABYLON.Tags.GetTags(this);
  36623. }
  36624. return serializationObject;
  36625. };
  36626. Geometry.prototype.serializeVerticeData = function () {
  36627. var serializationObject = this.serialize();
  36628. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36629. serializationObject.positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  36630. }
  36631. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36632. serializationObject.normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  36633. }
  36634. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36635. serializationObject.uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  36636. }
  36637. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36638. serializationObject.uv2s = this.getVerticesData(BABYLON.VertexBuffer.UV2Kind);
  36639. }
  36640. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36641. serializationObject.uv3s = this.getVerticesData(BABYLON.VertexBuffer.UV3Kind);
  36642. }
  36643. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36644. serializationObject.uv4s = this.getVerticesData(BABYLON.VertexBuffer.UV4Kind);
  36645. }
  36646. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36647. serializationObject.uv5s = this.getVerticesData(BABYLON.VertexBuffer.UV5Kind);
  36648. }
  36649. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36650. serializationObject.uv6s = this.getVerticesData(BABYLON.VertexBuffer.UV6Kind);
  36651. }
  36652. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36653. serializationObject.colors = this.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  36654. }
  36655. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36656. serializationObject.matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  36657. serializationObject.matricesIndices._isExpanded = true;
  36658. }
  36659. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36660. serializationObject.matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  36661. }
  36662. serializationObject.indices = this.getIndices();
  36663. return serializationObject;
  36664. };
  36665. // Statics
  36666. Geometry.ExtractFromMesh = function (mesh, id) {
  36667. var geometry = mesh._geometry;
  36668. if (!geometry) {
  36669. return null;
  36670. }
  36671. return geometry.copy(id);
  36672. };
  36673. /**
  36674. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  36675. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  36676. * Be aware Math.random() could cause collisions, but:
  36677. * "All but 6 of the 128 bits of the ID are randomly generated, which means that for any two ids, there's a 1 in 2^^122 (or 5.3x10^^36) chance they'll collide"
  36678. */
  36679. Geometry.RandomId = function () {
  36680. return BABYLON.Tools.RandomId();
  36681. };
  36682. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  36683. var scene = mesh.getScene();
  36684. // Geometry
  36685. var geometryId = parsedGeometry.geometryId;
  36686. if (geometryId) {
  36687. var geometry = scene.getGeometryByID(geometryId);
  36688. if (geometry) {
  36689. geometry.applyToMesh(mesh);
  36690. }
  36691. }
  36692. else if (parsedGeometry instanceof ArrayBuffer) {
  36693. var binaryInfo = mesh._binaryInfo;
  36694. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  36695. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  36696. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  36697. }
  36698. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  36699. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  36700. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  36701. }
  36702. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  36703. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  36704. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  36705. }
  36706. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  36707. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  36708. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  36709. }
  36710. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  36711. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  36712. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  36713. }
  36714. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  36715. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  36716. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  36717. }
  36718. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  36719. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  36720. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  36721. }
  36722. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  36723. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  36724. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  36725. }
  36726. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  36727. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  36728. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  36729. }
  36730. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  36731. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  36732. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  36733. }
  36734. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  36735. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  36736. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  36737. }
  36738. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  36739. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  36740. mesh.setIndices(indicesData);
  36741. }
  36742. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  36743. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  36744. mesh.subMeshes = [];
  36745. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  36746. var materialIndex = subMeshesData[(i * 5) + 0];
  36747. var verticesStart = subMeshesData[(i * 5) + 1];
  36748. var verticesCount = subMeshesData[(i * 5) + 2];
  36749. var indexStart = subMeshesData[(i * 5) + 3];
  36750. var indexCount = subMeshesData[(i * 5) + 4];
  36751. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  36752. }
  36753. }
  36754. }
  36755. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  36756. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, false);
  36757. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, false);
  36758. if (parsedGeometry.uvs) {
  36759. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, false);
  36760. }
  36761. if (parsedGeometry.uvs2) {
  36762. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, false);
  36763. }
  36764. if (parsedGeometry.uvs3) {
  36765. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, false);
  36766. }
  36767. if (parsedGeometry.uvs4) {
  36768. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, false);
  36769. }
  36770. if (parsedGeometry.uvs5) {
  36771. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, false);
  36772. }
  36773. if (parsedGeometry.uvs6) {
  36774. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, false);
  36775. }
  36776. if (parsedGeometry.colors) {
  36777. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), false);
  36778. }
  36779. if (parsedGeometry.matricesIndices) {
  36780. if (!parsedGeometry.matricesIndices._isExpanded) {
  36781. var floatIndices = [];
  36782. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  36783. var matricesIndex = parsedGeometry.matricesIndices[i];
  36784. floatIndices.push(matricesIndex & 0x000000FF);
  36785. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36786. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36787. floatIndices.push(matricesIndex >> 24);
  36788. }
  36789. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  36790. }
  36791. else {
  36792. delete parsedGeometry.matricesIndices._isExpanded;
  36793. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, false);
  36794. }
  36795. }
  36796. if (parsedGeometry.matricesIndicesExtra) {
  36797. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  36798. var floatIndices = [];
  36799. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  36800. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  36801. floatIndices.push(matricesIndex & 0x000000FF);
  36802. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  36803. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  36804. floatIndices.push(matricesIndex >> 24);
  36805. }
  36806. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, false);
  36807. }
  36808. else {
  36809. delete parsedGeometry.matricesIndices._isExpanded;
  36810. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, false);
  36811. }
  36812. }
  36813. if (parsedGeometry.matricesWeights) {
  36814. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, false);
  36815. }
  36816. if (parsedGeometry.matricesWeightsExtra) {
  36817. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, false);
  36818. }
  36819. mesh.setIndices(parsedGeometry.indices);
  36820. }
  36821. // SubMeshes
  36822. if (parsedGeometry.subMeshes) {
  36823. mesh.subMeshes = [];
  36824. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  36825. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  36826. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  36827. }
  36828. }
  36829. // Flat shading
  36830. if (mesh._shouldGenerateFlatShading) {
  36831. mesh.convertToFlatShadedMesh();
  36832. delete mesh._shouldGenerateFlatShading;
  36833. }
  36834. // Update
  36835. mesh.computeWorldMatrix(true);
  36836. // Octree
  36837. if (scene['_selectionOctree']) {
  36838. scene['_selectionOctree'].addMesh(mesh);
  36839. }
  36840. };
  36841. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  36842. if (scene.getGeometryByID(parsedVertexData.id)) {
  36843. return null; // null since geometry could be something else than a box...
  36844. }
  36845. var geometry = new Geometry(parsedVertexData.id, scene);
  36846. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  36847. if (parsedVertexData.delayLoadingFile) {
  36848. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  36849. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  36850. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  36851. geometry._delayInfo = [];
  36852. if (parsedVertexData.hasUVs) {
  36853. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  36854. }
  36855. if (parsedVertexData.hasUVs2) {
  36856. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  36857. }
  36858. if (parsedVertexData.hasUVs3) {
  36859. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  36860. }
  36861. if (parsedVertexData.hasUVs4) {
  36862. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  36863. }
  36864. if (parsedVertexData.hasUVs5) {
  36865. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  36866. }
  36867. if (parsedVertexData.hasUVs6) {
  36868. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  36869. }
  36870. if (parsedVertexData.hasColors) {
  36871. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  36872. }
  36873. if (parsedVertexData.hasMatricesIndices) {
  36874. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  36875. }
  36876. if (parsedVertexData.hasMatricesWeights) {
  36877. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  36878. }
  36879. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  36880. }
  36881. else {
  36882. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  36883. }
  36884. scene.pushGeometry(geometry, true);
  36885. return geometry;
  36886. };
  36887. return Geometry;
  36888. }());
  36889. BABYLON.Geometry = Geometry;
  36890. /////// Primitives //////////////////////////////////////////////
  36891. (function (Geometry) {
  36892. var Primitives;
  36893. (function (Primitives) {
  36894. /// Abstract class
  36895. var _Primitive = (function (_super) {
  36896. __extends(_Primitive, _super);
  36897. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  36898. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  36899. _this._canBeRegenerated = _canBeRegenerated;
  36900. _this._beingRegenerated = true;
  36901. _this.regenerate();
  36902. _this._beingRegenerated = false;
  36903. return _this;
  36904. }
  36905. _Primitive.prototype.canBeRegenerated = function () {
  36906. return this._canBeRegenerated;
  36907. };
  36908. _Primitive.prototype.regenerate = function () {
  36909. if (!this._canBeRegenerated) {
  36910. return;
  36911. }
  36912. this._beingRegenerated = true;
  36913. this.setAllVerticesData(this._regenerateVertexData(), false);
  36914. this._beingRegenerated = false;
  36915. };
  36916. _Primitive.prototype.asNewGeometry = function (id) {
  36917. return _super.prototype.copy.call(this, id);
  36918. };
  36919. // overrides
  36920. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  36921. if (!this._beingRegenerated) {
  36922. return;
  36923. }
  36924. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  36925. };
  36926. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  36927. if (!this._beingRegenerated) {
  36928. return;
  36929. }
  36930. _super.prototype.setVerticesData.call(this, kind, data, false);
  36931. };
  36932. // to override
  36933. // protected
  36934. _Primitive.prototype._regenerateVertexData = function () {
  36935. throw new Error("Abstract method");
  36936. };
  36937. _Primitive.prototype.copy = function (id) {
  36938. throw new Error("Must be overriden in sub-classes.");
  36939. };
  36940. _Primitive.prototype.serialize = function () {
  36941. var serializationObject = _super.prototype.serialize.call(this);
  36942. serializationObject.canBeRegenerated = this.canBeRegenerated();
  36943. return serializationObject;
  36944. };
  36945. return _Primitive;
  36946. }(Geometry));
  36947. Primitives._Primitive = _Primitive;
  36948. var Ribbon = (function (_super) {
  36949. __extends(Ribbon, _super);
  36950. // Members
  36951. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  36952. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36953. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36954. _this.pathArray = pathArray;
  36955. _this.closeArray = closeArray;
  36956. _this.closePath = closePath;
  36957. _this.offset = offset;
  36958. _this.side = side;
  36959. return _this;
  36960. }
  36961. Ribbon.prototype._regenerateVertexData = function () {
  36962. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  36963. };
  36964. Ribbon.prototype.copy = function (id) {
  36965. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  36966. };
  36967. return Ribbon;
  36968. }(_Primitive));
  36969. Primitives.Ribbon = Ribbon;
  36970. var Box = (function (_super) {
  36971. __extends(Box, _super);
  36972. // Members
  36973. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  36974. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  36975. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  36976. _this.size = size;
  36977. _this.side = side;
  36978. return _this;
  36979. }
  36980. Box.prototype._regenerateVertexData = function () {
  36981. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  36982. };
  36983. Box.prototype.copy = function (id) {
  36984. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  36985. };
  36986. Box.prototype.serialize = function () {
  36987. var serializationObject = _super.prototype.serialize.call(this);
  36988. serializationObject.size = this.size;
  36989. return serializationObject;
  36990. };
  36991. Box.Parse = function (parsedBox, scene) {
  36992. if (scene.getGeometryByID(parsedBox.id)) {
  36993. return null; // null since geometry could be something else than a box...
  36994. }
  36995. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  36996. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  36997. scene.pushGeometry(box, true);
  36998. return box;
  36999. };
  37000. return Box;
  37001. }(_Primitive));
  37002. Primitives.Box = Box;
  37003. var Sphere = (function (_super) {
  37004. __extends(Sphere, _super);
  37005. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  37006. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37007. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37008. _this.segments = segments;
  37009. _this.diameter = diameter;
  37010. _this.side = side;
  37011. return _this;
  37012. }
  37013. Sphere.prototype._regenerateVertexData = function () {
  37014. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  37015. };
  37016. Sphere.prototype.copy = function (id) {
  37017. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  37018. };
  37019. Sphere.prototype.serialize = function () {
  37020. var serializationObject = _super.prototype.serialize.call(this);
  37021. serializationObject.segments = this.segments;
  37022. serializationObject.diameter = this.diameter;
  37023. return serializationObject;
  37024. };
  37025. Sphere.Parse = function (parsedSphere, scene) {
  37026. if (scene.getGeometryByID(parsedSphere.id)) {
  37027. return null; // null since geometry could be something else than a sphere...
  37028. }
  37029. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  37030. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  37031. scene.pushGeometry(sphere, true);
  37032. return sphere;
  37033. };
  37034. return Sphere;
  37035. }(_Primitive));
  37036. Primitives.Sphere = Sphere;
  37037. var Disc = (function (_super) {
  37038. __extends(Disc, _super);
  37039. // Members
  37040. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  37041. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37042. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37043. _this.radius = radius;
  37044. _this.tessellation = tessellation;
  37045. _this.side = side;
  37046. return _this;
  37047. }
  37048. Disc.prototype._regenerateVertexData = function () {
  37049. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  37050. };
  37051. Disc.prototype.copy = function (id) {
  37052. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  37053. };
  37054. return Disc;
  37055. }(_Primitive));
  37056. Primitives.Disc = Disc;
  37057. var Cylinder = (function (_super) {
  37058. __extends(Cylinder, _super);
  37059. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  37060. if (subdivisions === void 0) { subdivisions = 1; }
  37061. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37062. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37063. _this.height = height;
  37064. _this.diameterTop = diameterTop;
  37065. _this.diameterBottom = diameterBottom;
  37066. _this.tessellation = tessellation;
  37067. _this.subdivisions = subdivisions;
  37068. _this.side = side;
  37069. return _this;
  37070. }
  37071. Cylinder.prototype._regenerateVertexData = function () {
  37072. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  37073. };
  37074. Cylinder.prototype.copy = function (id) {
  37075. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  37076. };
  37077. Cylinder.prototype.serialize = function () {
  37078. var serializationObject = _super.prototype.serialize.call(this);
  37079. serializationObject.height = this.height;
  37080. serializationObject.diameterTop = this.diameterTop;
  37081. serializationObject.diameterBottom = this.diameterBottom;
  37082. serializationObject.tessellation = this.tessellation;
  37083. return serializationObject;
  37084. };
  37085. Cylinder.Parse = function (parsedCylinder, scene) {
  37086. if (scene.getGeometryByID(parsedCylinder.id)) {
  37087. return null; // null since geometry could be something else than a cylinder...
  37088. }
  37089. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  37090. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  37091. scene.pushGeometry(cylinder, true);
  37092. return cylinder;
  37093. };
  37094. return Cylinder;
  37095. }(_Primitive));
  37096. Primitives.Cylinder = Cylinder;
  37097. var Torus = (function (_super) {
  37098. __extends(Torus, _super);
  37099. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  37100. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37101. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37102. _this.diameter = diameter;
  37103. _this.thickness = thickness;
  37104. _this.tessellation = tessellation;
  37105. _this.side = side;
  37106. return _this;
  37107. }
  37108. Torus.prototype._regenerateVertexData = function () {
  37109. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  37110. };
  37111. Torus.prototype.copy = function (id) {
  37112. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  37113. };
  37114. Torus.prototype.serialize = function () {
  37115. var serializationObject = _super.prototype.serialize.call(this);
  37116. serializationObject.diameter = this.diameter;
  37117. serializationObject.thickness = this.thickness;
  37118. serializationObject.tessellation = this.tessellation;
  37119. return serializationObject;
  37120. };
  37121. Torus.Parse = function (parsedTorus, scene) {
  37122. if (scene.getGeometryByID(parsedTorus.id)) {
  37123. return null; // null since geometry could be something else than a torus...
  37124. }
  37125. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  37126. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  37127. scene.pushGeometry(torus, true);
  37128. return torus;
  37129. };
  37130. return Torus;
  37131. }(_Primitive));
  37132. Primitives.Torus = Torus;
  37133. var Ground = (function (_super) {
  37134. __extends(Ground, _super);
  37135. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  37136. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37137. _this.width = width;
  37138. _this.height = height;
  37139. _this.subdivisions = subdivisions;
  37140. return _this;
  37141. }
  37142. Ground.prototype._regenerateVertexData = function () {
  37143. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  37144. };
  37145. Ground.prototype.copy = function (id) {
  37146. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  37147. };
  37148. Ground.prototype.serialize = function () {
  37149. var serializationObject = _super.prototype.serialize.call(this);
  37150. serializationObject.width = this.width;
  37151. serializationObject.height = this.height;
  37152. serializationObject.subdivisions = this.subdivisions;
  37153. return serializationObject;
  37154. };
  37155. Ground.Parse = function (parsedGround, scene) {
  37156. if (scene.getGeometryByID(parsedGround.id)) {
  37157. return null; // null since geometry could be something else than a ground...
  37158. }
  37159. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  37160. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  37161. scene.pushGeometry(ground, true);
  37162. return ground;
  37163. };
  37164. return Ground;
  37165. }(_Primitive));
  37166. Primitives.Ground = Ground;
  37167. var TiledGround = (function (_super) {
  37168. __extends(TiledGround, _super);
  37169. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  37170. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37171. _this.xmin = xmin;
  37172. _this.zmin = zmin;
  37173. _this.xmax = xmax;
  37174. _this.zmax = zmax;
  37175. _this.subdivisions = subdivisions;
  37176. _this.precision = precision;
  37177. return _this;
  37178. }
  37179. TiledGround.prototype._regenerateVertexData = function () {
  37180. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  37181. };
  37182. TiledGround.prototype.copy = function (id) {
  37183. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  37184. };
  37185. return TiledGround;
  37186. }(_Primitive));
  37187. Primitives.TiledGround = TiledGround;
  37188. var Plane = (function (_super) {
  37189. __extends(Plane, _super);
  37190. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  37191. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37192. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37193. _this.size = size;
  37194. _this.side = side;
  37195. return _this;
  37196. }
  37197. Plane.prototype._regenerateVertexData = function () {
  37198. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  37199. };
  37200. Plane.prototype.copy = function (id) {
  37201. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  37202. };
  37203. Plane.prototype.serialize = function () {
  37204. var serializationObject = _super.prototype.serialize.call(this);
  37205. serializationObject.size = this.size;
  37206. return serializationObject;
  37207. };
  37208. Plane.Parse = function (parsedPlane, scene) {
  37209. if (scene.getGeometryByID(parsedPlane.id)) {
  37210. return null; // null since geometry could be something else than a ground...
  37211. }
  37212. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  37213. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  37214. scene.pushGeometry(plane, true);
  37215. return plane;
  37216. };
  37217. return Plane;
  37218. }(_Primitive));
  37219. Primitives.Plane = Plane;
  37220. var TorusKnot = (function (_super) {
  37221. __extends(TorusKnot, _super);
  37222. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  37223. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  37224. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  37225. _this.radius = radius;
  37226. _this.tube = tube;
  37227. _this.radialSegments = radialSegments;
  37228. _this.tubularSegments = tubularSegments;
  37229. _this.p = p;
  37230. _this.q = q;
  37231. _this.side = side;
  37232. return _this;
  37233. }
  37234. TorusKnot.prototype._regenerateVertexData = function () {
  37235. 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 });
  37236. };
  37237. TorusKnot.prototype.copy = function (id) {
  37238. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  37239. };
  37240. TorusKnot.prototype.serialize = function () {
  37241. var serializationObject = _super.prototype.serialize.call(this);
  37242. serializationObject.radius = this.radius;
  37243. serializationObject.tube = this.tube;
  37244. serializationObject.radialSegments = this.radialSegments;
  37245. serializationObject.tubularSegments = this.tubularSegments;
  37246. serializationObject.p = this.p;
  37247. serializationObject.q = this.q;
  37248. return serializationObject;
  37249. };
  37250. ;
  37251. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  37252. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  37253. return null; // null since geometry could be something else than a ground...
  37254. }
  37255. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  37256. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  37257. scene.pushGeometry(torusKnot, true);
  37258. return torusKnot;
  37259. };
  37260. return TorusKnot;
  37261. }(_Primitive));
  37262. Primitives.TorusKnot = TorusKnot;
  37263. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  37264. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  37265. })(BABYLON || (BABYLON = {}));
  37266. //# sourceMappingURL=babylon.geometry.js.map
  37267. var BABYLON;
  37268. (function (BABYLON) {
  37269. var GroundMesh = (function (_super) {
  37270. __extends(GroundMesh, _super);
  37271. function GroundMesh(name, scene) {
  37272. var _this = _super.call(this, name, scene) || this;
  37273. _this.generateOctree = false;
  37274. _this._worldInverse = new BABYLON.Matrix();
  37275. return _this;
  37276. }
  37277. GroundMesh.prototype.getClassName = function () {
  37278. return "GroundMesh";
  37279. };
  37280. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  37281. get: function () {
  37282. return Math.min(this._subdivisionsX, this._subdivisionsY);
  37283. },
  37284. enumerable: true,
  37285. configurable: true
  37286. });
  37287. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  37288. get: function () {
  37289. return this._subdivisionsX;
  37290. },
  37291. enumerable: true,
  37292. configurable: true
  37293. });
  37294. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  37295. get: function () {
  37296. return this._subdivisionsY;
  37297. },
  37298. enumerable: true,
  37299. configurable: true
  37300. });
  37301. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  37302. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  37303. this._subdivisionsX = chunksCount;
  37304. this._subdivisionsY = chunksCount;
  37305. this.subdivide(chunksCount);
  37306. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  37307. };
  37308. /**
  37309. * Returns a height (y) value in the Worl system :
  37310. * the ground altitude at the coordinates (x, z) expressed in the World system.
  37311. * Returns the ground y position if (x, z) are outside the ground surface.
  37312. * Not pertinent if the ground is rotated.
  37313. */
  37314. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  37315. // express x and y in the ground local system
  37316. x -= this.position.x;
  37317. z -= this.position.z;
  37318. x /= this.scaling.x;
  37319. z /= this.scaling.z;
  37320. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37321. return this.position.y;
  37322. }
  37323. if (!this._heightQuads || this._heightQuads.length == 0) {
  37324. this._initHeightQuads();
  37325. this._computeHeightQuads();
  37326. }
  37327. var facet = this._getFacetAt(x, z);
  37328. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  37329. // return y in the World system
  37330. return y * this.scaling.y + this.position.y;
  37331. };
  37332. /**
  37333. * Returns a normalized vector (Vector3) orthogonal to the ground
  37334. * at the ground coordinates (x, z) expressed in the World system.
  37335. * Returns Vector3(0, 1, 0) if (x, z) are outside the ground surface.
  37336. * Not pertinent if the ground is rotated.
  37337. */
  37338. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  37339. var normal = new BABYLON.Vector3(0, 1, 0);
  37340. this.getNormalAtCoordinatesToRef(x, z, normal);
  37341. return normal;
  37342. };
  37343. /**
  37344. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  37345. * at the ground coordinates (x, z) expressed in the World system.
  37346. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  37347. * Not pertinent if the ground is rotated.
  37348. */
  37349. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  37350. // express x and y in the ground local system
  37351. x -= this.position.x;
  37352. z -= this.position.z;
  37353. x /= this.scaling.x;
  37354. z /= this.scaling.z;
  37355. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  37356. return;
  37357. }
  37358. if (!this._heightQuads || this._heightQuads.length == 0) {
  37359. this._initHeightQuads();
  37360. this._computeHeightQuads();
  37361. }
  37362. var facet = this._getFacetAt(x, z);
  37363. ref.x = facet.x;
  37364. ref.y = facet.y;
  37365. ref.z = facet.z;
  37366. };
  37367. /**
  37368. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  37369. * if the ground has been updated.
  37370. * This can be used in the render loop
  37371. */
  37372. GroundMesh.prototype.updateCoordinateHeights = function () {
  37373. if (!this._heightQuads || this._heightQuads.length == 0) {
  37374. this._initHeightQuads();
  37375. }
  37376. this._computeHeightQuads();
  37377. };
  37378. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  37379. GroundMesh.prototype._getFacetAt = function (x, z) {
  37380. // retrieve col and row from x, z coordinates in the ground local system
  37381. var subdivisionsX = this._subdivisionsX;
  37382. var subdivisionsY = this._subdivisionsY;
  37383. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  37384. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  37385. var quad = this._heightQuads[row * this._subdivisionsX + col];
  37386. var facet;
  37387. if (z < quad.slope.x * x + quad.slope.y) {
  37388. facet = quad.facet1;
  37389. }
  37390. else {
  37391. facet = quad.facet2;
  37392. }
  37393. return facet;
  37394. };
  37395. // Creates and populates the heightMap array with "facet" elements :
  37396. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  37397. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37398. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37399. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37400. GroundMesh.prototype._initHeightQuads = function () {
  37401. var subdivisionsX = this._subdivisionsX;
  37402. var subdivisionsY = this._subdivisionsY;
  37403. this._heightQuads = new Array();
  37404. for (var row = 0; row < subdivisionsY; row++) {
  37405. for (var col = 0; col < subdivisionsX; col++) {
  37406. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0, 0, 0, 0), facet2: new BABYLON.Vector4(0, 0, 0, 0) };
  37407. this._heightQuads[row * subdivisionsX + col] = quad;
  37408. }
  37409. }
  37410. };
  37411. // Compute each quad element values and update the the heightMap array :
  37412. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  37413. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  37414. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  37415. GroundMesh.prototype._computeHeightQuads = function () {
  37416. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37417. var v1 = BABYLON.Tmp.Vector3[3];
  37418. var v2 = BABYLON.Tmp.Vector3[2];
  37419. var v3 = BABYLON.Tmp.Vector3[1];
  37420. var v4 = BABYLON.Tmp.Vector3[0];
  37421. var v1v2 = BABYLON.Tmp.Vector3[4];
  37422. var v1v3 = BABYLON.Tmp.Vector3[5];
  37423. var v1v4 = BABYLON.Tmp.Vector3[6];
  37424. var norm1 = BABYLON.Tmp.Vector3[7];
  37425. var norm2 = BABYLON.Tmp.Vector3[8];
  37426. var i = 0;
  37427. var j = 0;
  37428. var k = 0;
  37429. var cd = 0; // 2D slope coefficient : z = cd * x + h
  37430. var h = 0;
  37431. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  37432. var d2 = 0;
  37433. var subdivisionsX = this._subdivisionsX;
  37434. var subdivisionsY = this._subdivisionsY;
  37435. for (var row = 0; row < subdivisionsY; row++) {
  37436. for (var col = 0; col < subdivisionsX; col++) {
  37437. i = col * 3;
  37438. j = row * (subdivisionsX + 1) * 3;
  37439. k = (row + 1) * (subdivisionsX + 1) * 3;
  37440. v1.x = positions[j + i];
  37441. v1.y = positions[j + i + 1];
  37442. v1.z = positions[j + i + 2];
  37443. v2.x = positions[j + i + 3];
  37444. v2.y = positions[j + i + 4];
  37445. v2.z = positions[j + i + 5];
  37446. v3.x = positions[k + i];
  37447. v3.y = positions[k + i + 1];
  37448. v3.z = positions[k + i + 2];
  37449. v4.x = positions[k + i + 3];
  37450. v4.y = positions[k + i + 4];
  37451. v4.z = positions[k + i + 5];
  37452. // 2D slope V1V4
  37453. cd = (v4.z - v1.z) / (v4.x - v1.x);
  37454. h = v1.z - cd * v1.x; // v1 belongs to the slope
  37455. // facet equations :
  37456. // we compute each facet normal vector
  37457. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  37458. // we compute the value d by applying the equation to v1 which belongs to the plane
  37459. // then we store the facet equation in a Vector4
  37460. v2.subtractToRef(v1, v1v2);
  37461. v3.subtractToRef(v1, v1v3);
  37462. v4.subtractToRef(v1, v1v4);
  37463. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  37464. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  37465. norm1.normalize();
  37466. norm2.normalize();
  37467. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  37468. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  37469. var quad = this._heightQuads[row * subdivisionsX + col];
  37470. quad.slope.copyFromFloats(cd, h);
  37471. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  37472. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  37473. }
  37474. }
  37475. };
  37476. return GroundMesh;
  37477. }(BABYLON.Mesh));
  37478. BABYLON.GroundMesh = GroundMesh;
  37479. })(BABYLON || (BABYLON = {}));
  37480. //# sourceMappingURL=babylon.groundMesh.js.map
  37481. var BABYLON;
  37482. (function (BABYLON) {
  37483. var LinesMesh = (function (_super) {
  37484. __extends(LinesMesh, _super);
  37485. function LinesMesh(name, scene, parent, source, doNotCloneChildren) {
  37486. if (parent === void 0) { parent = null; }
  37487. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  37488. _this.color = new BABYLON.Color3(1, 1, 1);
  37489. _this.alpha = 1;
  37490. _this._positionBuffer = {};
  37491. if (source) {
  37492. _this.color = source.color.clone();
  37493. _this.alpha = source.alpha;
  37494. }
  37495. _this._intersectionThreshold = 0.1;
  37496. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", {
  37497. attributes: [BABYLON.VertexBuffer.PositionKind],
  37498. uniforms: ["worldViewProjection", "color"],
  37499. needAlphaBlending: true
  37500. });
  37501. _this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = null;
  37502. return _this;
  37503. }
  37504. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  37505. /**
  37506. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37507. * This margin is expressed in world space coordinates, so its value may vary.
  37508. * Default value is 0.1
  37509. * @returns the intersection Threshold value.
  37510. */
  37511. get: function () {
  37512. return this._intersectionThreshold;
  37513. },
  37514. /**
  37515. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  37516. * This margin is expressed in world space coordinates, so its value may vary.
  37517. * @param value the new threshold to apply
  37518. */
  37519. set: function (value) {
  37520. if (this._intersectionThreshold === value) {
  37521. return;
  37522. }
  37523. this._intersectionThreshold = value;
  37524. if (this.geometry) {
  37525. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  37526. }
  37527. },
  37528. enumerable: true,
  37529. configurable: true
  37530. });
  37531. LinesMesh.prototype.getClassName = function () {
  37532. return "LinesMesh";
  37533. };
  37534. Object.defineProperty(LinesMesh.prototype, "material", {
  37535. get: function () {
  37536. return this._colorShader;
  37537. },
  37538. enumerable: true,
  37539. configurable: true
  37540. });
  37541. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  37542. get: function () {
  37543. return false;
  37544. },
  37545. enumerable: true,
  37546. configurable: true
  37547. });
  37548. LinesMesh.prototype.createInstance = function (name) {
  37549. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  37550. return null;
  37551. };
  37552. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  37553. var engine = this.getScene().getEngine();
  37554. this._positionBuffer[BABYLON.VertexBuffer.PositionKind] = this._geometry.getVertexBuffer(BABYLON.VertexBuffer.PositionKind);
  37555. // VBOs
  37556. engine.bindBuffers(this._positionBuffer, this._geometry.getIndexBuffer(), this._colorShader.getEffect());
  37557. // Color
  37558. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  37559. };
  37560. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  37561. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  37562. return;
  37563. }
  37564. var engine = this.getScene().getEngine();
  37565. // Draw order
  37566. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  37567. };
  37568. LinesMesh.prototype.dispose = function (doNotRecurse) {
  37569. this._colorShader.dispose();
  37570. _super.prototype.dispose.call(this, doNotRecurse);
  37571. };
  37572. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  37573. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  37574. };
  37575. return LinesMesh;
  37576. }(BABYLON.Mesh));
  37577. BABYLON.LinesMesh = LinesMesh;
  37578. })(BABYLON || (BABYLON = {}));
  37579. //# sourceMappingURL=babylon.linesMesh.js.map
  37580. var BABYLON;
  37581. (function (BABYLON) {
  37582. var DefaultLoadingScreen = (function () {
  37583. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  37584. if (_loadingText === void 0) { _loadingText = ""; }
  37585. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  37586. var _this = this;
  37587. this._renderingCanvas = _renderingCanvas;
  37588. this._loadingText = _loadingText;
  37589. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  37590. // Resize
  37591. this._resizeLoadingUI = function () {
  37592. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  37593. _this._loadingDiv.style.position = "absolute";
  37594. _this._loadingDiv.style.left = canvasRect.left + "px";
  37595. _this._loadingDiv.style.top = canvasRect.top + "px";
  37596. _this._loadingDiv.style.width = canvasRect.width + "px";
  37597. _this._loadingDiv.style.height = canvasRect.height + "px";
  37598. };
  37599. }
  37600. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  37601. var _this = this;
  37602. if (this._loadingDiv) {
  37603. // Do not add a loading screen if there is already one
  37604. return;
  37605. }
  37606. this._loadingDiv = document.createElement("div");
  37607. this._loadingDiv.id = "babylonjsLoadingDiv";
  37608. this._loadingDiv.style.opacity = "0";
  37609. this._loadingDiv.style.transition = "opacity 1.5s ease";
  37610. // Loading text
  37611. this._loadingTextDiv = document.createElement("div");
  37612. this._loadingTextDiv.style.position = "absolute";
  37613. this._loadingTextDiv.style.left = "0";
  37614. this._loadingTextDiv.style.top = "50%";
  37615. this._loadingTextDiv.style.marginTop = "80px";
  37616. this._loadingTextDiv.style.width = "100%";
  37617. this._loadingTextDiv.style.height = "20px";
  37618. this._loadingTextDiv.style.fontFamily = "Arial";
  37619. this._loadingTextDiv.style.fontSize = "14px";
  37620. this._loadingTextDiv.style.color = "white";
  37621. this._loadingTextDiv.style.textAlign = "center";
  37622. this._loadingTextDiv.innerHTML = "Loading";
  37623. this._loadingDiv.appendChild(this._loadingTextDiv);
  37624. //set the predefined text
  37625. this._loadingTextDiv.innerHTML = this._loadingText;
  37626. // Loading img
  37627. var imgBack = new Image();
  37628. 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==";
  37629. imgBack.style.position = "absolute";
  37630. imgBack.style.left = "50%";
  37631. imgBack.style.top = "50%";
  37632. imgBack.style.marginLeft = "-50px";
  37633. imgBack.style.marginTop = "-50px";
  37634. imgBack.style.transition = "transform 1.0s ease";
  37635. imgBack.style.webkitTransition = "-webkit-transform 1.0s ease";
  37636. var deg = 360;
  37637. var onTransitionEnd = function () {
  37638. deg += 360;
  37639. imgBack.style.transform = "rotateZ(" + deg + "deg)";
  37640. imgBack.style.webkitTransform = "rotateZ(" + deg + "deg)";
  37641. };
  37642. imgBack.addEventListener("transitionend", onTransitionEnd);
  37643. imgBack.addEventListener("webkitTransitionEnd", onTransitionEnd);
  37644. this._loadingDiv.appendChild(imgBack);
  37645. // front image
  37646. var imgFront = new Image();
  37647. 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=";
  37648. imgFront.style.position = "absolute";
  37649. imgFront.style.left = "50%";
  37650. imgFront.style.top = "50%";
  37651. imgFront.style.marginLeft = "-50px";
  37652. imgFront.style.marginTop = "-50px";
  37653. this._loadingDiv.appendChild(imgFront);
  37654. this._resizeLoadingUI();
  37655. window.addEventListener("resize", this._resizeLoadingUI);
  37656. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37657. document.body.appendChild(this._loadingDiv);
  37658. setTimeout(function () {
  37659. _this._loadingDiv.style.opacity = "1";
  37660. imgBack.style.transform = "rotateZ(360deg)";
  37661. imgBack.style.webkitTransform = "rotateZ(360deg)";
  37662. }, 0);
  37663. };
  37664. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  37665. var _this = this;
  37666. if (!this._loadingDiv) {
  37667. return;
  37668. }
  37669. var onTransitionEnd = function () {
  37670. if (!_this._loadingDiv) {
  37671. return;
  37672. }
  37673. document.body.removeChild(_this._loadingDiv);
  37674. window.removeEventListener("resize", _this._resizeLoadingUI);
  37675. _this._loadingDiv = null;
  37676. };
  37677. this._loadingDiv.style.opacity = "0";
  37678. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  37679. };
  37680. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  37681. set: function (text) {
  37682. this._loadingText = text;
  37683. if (this._loadingTextDiv) {
  37684. this._loadingTextDiv.innerHTML = this._loadingText;
  37685. }
  37686. },
  37687. enumerable: true,
  37688. configurable: true
  37689. });
  37690. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  37691. get: function () {
  37692. return this._loadingDivBackgroundColor;
  37693. },
  37694. set: function (color) {
  37695. this._loadingDivBackgroundColor = color;
  37696. if (!this._loadingDiv) {
  37697. return;
  37698. }
  37699. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  37700. },
  37701. enumerable: true,
  37702. configurable: true
  37703. });
  37704. return DefaultLoadingScreen;
  37705. }());
  37706. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  37707. })(BABYLON || (BABYLON = {}));
  37708. //# sourceMappingURL=babylon.loadingScreen.js.map
  37709. var BABYLON;
  37710. (function (BABYLON) {
  37711. var AudioEngine = (function () {
  37712. function AudioEngine() {
  37713. this._audioContext = null;
  37714. this._audioContextInitialized = false;
  37715. this.canUseWebAudio = false;
  37716. this.WarnedWebAudioUnsupported = false;
  37717. this.unlocked = false;
  37718. this.isMP3supported = false;
  37719. this.isOGGsupported = false;
  37720. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  37721. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  37722. this.canUseWebAudio = true;
  37723. }
  37724. var audioElem = document.createElement('audio');
  37725. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  37726. this.isMP3supported = true;
  37727. }
  37728. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  37729. this.isOGGsupported = true;
  37730. }
  37731. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  37732. this._unlockiOSaudio();
  37733. }
  37734. else {
  37735. this.unlocked = true;
  37736. }
  37737. }
  37738. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  37739. get: function () {
  37740. if (!this._audioContextInitialized) {
  37741. this._initializeAudioContext();
  37742. }
  37743. return this._audioContext;
  37744. },
  37745. enumerable: true,
  37746. configurable: true
  37747. });
  37748. AudioEngine.prototype._unlockiOSaudio = function () {
  37749. var _this = this;
  37750. var unlockaudio = function () {
  37751. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  37752. var source = _this.audioContext.createBufferSource();
  37753. source.buffer = buffer;
  37754. source.connect(_this.audioContext.destination);
  37755. source.start(0);
  37756. setTimeout(function () {
  37757. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  37758. _this.unlocked = true;
  37759. window.removeEventListener('touchend', unlockaudio, false);
  37760. if (_this.onAudioUnlocked) {
  37761. _this.onAudioUnlocked();
  37762. }
  37763. }
  37764. }, 0);
  37765. };
  37766. window.addEventListener('touchend', unlockaudio, false);
  37767. };
  37768. AudioEngine.prototype._initializeAudioContext = function () {
  37769. try {
  37770. if (this.canUseWebAudio) {
  37771. this._audioContext = new AudioContext();
  37772. // create a global volume gain node
  37773. this.masterGain = this._audioContext.createGain();
  37774. this.masterGain.gain.value = 1;
  37775. this.masterGain.connect(this._audioContext.destination);
  37776. this._audioContextInitialized = true;
  37777. }
  37778. }
  37779. catch (e) {
  37780. this.canUseWebAudio = false;
  37781. BABYLON.Tools.Error("Web Audio: " + e.message);
  37782. }
  37783. };
  37784. AudioEngine.prototype.dispose = function () {
  37785. if (this.canUseWebAudio && this._audioContextInitialized) {
  37786. if (this._connectedAnalyser) {
  37787. this._connectedAnalyser.stopDebugCanvas();
  37788. this._connectedAnalyser.dispose();
  37789. this.masterGain.disconnect();
  37790. this.masterGain.connect(this._audioContext.destination);
  37791. this._connectedAnalyser = null;
  37792. }
  37793. this.masterGain.gain.value = 1;
  37794. }
  37795. this.WarnedWebAudioUnsupported = false;
  37796. };
  37797. AudioEngine.prototype.getGlobalVolume = function () {
  37798. if (this.canUseWebAudio && this._audioContextInitialized) {
  37799. return this.masterGain.gain.value;
  37800. }
  37801. else {
  37802. return -1;
  37803. }
  37804. };
  37805. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  37806. if (this.canUseWebAudio && this._audioContextInitialized) {
  37807. this.masterGain.gain.value = newVolume;
  37808. }
  37809. };
  37810. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  37811. if (this._connectedAnalyser) {
  37812. this._connectedAnalyser.stopDebugCanvas();
  37813. }
  37814. if (this.canUseWebAudio && this._audioContextInitialized) {
  37815. this._connectedAnalyser = analyser;
  37816. this.masterGain.disconnect();
  37817. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  37818. }
  37819. };
  37820. return AudioEngine;
  37821. }());
  37822. BABYLON.AudioEngine = AudioEngine;
  37823. })(BABYLON || (BABYLON = {}));
  37824. //# sourceMappingURL=babylon.audioEngine.js.map
  37825. var BABYLON;
  37826. (function (BABYLON) {
  37827. var Sound = (function () {
  37828. /**
  37829. * Create a sound and attach it to a scene
  37830. * @param name Name of your sound
  37831. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  37832. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  37833. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  37834. */
  37835. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  37836. var _this = this;
  37837. this.autoplay = false;
  37838. this.loop = false;
  37839. this.useCustomAttenuation = false;
  37840. this.spatialSound = false;
  37841. this.refDistance = 1;
  37842. this.rolloffFactor = 1;
  37843. this.maxDistance = 100;
  37844. this.distanceModel = "linear";
  37845. this._panningModel = "equalpower";
  37846. this._playbackRate = 1;
  37847. this._streaming = false;
  37848. this._startTime = 0;
  37849. this._startOffset = 0;
  37850. this._position = BABYLON.Vector3.Zero();
  37851. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  37852. this._volume = 1;
  37853. this._isLoaded = false;
  37854. this._isReadyToPlay = false;
  37855. this.isPlaying = false;
  37856. this.isPaused = false;
  37857. this._isDirectional = false;
  37858. // Used if you'd like to create a directional sound.
  37859. // If not set, the sound will be omnidirectional
  37860. this._coneInnerAngle = 360;
  37861. this._coneOuterAngle = 360;
  37862. this._coneOuterGain = 0;
  37863. this._isOutputConnected = false;
  37864. this._urlType = "Unknown";
  37865. this.name = name;
  37866. this._scene = scene;
  37867. this._readyToPlayCallback = readyToPlayCallback;
  37868. // Default custom attenuation function is a linear attenuation
  37869. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  37870. if (currentDistance < maxDistance) {
  37871. return currentVolume * (1 - currentDistance / maxDistance);
  37872. }
  37873. else {
  37874. return 0;
  37875. }
  37876. };
  37877. if (options) {
  37878. this.autoplay = options.autoplay || false;
  37879. this.loop = options.loop || false;
  37880. // if volume === 0, we need another way to check this option
  37881. if (options.volume !== undefined) {
  37882. this._volume = options.volume;
  37883. }
  37884. this.spatialSound = options.spatialSound || false;
  37885. this.maxDistance = options.maxDistance || 100;
  37886. this.useCustomAttenuation = options.useCustomAttenuation || false;
  37887. this.rolloffFactor = options.rolloffFactor || 1;
  37888. this.refDistance = options.refDistance || 1;
  37889. this.distanceModel = options.distanceModel || "linear";
  37890. this._playbackRate = options.playbackRate || 1;
  37891. this._streaming = options.streaming || false;
  37892. }
  37893. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  37894. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  37895. this._soundGain.gain.value = this._volume;
  37896. this._inputAudioNode = this._soundGain;
  37897. this._ouputAudioNode = this._soundGain;
  37898. if (this.spatialSound) {
  37899. this._createSpatialParameters();
  37900. }
  37901. this._scene.mainSoundTrack.AddSound(this);
  37902. var validParameter = true;
  37903. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  37904. if (urlOrArrayBuffer) {
  37905. if (typeof (urlOrArrayBuffer) === "string")
  37906. this._urlType = "String";
  37907. if (Array.isArray(urlOrArrayBuffer))
  37908. this._urlType = "Array";
  37909. if (urlOrArrayBuffer instanceof ArrayBuffer)
  37910. this._urlType = "ArrayBuffer";
  37911. var urls = [];
  37912. var codecSupportedFound = false;
  37913. switch (this._urlType) {
  37914. case "ArrayBuffer":
  37915. if (urlOrArrayBuffer.byteLength > 0) {
  37916. codecSupportedFound = true;
  37917. this._soundLoaded(urlOrArrayBuffer);
  37918. }
  37919. break;
  37920. case "String":
  37921. urls.push(urlOrArrayBuffer);
  37922. case "Array":
  37923. if (urls.length === 0)
  37924. urls = urlOrArrayBuffer;
  37925. // If we found a supported format, we load it immediately and stop the loop
  37926. for (var i = 0; i < urls.length; i++) {
  37927. var url = urls[i];
  37928. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  37929. codecSupportedFound = true;
  37930. }
  37931. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  37932. codecSupportedFound = true;
  37933. }
  37934. if (url.indexOf(".wav", url.length - 4) !== -1) {
  37935. codecSupportedFound = true;
  37936. }
  37937. if (codecSupportedFound) {
  37938. // Loading sound using XHR2
  37939. if (!this._streaming) {
  37940. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  37941. }
  37942. else {
  37943. this._htmlAudioElement = new Audio(url);
  37944. this._htmlAudioElement.controls = false;
  37945. this._htmlAudioElement.loop = this.loop;
  37946. this._htmlAudioElement.crossOrigin = "anonymous";
  37947. this._htmlAudioElement.preload = "auto";
  37948. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  37949. _this._isReadyToPlay = true;
  37950. if (_this.autoplay) {
  37951. _this.play();
  37952. }
  37953. if (_this._readyToPlayCallback) {
  37954. _this._readyToPlayCallback();
  37955. }
  37956. });
  37957. document.body.appendChild(this._htmlAudioElement);
  37958. }
  37959. break;
  37960. }
  37961. }
  37962. break;
  37963. default:
  37964. validParameter = false;
  37965. break;
  37966. }
  37967. if (!validParameter) {
  37968. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  37969. }
  37970. else {
  37971. if (!codecSupportedFound) {
  37972. this._isReadyToPlay = true;
  37973. // Simulating a ready to play event to avoid breaking code path
  37974. if (this._readyToPlayCallback) {
  37975. window.setTimeout(function () {
  37976. _this._readyToPlayCallback();
  37977. }, 1000);
  37978. }
  37979. }
  37980. }
  37981. }
  37982. }
  37983. else {
  37984. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  37985. this._scene.mainSoundTrack.AddSound(this);
  37986. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  37987. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  37988. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  37989. }
  37990. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  37991. if (this._readyToPlayCallback) {
  37992. window.setTimeout(function () {
  37993. _this._readyToPlayCallback();
  37994. }, 1000);
  37995. }
  37996. }
  37997. }
  37998. Sound.prototype.dispose = function () {
  37999. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  38000. if (this.isPlaying) {
  38001. this.stop();
  38002. }
  38003. this._isReadyToPlay = false;
  38004. if (this.soundTrackId === -1) {
  38005. this._scene.mainSoundTrack.RemoveSound(this);
  38006. }
  38007. else {
  38008. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  38009. }
  38010. if (this._soundGain) {
  38011. this._soundGain.disconnect();
  38012. this._soundGain = null;
  38013. }
  38014. if (this._soundPanner) {
  38015. this._soundPanner.disconnect();
  38016. this._soundPanner = null;
  38017. }
  38018. if (this._soundSource) {
  38019. this._soundSource.disconnect();
  38020. this._soundSource = null;
  38021. }
  38022. this._audioBuffer = null;
  38023. if (this._htmlAudioElement) {
  38024. this._htmlAudioElement.pause();
  38025. this._htmlAudioElement.src = "";
  38026. document.body.removeChild(this._htmlAudioElement);
  38027. }
  38028. if (this._connectedMesh) {
  38029. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38030. this._connectedMesh = null;
  38031. }
  38032. }
  38033. };
  38034. Sound.prototype._soundLoaded = function (audioData) {
  38035. var _this = this;
  38036. this._isLoaded = true;
  38037. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  38038. _this._audioBuffer = buffer;
  38039. _this._isReadyToPlay = true;
  38040. if (_this.autoplay) {
  38041. _this.play();
  38042. }
  38043. if (_this._readyToPlayCallback) {
  38044. _this._readyToPlayCallback();
  38045. }
  38046. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  38047. };
  38048. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  38049. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38050. this._audioBuffer = audioBuffer;
  38051. this._isReadyToPlay = true;
  38052. }
  38053. };
  38054. Sound.prototype.updateOptions = function (options) {
  38055. if (options) {
  38056. this.loop = options.loop || this.loop;
  38057. this.maxDistance = options.maxDistance || this.maxDistance;
  38058. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  38059. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  38060. this.refDistance = options.refDistance || this.refDistance;
  38061. this.distanceModel = options.distanceModel || this.distanceModel;
  38062. this._playbackRate = options.playbackRate || this._playbackRate;
  38063. this._updateSpatialParameters();
  38064. if (this.isPlaying) {
  38065. if (this._streaming) {
  38066. this._htmlAudioElement.playbackRate = this._playbackRate;
  38067. }
  38068. else {
  38069. this._soundSource.playbackRate.value = this._playbackRate;
  38070. }
  38071. }
  38072. }
  38073. };
  38074. Sound.prototype._createSpatialParameters = function () {
  38075. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38076. if (this._scene.headphone) {
  38077. this._panningModel = "HRTF";
  38078. }
  38079. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  38080. this._updateSpatialParameters();
  38081. this._soundPanner.connect(this._ouputAudioNode);
  38082. this._inputAudioNode = this._soundPanner;
  38083. }
  38084. };
  38085. Sound.prototype._updateSpatialParameters = function () {
  38086. if (this.spatialSound) {
  38087. if (this.useCustomAttenuation) {
  38088. // Tricks to disable in a way embedded Web Audio attenuation
  38089. this._soundPanner.distanceModel = "linear";
  38090. this._soundPanner.maxDistance = Number.MAX_VALUE;
  38091. this._soundPanner.refDistance = 1;
  38092. this._soundPanner.rolloffFactor = 1;
  38093. this._soundPanner.panningModel = this._panningModel;
  38094. }
  38095. else {
  38096. this._soundPanner.distanceModel = this.distanceModel;
  38097. this._soundPanner.maxDistance = this.maxDistance;
  38098. this._soundPanner.refDistance = this.refDistance;
  38099. this._soundPanner.rolloffFactor = this.rolloffFactor;
  38100. this._soundPanner.panningModel = this._panningModel;
  38101. }
  38102. }
  38103. };
  38104. Sound.prototype.switchPanningModelToHRTF = function () {
  38105. this._panningModel = "HRTF";
  38106. this._switchPanningModel();
  38107. };
  38108. Sound.prototype.switchPanningModelToEqualPower = function () {
  38109. this._panningModel = "equalpower";
  38110. this._switchPanningModel();
  38111. };
  38112. Sound.prototype._switchPanningModel = function () {
  38113. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38114. this._soundPanner.panningModel = this._panningModel;
  38115. }
  38116. };
  38117. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  38118. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38119. if (this._isOutputConnected) {
  38120. this._ouputAudioNode.disconnect();
  38121. }
  38122. this._ouputAudioNode.connect(soundTrackAudioNode);
  38123. this._isOutputConnected = true;
  38124. }
  38125. };
  38126. /**
  38127. * Transform this sound into a directional source
  38128. * @param coneInnerAngle Size of the inner cone in degree
  38129. * @param coneOuterAngle Size of the outer cone in degree
  38130. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  38131. */
  38132. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  38133. if (coneOuterAngle < coneInnerAngle) {
  38134. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  38135. return;
  38136. }
  38137. this._coneInnerAngle = coneInnerAngle;
  38138. this._coneOuterAngle = coneOuterAngle;
  38139. this._coneOuterGain = coneOuterGain;
  38140. this._isDirectional = true;
  38141. if (this.isPlaying && this.loop) {
  38142. this.stop();
  38143. this.play();
  38144. }
  38145. };
  38146. Sound.prototype.setPosition = function (newPosition) {
  38147. this._position = newPosition;
  38148. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  38149. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38150. }
  38151. };
  38152. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  38153. this._localDirection = newLocalDirection;
  38154. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  38155. this._updateDirection();
  38156. }
  38157. };
  38158. Sound.prototype._updateDirection = function () {
  38159. var mat = this._connectedMesh.getWorldMatrix();
  38160. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  38161. direction.normalize();
  38162. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  38163. };
  38164. Sound.prototype.updateDistanceFromListener = function () {
  38165. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  38166. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  38167. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  38168. }
  38169. };
  38170. Sound.prototype.setAttenuationFunction = function (callback) {
  38171. this._customAttenuationFunction = callback;
  38172. };
  38173. /**
  38174. * Play the sound
  38175. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  38176. * @param offset (optional) Start the sound setting it at a specific time
  38177. */
  38178. Sound.prototype.play = function (time, offset) {
  38179. var _this = this;
  38180. if (this._isReadyToPlay && this._scene.audioEnabled) {
  38181. try {
  38182. if (this._startOffset < 0) {
  38183. time = -this._startOffset;
  38184. this._startOffset = 0;
  38185. }
  38186. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38187. if (!this._soundSource || !this._streamingSource) {
  38188. if (this.spatialSound) {
  38189. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  38190. if (this._isDirectional) {
  38191. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  38192. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  38193. this._soundPanner.coneOuterGain = this._coneOuterGain;
  38194. if (this._connectedMesh) {
  38195. this._updateDirection();
  38196. }
  38197. else {
  38198. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  38199. }
  38200. }
  38201. }
  38202. }
  38203. if (this._streaming) {
  38204. if (!this._streamingSource) {
  38205. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  38206. this._htmlAudioElement.onended = function () { _this._onended(); };
  38207. this._htmlAudioElement.playbackRate = this._playbackRate;
  38208. }
  38209. this._streamingSource.disconnect();
  38210. this._streamingSource.connect(this._inputAudioNode);
  38211. this._htmlAudioElement.play();
  38212. }
  38213. else {
  38214. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  38215. this._soundSource.buffer = this._audioBuffer;
  38216. this._soundSource.connect(this._inputAudioNode);
  38217. this._soundSource.loop = this.loop;
  38218. this._soundSource.playbackRate.value = this._playbackRate;
  38219. this._soundSource.onended = function () { _this._onended(); };
  38220. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  38221. }
  38222. this._startTime = startTime;
  38223. this.isPlaying = true;
  38224. this.isPaused = false;
  38225. }
  38226. catch (ex) {
  38227. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  38228. }
  38229. }
  38230. };
  38231. Sound.prototype._onended = function () {
  38232. this.isPlaying = false;
  38233. if (this.onended) {
  38234. this.onended();
  38235. }
  38236. };
  38237. /**
  38238. * Stop the sound
  38239. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  38240. */
  38241. Sound.prototype.stop = function (time) {
  38242. if (this.isPlaying) {
  38243. if (this._streaming) {
  38244. this._htmlAudioElement.pause();
  38245. // Test needed for Firefox or it will generate an Invalid State Error
  38246. if (this._htmlAudioElement.currentTime > 0) {
  38247. this._htmlAudioElement.currentTime = 0;
  38248. }
  38249. }
  38250. else {
  38251. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  38252. this._soundSource.stop(stopTime);
  38253. this._soundSource.onended = null;
  38254. if (!this.isPaused) {
  38255. this._startOffset = 0;
  38256. }
  38257. }
  38258. this.isPlaying = false;
  38259. }
  38260. };
  38261. Sound.prototype.pause = function () {
  38262. if (this.isPlaying) {
  38263. this.isPaused = true;
  38264. if (this._streaming) {
  38265. this._htmlAudioElement.pause();
  38266. }
  38267. else {
  38268. this.stop(0);
  38269. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  38270. }
  38271. }
  38272. };
  38273. Sound.prototype.setVolume = function (newVolume, time) {
  38274. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38275. if (time) {
  38276. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  38277. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  38278. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  38279. }
  38280. else {
  38281. this._soundGain.gain.value = newVolume;
  38282. }
  38283. }
  38284. this._volume = newVolume;
  38285. };
  38286. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  38287. this._playbackRate = newPlaybackRate;
  38288. if (this.isPlaying) {
  38289. if (this._streaming) {
  38290. this._htmlAudioElement.playbackRate = this._playbackRate;
  38291. }
  38292. else {
  38293. this._soundSource.playbackRate.value = this._playbackRate;
  38294. }
  38295. }
  38296. };
  38297. Sound.prototype.getVolume = function () {
  38298. return this._volume;
  38299. };
  38300. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  38301. var _this = this;
  38302. if (this._connectedMesh) {
  38303. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38304. this._registerFunc = null;
  38305. }
  38306. this._connectedMesh = meshToConnectTo;
  38307. if (!this.spatialSound) {
  38308. this.spatialSound = true;
  38309. this._createSpatialParameters();
  38310. if (this.isPlaying && this.loop) {
  38311. this.stop();
  38312. this.play();
  38313. }
  38314. }
  38315. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  38316. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  38317. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  38318. };
  38319. Sound.prototype.detachFromMesh = function () {
  38320. if (this._connectedMesh) {
  38321. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  38322. this._registerFunc = null;
  38323. this._connectedMesh = null;
  38324. }
  38325. };
  38326. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  38327. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  38328. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  38329. this._updateDirection();
  38330. }
  38331. };
  38332. Sound.prototype.clone = function () {
  38333. var _this = this;
  38334. if (!this._streaming) {
  38335. var setBufferAndRun = function () {
  38336. if (_this._isReadyToPlay) {
  38337. clonedSound._audioBuffer = _this.getAudioBuffer();
  38338. clonedSound._isReadyToPlay = true;
  38339. if (clonedSound.autoplay) {
  38340. clonedSound.play();
  38341. }
  38342. }
  38343. else {
  38344. window.setTimeout(setBufferAndRun, 300);
  38345. }
  38346. };
  38347. var currentOptions = {
  38348. autoplay: this.autoplay, loop: this.loop,
  38349. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  38350. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  38351. refDistance: this.refDistance, distanceModel: this.distanceModel
  38352. };
  38353. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  38354. if (this.useCustomAttenuation) {
  38355. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  38356. }
  38357. clonedSound.setPosition(this._position);
  38358. clonedSound.setPlaybackRate(this._playbackRate);
  38359. setBufferAndRun();
  38360. return clonedSound;
  38361. }
  38362. else {
  38363. return null;
  38364. }
  38365. };
  38366. Sound.prototype.getAudioBuffer = function () {
  38367. return this._audioBuffer;
  38368. };
  38369. Sound.prototype.serialize = function () {
  38370. var serializationObject = {
  38371. name: this.name,
  38372. url: this.name,
  38373. autoplay: this.autoplay,
  38374. loop: this.loop,
  38375. volume: this._volume,
  38376. spatialSound: this.spatialSound,
  38377. maxDistance: this.maxDistance,
  38378. rolloffFactor: this.rolloffFactor,
  38379. refDistance: this.refDistance,
  38380. distanceModel: this.distanceModel,
  38381. playbackRate: this._playbackRate,
  38382. panningModel: this._panningModel,
  38383. soundTrackId: this.soundTrackId
  38384. };
  38385. if (this.spatialSound) {
  38386. if (this._connectedMesh)
  38387. serializationObject.connectedMeshId = this._connectedMesh.id;
  38388. serializationObject.position = this._position.asArray();
  38389. serializationObject.refDistance = this.refDistance;
  38390. serializationObject.distanceModel = this.distanceModel;
  38391. serializationObject.isDirectional = this._isDirectional;
  38392. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  38393. serializationObject.coneInnerAngle = this._coneInnerAngle;
  38394. serializationObject.coneOuterAngle = this._coneOuterAngle;
  38395. serializationObject.coneOuterGain = this._coneOuterGain;
  38396. }
  38397. return serializationObject;
  38398. };
  38399. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  38400. var soundName = parsedSound.name;
  38401. var soundUrl;
  38402. if (parsedSound.url) {
  38403. soundUrl = rootUrl + parsedSound.url;
  38404. }
  38405. else {
  38406. soundUrl = rootUrl + soundName;
  38407. }
  38408. var options = {
  38409. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  38410. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  38411. rolloffFactor: parsedSound.rolloffFactor,
  38412. refDistance: parsedSound.refDistance,
  38413. distanceModel: parsedSound.distanceModel,
  38414. playbackRate: parsedSound.playbackRate
  38415. };
  38416. var newSound;
  38417. if (!sourceSound) {
  38418. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  38419. scene._addPendingData(newSound);
  38420. }
  38421. else {
  38422. var setBufferAndRun = function () {
  38423. if (sourceSound._isReadyToPlay) {
  38424. newSound._audioBuffer = sourceSound.getAudioBuffer();
  38425. newSound._isReadyToPlay = true;
  38426. if (newSound.autoplay) {
  38427. newSound.play();
  38428. }
  38429. }
  38430. else {
  38431. window.setTimeout(setBufferAndRun, 300);
  38432. }
  38433. };
  38434. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  38435. setBufferAndRun();
  38436. }
  38437. if (parsedSound.position) {
  38438. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  38439. newSound.setPosition(soundPosition);
  38440. }
  38441. if (parsedSound.isDirectional) {
  38442. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  38443. if (parsedSound.localDirectionToMesh) {
  38444. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  38445. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  38446. }
  38447. }
  38448. if (parsedSound.connectedMeshId) {
  38449. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  38450. if (connectedMesh) {
  38451. newSound.attachToMesh(connectedMesh);
  38452. }
  38453. }
  38454. return newSound;
  38455. };
  38456. return Sound;
  38457. }());
  38458. BABYLON.Sound = Sound;
  38459. })(BABYLON || (BABYLON = {}));
  38460. //# sourceMappingURL=babylon.sound.js.map
  38461. var BABYLON;
  38462. (function (BABYLON) {
  38463. var SoundTrack = (function () {
  38464. function SoundTrack(scene, options) {
  38465. this.id = -1;
  38466. this._isMainTrack = false;
  38467. this._isInitialized = false;
  38468. this._scene = scene;
  38469. this.soundCollection = new Array();
  38470. this._options = options;
  38471. if (!this._isMainTrack) {
  38472. this._scene.soundTracks.push(this);
  38473. this.id = this._scene.soundTracks.length - 1;
  38474. }
  38475. }
  38476. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  38477. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38478. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  38479. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  38480. if (this._options) {
  38481. if (this._options.volume) {
  38482. this._outputAudioNode.gain.value = this._options.volume;
  38483. }
  38484. if (this._options.mainTrack) {
  38485. this._isMainTrack = this._options.mainTrack;
  38486. }
  38487. }
  38488. this._isInitialized = true;
  38489. }
  38490. };
  38491. SoundTrack.prototype.dispose = function () {
  38492. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38493. if (this._connectedAnalyser) {
  38494. this._connectedAnalyser.stopDebugCanvas();
  38495. }
  38496. while (this.soundCollection.length) {
  38497. this.soundCollection[0].dispose();
  38498. }
  38499. if (this._outputAudioNode) {
  38500. this._outputAudioNode.disconnect();
  38501. }
  38502. this._outputAudioNode = null;
  38503. }
  38504. };
  38505. SoundTrack.prototype.AddSound = function (sound) {
  38506. if (!this._isInitialized) {
  38507. this._initializeSoundTrackAudioGraph();
  38508. }
  38509. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38510. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  38511. }
  38512. if (sound.soundTrackId) {
  38513. if (sound.soundTrackId === -1) {
  38514. this._scene.mainSoundTrack.RemoveSound(sound);
  38515. }
  38516. else {
  38517. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  38518. }
  38519. }
  38520. this.soundCollection.push(sound);
  38521. sound.soundTrackId = this.id;
  38522. };
  38523. SoundTrack.prototype.RemoveSound = function (sound) {
  38524. var index = this.soundCollection.indexOf(sound);
  38525. if (index !== -1) {
  38526. this.soundCollection.splice(index, 1);
  38527. }
  38528. };
  38529. SoundTrack.prototype.setVolume = function (newVolume) {
  38530. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38531. this._outputAudioNode.gain.value = newVolume;
  38532. }
  38533. };
  38534. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  38535. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38536. for (var i = 0; i < this.soundCollection.length; i++) {
  38537. this.soundCollection[i].switchPanningModelToHRTF();
  38538. }
  38539. }
  38540. };
  38541. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  38542. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38543. for (var i = 0; i < this.soundCollection.length; i++) {
  38544. this.soundCollection[i].switchPanningModelToEqualPower();
  38545. }
  38546. }
  38547. };
  38548. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  38549. if (this._connectedAnalyser) {
  38550. this._connectedAnalyser.stopDebugCanvas();
  38551. }
  38552. this._connectedAnalyser = analyser;
  38553. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  38554. this._outputAudioNode.disconnect();
  38555. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  38556. }
  38557. };
  38558. return SoundTrack;
  38559. }());
  38560. BABYLON.SoundTrack = SoundTrack;
  38561. })(BABYLON || (BABYLON = {}));
  38562. //# sourceMappingURL=babylon.soundtrack.js.map
  38563. var BABYLON;
  38564. (function (BABYLON) {
  38565. /**
  38566. * Special Glow Blur post process only blurring the alpha channel
  38567. * It enforces keeping the most luminous color in the color channel.
  38568. */
  38569. var GlowBlurPostProcess = (function (_super) {
  38570. __extends(GlowBlurPostProcess, _super);
  38571. function GlowBlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  38572. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  38573. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  38574. _this.direction = direction;
  38575. _this.blurWidth = blurWidth;
  38576. _this.onApplyObservable.add(function (effect) {
  38577. effect.setFloat2("screenSize", _this.width, _this.height);
  38578. effect.setVector2("direction", _this.direction);
  38579. effect.setFloat("blurWidth", _this.blurWidth);
  38580. });
  38581. return _this;
  38582. }
  38583. return GlowBlurPostProcess;
  38584. }(BABYLON.PostProcess));
  38585. /**
  38586. * The highlight layer Helps adding a glow effect around a mesh.
  38587. *
  38588. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  38589. * glowy meshes to your scene.
  38590. *
  38591. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  38592. */
  38593. var HighlightLayer = (function () {
  38594. /**
  38595. * Instantiates a new highlight Layer and references it to the scene..
  38596. * @param name The name of the layer
  38597. * @param scene The scene to use the layer in
  38598. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  38599. */
  38600. function HighlightLayer(name, scene, options) {
  38601. this._vertexBuffers = {};
  38602. this._mainTextureDesiredSize = { width: 0, height: 0 };
  38603. this._meshes = {};
  38604. this._maxSize = 0;
  38605. this._shouldRender = false;
  38606. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  38607. this._excludedMeshes = {};
  38608. /**
  38609. * Specifies whether or not the inner glow is ACTIVE in the layer.
  38610. */
  38611. this.innerGlow = true;
  38612. /**
  38613. * Specifies whether or not the outer glow is ACTIVE in the layer.
  38614. */
  38615. this.outerGlow = true;
  38616. /**
  38617. * Specifies wether the highlight layer is enabled or not.
  38618. */
  38619. this.isEnabled = true;
  38620. /**
  38621. * An event triggered when the highlight layer has been disposed.
  38622. * @type {BABYLON.Observable}
  38623. */
  38624. this.onDisposeObservable = new BABYLON.Observable();
  38625. /**
  38626. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  38627. * @type {BABYLON.Observable}
  38628. */
  38629. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  38630. /**
  38631. * An event triggered when the highlight layer is being blurred.
  38632. * @type {BABYLON.Observable}
  38633. */
  38634. this.onBeforeBlurObservable = new BABYLON.Observable();
  38635. /**
  38636. * An event triggered when the highlight layer has been blurred.
  38637. * @type {BABYLON.Observable}
  38638. */
  38639. this.onAfterBlurObservable = new BABYLON.Observable();
  38640. /**
  38641. * An event triggered when the glowing blurred texture is being merged in the scene.
  38642. * @type {BABYLON.Observable}
  38643. */
  38644. this.onBeforeComposeObservable = new BABYLON.Observable();
  38645. /**
  38646. * An event triggered when the glowing blurred texture has been merged in the scene.
  38647. * @type {BABYLON.Observable}
  38648. */
  38649. this.onAfterComposeObservable = new BABYLON.Observable();
  38650. /**
  38651. * An event triggered when the highlight layer changes its size.
  38652. * @type {BABYLON.Observable}
  38653. */
  38654. this.onSizeChangedObservable = new BABYLON.Observable();
  38655. this._scene = scene;
  38656. var engine = scene.getEngine();
  38657. this._engine = engine;
  38658. this._maxSize = this._engine.getCaps().maxTextureSize;
  38659. this._scene.highlightLayers.push(this);
  38660. // Warn on stencil.
  38661. if (!this._engine.isStencilEnable) {
  38662. BABYLON.Tools.Warn("Rendering the Highlight Layer requires the stencil to be active on the canvas. var engine = new BABYLON.Engine(canvas, antialias, { stencil: true }");
  38663. }
  38664. // Adapt options
  38665. this._options = options || {
  38666. mainTextureRatio: 0.25,
  38667. blurTextureSizeRatio: 0.5,
  38668. blurHorizontalSize: 1,
  38669. blurVerticalSize: 1,
  38670. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  38671. };
  38672. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.25;
  38673. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 0.5;
  38674. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  38675. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  38676. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  38677. // VBO
  38678. var vertices = [];
  38679. vertices.push(1, 1);
  38680. vertices.push(-1, 1);
  38681. vertices.push(-1, -1);
  38682. vertices.push(1, -1);
  38683. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  38684. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  38685. // Indices
  38686. var indices = [];
  38687. indices.push(0);
  38688. indices.push(1);
  38689. indices.push(2);
  38690. indices.push(0);
  38691. indices.push(2);
  38692. indices.push(3);
  38693. this._indexBuffer = engine.createIndexBuffer(indices);
  38694. // Effect
  38695. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  38696. // Render target
  38697. this.setMainTextureSize();
  38698. // Create Textures and post processes
  38699. this.createTextureAndPostProcesses();
  38700. }
  38701. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  38702. /**
  38703. * Gets the horizontal size of the blur.
  38704. */
  38705. get: function () {
  38706. return this._horizontalBlurPostprocess.blurWidth;
  38707. },
  38708. /**
  38709. * Specifies the horizontal size of the blur.
  38710. */
  38711. set: function (value) {
  38712. this._horizontalBlurPostprocess.blurWidth = value;
  38713. },
  38714. enumerable: true,
  38715. configurable: true
  38716. });
  38717. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  38718. /**
  38719. * Gets the vertical size of the blur.
  38720. */
  38721. get: function () {
  38722. return this._verticalBlurPostprocess.blurWidth;
  38723. },
  38724. /**
  38725. * Specifies the vertical size of the blur.
  38726. */
  38727. set: function (value) {
  38728. this._verticalBlurPostprocess.blurWidth = value;
  38729. },
  38730. enumerable: true,
  38731. configurable: true
  38732. });
  38733. Object.defineProperty(HighlightLayer.prototype, "camera", {
  38734. /**
  38735. * Gets the camera attached to the layer.
  38736. */
  38737. get: function () {
  38738. return this._options.camera;
  38739. },
  38740. enumerable: true,
  38741. configurable: true
  38742. });
  38743. /**
  38744. * Creates the render target textures and post processes used in the highlight layer.
  38745. */
  38746. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  38747. var _this = this;
  38748. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  38749. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  38750. blurTextureWidth = BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize);
  38751. blurTextureHeight = BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize);
  38752. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  38753. width: this._mainTextureDesiredSize.width,
  38754. height: this._mainTextureDesiredSize.height
  38755. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38756. this._mainTexture.activeCamera = this._options.camera;
  38757. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38758. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38759. this._mainTexture.anisotropicFilteringLevel = 1;
  38760. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  38761. this._mainTexture.renderParticles = false;
  38762. this._mainTexture.renderList = null;
  38763. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  38764. width: blurTextureWidth,
  38765. height: blurTextureHeight
  38766. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  38767. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38768. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38769. this._blurTexture.anisotropicFilteringLevel = 16;
  38770. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  38771. this._blurTexture.renderParticles = false;
  38772. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38773. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  38774. effect.setTexture("textureSampler", _this._mainTexture);
  38775. });
  38776. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  38777. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38778. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38779. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38780. });
  38781. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38782. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38783. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38784. });
  38785. }
  38786. else {
  38787. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38788. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  38789. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38790. });
  38791. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  38792. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  38793. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  38794. });
  38795. }
  38796. this._mainTexture.onAfterUnbindObservable.add(function () {
  38797. _this.onBeforeBlurObservable.notifyObservers(_this);
  38798. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture());
  38799. _this.onAfterBlurObservable.notifyObservers(_this);
  38800. });
  38801. // Custom render function
  38802. var renderSubMesh = function (subMesh) {
  38803. var mesh = subMesh.getRenderingMesh();
  38804. var scene = _this._scene;
  38805. var engine = scene.getEngine();
  38806. // Culling
  38807. engine.setState(subMesh.getMaterial().backFaceCulling);
  38808. // Managing instances
  38809. var batch = mesh._getInstancesRenderList(subMesh._id);
  38810. if (batch.mustReturn) {
  38811. return;
  38812. }
  38813. // Excluded Mesh
  38814. if (_this._excludedMeshes[mesh.uniqueId]) {
  38815. return;
  38816. }
  38817. ;
  38818. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  38819. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  38820. var material = subMesh.getMaterial();
  38821. var emissiveTexture = null;
  38822. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  38823. emissiveTexture = material.emissiveTexture;
  38824. }
  38825. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  38826. engine.enableEffect(_this._glowMapGenerationEffect);
  38827. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  38828. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  38829. if (highlightLayerMesh) {
  38830. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  38831. }
  38832. else {
  38833. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  38834. }
  38835. // Alpha test
  38836. if (material && material.needAlphaTesting()) {
  38837. var alphaTexture = material.getAlphaTestTexture();
  38838. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  38839. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  38840. }
  38841. // Glow emissive only
  38842. if (emissiveTexture) {
  38843. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  38844. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  38845. }
  38846. // Bones
  38847. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38848. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  38849. }
  38850. // Draw
  38851. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  38852. }
  38853. else {
  38854. // Need to reset refresh rate of the shadowMap
  38855. _this._mainTexture.resetRefreshCounter();
  38856. }
  38857. };
  38858. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  38859. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  38860. var index;
  38861. for (index = 0; index < opaqueSubMeshes.length; index++) {
  38862. renderSubMesh(opaqueSubMeshes.data[index]);
  38863. }
  38864. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  38865. renderSubMesh(alphaTestSubMeshes.data[index]);
  38866. }
  38867. for (index = 0; index < transparentSubMeshes.length; index++) {
  38868. renderSubMesh(transparentSubMeshes.data[index]);
  38869. }
  38870. };
  38871. this._mainTexture.onClearObservable.add(function (engine) {
  38872. engine.clear(HighlightLayer.neutralColor, true, true, true);
  38873. });
  38874. };
  38875. /**
  38876. * Checks for the readiness of the element composing the layer.
  38877. * @param subMesh the mesh to check for
  38878. * @param useInstances specify wether or not to use instances to render the mesh
  38879. * @param emissiveTexture the associated emissive texture used to generate the glow
  38880. * @return true if ready otherwise, false
  38881. */
  38882. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  38883. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  38884. return false;
  38885. }
  38886. var defines = [];
  38887. var attribs = [BABYLON.VertexBuffer.PositionKind];
  38888. var mesh = subMesh.getMesh();
  38889. var material = subMesh.getMaterial();
  38890. var uv1 = false;
  38891. var uv2 = false;
  38892. // Alpha test
  38893. if (material && material.needAlphaTesting()) {
  38894. var alphaTexture = material.getAlphaTestTexture();
  38895. if (alphaTexture) {
  38896. defines.push("#define ALPHATEST");
  38897. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38898. alphaTexture.coordinatesIndex === 1) {
  38899. defines.push("#define DIFFUSEUV2");
  38900. uv2 = true;
  38901. }
  38902. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38903. defines.push("#define DIFFUSEUV1");
  38904. uv1 = true;
  38905. }
  38906. }
  38907. }
  38908. // Emissive
  38909. if (emissiveTexture) {
  38910. defines.push("#define EMISSIVE");
  38911. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  38912. emissiveTexture.coordinatesIndex === 1) {
  38913. defines.push("#define EMISSIVEUV2");
  38914. uv2 = true;
  38915. }
  38916. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  38917. defines.push("#define EMISSIVEUV1");
  38918. uv1 = true;
  38919. }
  38920. }
  38921. if (uv1) {
  38922. attribs.push(BABYLON.VertexBuffer.UVKind);
  38923. defines.push("#define UV1");
  38924. }
  38925. if (uv2) {
  38926. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  38927. defines.push("#define UV2");
  38928. }
  38929. // Bones
  38930. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  38931. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  38932. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  38933. if (mesh.numBoneInfluencers > 4) {
  38934. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  38935. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  38936. }
  38937. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  38938. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  38939. }
  38940. else {
  38941. defines.push("#define NUM_BONE_INFLUENCERS 0");
  38942. }
  38943. // Instances
  38944. if (useInstances) {
  38945. defines.push("#define INSTANCES");
  38946. attribs.push("world0");
  38947. attribs.push("world1");
  38948. attribs.push("world2");
  38949. attribs.push("world3");
  38950. }
  38951. // Get correct effect
  38952. var join = defines.join("\n");
  38953. if (this._cachedDefines !== join) {
  38954. this._cachedDefines = join;
  38955. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  38956. }
  38957. return this._glowMapGenerationEffect.isReady();
  38958. };
  38959. /**
  38960. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  38961. */
  38962. HighlightLayer.prototype.render = function () {
  38963. var currentEffect = this._glowMapMergeEffect;
  38964. // Check
  38965. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  38966. return;
  38967. var engine = this._scene.getEngine();
  38968. this.onBeforeComposeObservable.notifyObservers(this);
  38969. // Render
  38970. engine.enableEffect(currentEffect);
  38971. engine.setState(false);
  38972. // Cache
  38973. var previousStencilBuffer = engine.getStencilBuffer();
  38974. var previousStencilFunction = engine.getStencilFunction();
  38975. var previousStencilMask = engine.getStencilMask();
  38976. var previousAlphaMode = engine.getAlphaMode();
  38977. // Texture
  38978. currentEffect.setTexture("textureSampler", this._blurTexture);
  38979. // VBOs
  38980. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  38981. // Draw order
  38982. engine.setAlphaMode(this._options.alphaBlendingMode);
  38983. engine.setStencilMask(0x00);
  38984. engine.setStencilBuffer(true);
  38985. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  38986. if (this.outerGlow) {
  38987. currentEffect.setFloat("offset", 0);
  38988. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  38989. engine.draw(true, 0, 6);
  38990. }
  38991. if (this.innerGlow) {
  38992. currentEffect.setFloat("offset", 1);
  38993. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  38994. engine.draw(true, 0, 6);
  38995. }
  38996. // Restore Cache
  38997. engine.setStencilFunction(previousStencilFunction);
  38998. engine.setStencilMask(previousStencilMask);
  38999. engine.setAlphaMode(previousAlphaMode);
  39000. engine.setStencilBuffer(previousStencilBuffer);
  39001. this.onAfterComposeObservable.notifyObservers(this);
  39002. // Handle size changes.
  39003. var size = this._mainTexture.getSize();
  39004. this.setMainTextureSize();
  39005. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  39006. // Recreate RTT and post processes on size change.
  39007. this.onSizeChangedObservable.notifyObservers(this);
  39008. this.disposeTextureAndPostProcesses();
  39009. this.createTextureAndPostProcesses();
  39010. }
  39011. };
  39012. /**
  39013. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  39014. * @param mesh The mesh to exclude from the highlight layer
  39015. */
  39016. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  39017. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39018. if (!meshExcluded) {
  39019. this._excludedMeshes[mesh.uniqueId] = {
  39020. mesh: mesh,
  39021. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  39022. mesh.getEngine().setStencilBuffer(false);
  39023. }),
  39024. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  39025. mesh.getEngine().setStencilBuffer(true);
  39026. }),
  39027. };
  39028. }
  39029. };
  39030. /**
  39031. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  39032. * @param mesh The mesh to highlight
  39033. */
  39034. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  39035. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  39036. if (meshExcluded) {
  39037. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  39038. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  39039. }
  39040. this._excludedMeshes[mesh.uniqueId] = undefined;
  39041. };
  39042. /**
  39043. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  39044. * @param mesh The mesh to highlight
  39045. * @param color The color of the highlight
  39046. * @param glowEmissiveOnly Extract the glow from the emissive texture
  39047. */
  39048. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  39049. var _this = this;
  39050. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  39051. var meshHighlight = this._meshes[mesh.uniqueId];
  39052. if (meshHighlight) {
  39053. meshHighlight.color = color;
  39054. }
  39055. else {
  39056. this._meshes[mesh.uniqueId] = {
  39057. mesh: mesh,
  39058. color: color,
  39059. // Lambda required for capture due to Observable this context
  39060. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  39061. if (_this._excludedMeshes[mesh.uniqueId]) {
  39062. _this.defaultStencilReference(mesh);
  39063. }
  39064. else {
  39065. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  39066. }
  39067. }),
  39068. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  39069. glowEmissiveOnly: glowEmissiveOnly
  39070. };
  39071. }
  39072. this._shouldRender = true;
  39073. };
  39074. /**
  39075. * Remove a mesh from the highlight layer in order to make it stop glowing.
  39076. * @param mesh The mesh to highlight
  39077. */
  39078. HighlightLayer.prototype.removeMesh = function (mesh) {
  39079. var meshHighlight = this._meshes[mesh.uniqueId];
  39080. if (meshHighlight) {
  39081. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39082. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39083. }
  39084. this._meshes[mesh.uniqueId] = undefined;
  39085. this._shouldRender = false;
  39086. for (var meshHighlightToCheck in this._meshes) {
  39087. if (meshHighlightToCheck) {
  39088. this._shouldRender = true;
  39089. break;
  39090. }
  39091. }
  39092. };
  39093. /**
  39094. * Returns true if the layer contains information to display, otherwise false.
  39095. */
  39096. HighlightLayer.prototype.shouldRender = function () {
  39097. return this.isEnabled && this._shouldRender;
  39098. };
  39099. /**
  39100. * Sets the main texture desired size which is the closest power of two
  39101. * of the engine canvas size.
  39102. */
  39103. HighlightLayer.prototype.setMainTextureSize = function () {
  39104. if (this._options.mainTextureFixedSize) {
  39105. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  39106. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  39107. }
  39108. else {
  39109. this._mainTextureDesiredSize.width = this._engine.getRenderingCanvas().width * this._options.mainTextureRatio;
  39110. this._mainTextureDesiredSize.height = this._engine.getRenderingCanvas().height * this._options.mainTextureRatio;
  39111. this._mainTextureDesiredSize.width = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize);
  39112. this._mainTextureDesiredSize.height = BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize);
  39113. }
  39114. };
  39115. /**
  39116. * Force the stencil to the normal expected value for none glowing parts
  39117. */
  39118. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  39119. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  39120. };
  39121. /**
  39122. * Dispose only the render target textures and post process.
  39123. */
  39124. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  39125. this._blurTexture.dispose();
  39126. this._mainTexture.dispose();
  39127. this._downSamplePostprocess.dispose();
  39128. this._horizontalBlurPostprocess.dispose();
  39129. this._verticalBlurPostprocess.dispose();
  39130. };
  39131. /**
  39132. * Dispose the highlight layer and free resources.
  39133. */
  39134. HighlightLayer.prototype.dispose = function () {
  39135. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  39136. if (vertexBuffer) {
  39137. vertexBuffer.dispose();
  39138. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  39139. }
  39140. if (this._indexBuffer) {
  39141. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39142. this._indexBuffer = null;
  39143. }
  39144. // Clean textures and post processes
  39145. this.disposeTextureAndPostProcesses();
  39146. // Clean mesh references
  39147. for (var id in this._meshes) {
  39148. var meshHighlight = this._meshes[id];
  39149. if (meshHighlight && meshHighlight.mesh) {
  39150. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  39151. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  39152. }
  39153. }
  39154. this._meshes = null;
  39155. for (var id in this._excludedMeshes) {
  39156. var meshHighlight = this._excludedMeshes[id];
  39157. if (meshHighlight) {
  39158. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  39159. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  39160. }
  39161. }
  39162. this._excludedMeshes = null;
  39163. // Remove from scene
  39164. var index = this._scene.highlightLayers.indexOf(this, 0);
  39165. if (index > -1) {
  39166. this._scene.highlightLayers.splice(index, 1);
  39167. }
  39168. // Callback
  39169. this.onDisposeObservable.notifyObservers(this);
  39170. this.onDisposeObservable.clear();
  39171. this.onBeforeRenderMainTextureObservable.clear();
  39172. this.onBeforeBlurObservable.clear();
  39173. this.onBeforeComposeObservable.clear();
  39174. this.onAfterComposeObservable.clear();
  39175. this.onSizeChangedObservable.clear();
  39176. };
  39177. return HighlightLayer;
  39178. }());
  39179. /**
  39180. * The neutral color used during the preparation of the glow effect.
  39181. * This is black by default as the blend operation is a blend operation.
  39182. */
  39183. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  39184. /**
  39185. * Stencil value used for glowing meshes.
  39186. */
  39187. HighlightLayer.glowingMeshStencilReference = 0x02;
  39188. /**
  39189. * Stencil value used for the other meshes in the scene.
  39190. */
  39191. HighlightLayer.normalMeshStencilReference = 0x01;
  39192. BABYLON.HighlightLayer = HighlightLayer;
  39193. })(BABYLON || (BABYLON = {}));
  39194. //# sourceMappingURL=babylon.highlightlayer.js.map
  39195. var BABYLON;
  39196. (function (BABYLON) {
  39197. var SIMDVector3 = (function () {
  39198. function SIMDVector3() {
  39199. }
  39200. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  39201. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  39202. };
  39203. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  39204. var m = transformation.m;
  39205. var m0 = SIMD.Float32x4.load(m, 0);
  39206. var m1 = SIMD.Float32x4.load(m, 4);
  39207. var m2 = SIMD.Float32x4.load(m, 8);
  39208. var m3 = SIMD.Float32x4.load(m, 12);
  39209. var r = SIMD.Float32x4.add(SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(x), m0), SIMD.Float32x4.mul(SIMD.Float32x4.splat(y), m1)), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(z), m2), m3));
  39210. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  39211. result.x = SIMD.Float32x4.extractLane(r, 0);
  39212. result.y = SIMD.Float32x4.extractLane(r, 1);
  39213. result.z = SIMD.Float32x4.extractLane(r, 2);
  39214. };
  39215. return SIMDVector3;
  39216. }());
  39217. var SIMDMatrix = (function () {
  39218. function SIMDMatrix() {
  39219. }
  39220. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  39221. var tm = this.m;
  39222. var om = other.m;
  39223. var m0 = SIMD.Float32x4.load(om, 0);
  39224. var m1 = SIMD.Float32x4.load(om, 4);
  39225. var m2 = SIMD.Float32x4.load(om, 8);
  39226. var m3 = SIMD.Float32x4.load(om, 12);
  39227. for (var i = 0; i < 16; i += 4) {
  39228. SIMD.Float32x4.store(result, i + offset, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i]), m0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 1]), m1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 2]), m2), SIMD.Float32x4.mul(SIMD.Float32x4.splat(tm[i + 3]), m3)))));
  39229. }
  39230. return this;
  39231. };
  39232. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  39233. var src = this.m;
  39234. var dest = other.m;
  39235. // Load the 4 rows
  39236. var src0 = SIMD.Float32x4.load(src, 0);
  39237. var src1 = SIMD.Float32x4.load(src, 4);
  39238. var src2 = SIMD.Float32x4.load(src, 8);
  39239. var src3 = SIMD.Float32x4.load(src, 12);
  39240. // Transpose the source matrix. Sort of. Not a true transpose operation
  39241. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  39242. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  39243. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  39244. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  39245. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  39246. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  39247. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  39248. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  39249. // This is a true transposition, but it will lead to an incorrect result
  39250. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  39251. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  39252. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39253. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39254. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  39255. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  39256. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  39257. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  39258. // ----
  39259. tmp1 = SIMD.Float32x4.mul(row2, row3);
  39260. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39261. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  39262. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  39263. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39264. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  39265. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  39266. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  39267. // ----
  39268. tmp1 = SIMD.Float32x4.mul(row1, row2);
  39269. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39270. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  39271. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  39272. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39273. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  39274. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  39275. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  39276. // ----
  39277. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  39278. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39279. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  39280. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  39281. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  39282. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39283. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  39284. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  39285. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  39286. // ----
  39287. tmp1 = SIMD.Float32x4.mul(row0, row1);
  39288. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39289. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39290. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  39291. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39292. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  39293. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  39294. // ----
  39295. tmp1 = SIMD.Float32x4.mul(row0, row3);
  39296. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39297. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  39298. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  39299. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39300. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  39301. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  39302. // ----
  39303. tmp1 = SIMD.Float32x4.mul(row0, row2);
  39304. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  39305. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  39306. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  39307. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  39308. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  39309. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  39310. // Compute determinant
  39311. var det = SIMD.Float32x4.mul(row0, minor0);
  39312. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  39313. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  39314. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  39315. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  39316. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  39317. // These shuffles aren't necessary if the faulty transposition is done
  39318. // up at the top of this function.
  39319. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  39320. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  39321. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  39322. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  39323. // Compute final values by multiplying with 1/det
  39324. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  39325. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  39326. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  39327. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  39328. return this;
  39329. };
  39330. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  39331. var out = result.m;
  39332. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  39333. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  39334. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  39335. // cc.kmVec3Subtract(f, pCenter, pEye);
  39336. var f = SIMD.Float32x4.sub(center, eye);
  39337. // cc.kmVec3Normalize(f, f);
  39338. var tmp = SIMD.Float32x4.mul(f, f);
  39339. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39340. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39341. // cc.kmVec3Assign(up, pUp);
  39342. // cc.kmVec3Normalize(up, up);
  39343. tmp = SIMD.Float32x4.mul(up, up);
  39344. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39345. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39346. // cc.kmVec3Cross(s, f, up);
  39347. 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)));
  39348. // cc.kmVec3Normalize(s, s);
  39349. tmp = SIMD.Float32x4.mul(s, s);
  39350. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39351. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39352. // cc.kmVec3Cross(u, s, f);
  39353. 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)));
  39354. // cc.kmVec3Normalize(s, s);
  39355. tmp = SIMD.Float32x4.mul(s, s);
  39356. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  39357. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  39358. var zero = SIMD.Float32x4.splat(0.0);
  39359. s = SIMD.Float32x4.neg(s);
  39360. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  39361. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  39362. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  39363. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  39364. var a2 = SIMD.Float32x4.shuffle(SIMD.Float32x4.shuffle(s, u, 2, 3, 6, 7), SIMD.Float32x4.shuffle(f, zero, 2, 3, 6, 7), 0, 2, 4, 6);
  39365. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  39366. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  39367. SIMD.Float32x4.store(out, 0, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  39368. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  39369. SIMD.Float32x4.store(out, 4, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  39370. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  39371. SIMD.Float32x4.store(out, 8, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  39372. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  39373. SIMD.Float32x4.store(out, 12, SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 0, 0, 0, 0), a0), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 1, 1, 1, 1), a1), SIMD.Float32x4.add(SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 2, 2, 2, 2), a2), SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(b, 3, 3, 3, 3), a3)))));
  39374. };
  39375. return SIMDMatrix;
  39376. }());
  39377. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  39378. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  39379. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  39380. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  39381. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  39382. var SIMDHelper = (function () {
  39383. function SIMDHelper() {
  39384. }
  39385. Object.defineProperty(SIMDHelper, "IsEnabled", {
  39386. get: function () {
  39387. return SIMDHelper._isEnabled;
  39388. },
  39389. enumerable: true,
  39390. configurable: true
  39391. });
  39392. SIMDHelper.DisableSIMD = function () {
  39393. // Replace functions
  39394. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  39395. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  39396. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  39397. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  39398. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  39399. SIMDHelper._isEnabled = false;
  39400. };
  39401. SIMDHelper.EnableSIMD = function () {
  39402. if (self.SIMD === undefined) {
  39403. return;
  39404. }
  39405. // check if polyfills needed
  39406. if (!self.Math.fround) {
  39407. self.Math.fround = (function (array) { return function (x) {
  39408. return array[0] = x, array[0];
  39409. }; })(new Float32Array(1));
  39410. }
  39411. if (!self.Math.imul) {
  39412. self.Math.imul = function (a, b) {
  39413. var ah = (a >>> 16) & 0xffff;
  39414. var al = a & 0xffff;
  39415. var bh = (b >>> 16) & 0xffff;
  39416. var bl = b & 0xffff;
  39417. // the shift by 0 fixes the sign on the high part
  39418. // the final |0 converts the unsigned value into a signed value
  39419. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  39420. };
  39421. }
  39422. // Replace functions
  39423. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  39424. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  39425. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  39426. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  39427. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  39428. SIMDHelper._isEnabled = true;
  39429. };
  39430. return SIMDHelper;
  39431. }());
  39432. SIMDHelper._isEnabled = false;
  39433. BABYLON.SIMDHelper = SIMDHelper;
  39434. })(BABYLON || (BABYLON = {}));
  39435. //# sourceMappingURL=babylon.math.SIMD.js.map
  39436. var BABYLON;
  39437. (function (BABYLON) {
  39438. /**
  39439. * This class describe a rectangle that were added to the map.
  39440. * You have access to its coordinates either in pixel or normalized (UV)
  39441. */
  39442. var PackedRect = (function () {
  39443. function PackedRect(root, parent, pos, size) {
  39444. this._pos = pos;
  39445. this._size = size;
  39446. this._root = root;
  39447. this._parent = parent;
  39448. this._contentSize = null;
  39449. this._bottomNode = null;
  39450. this._leftNode = null;
  39451. this._initialSize = null;
  39452. this._rightNode = null;
  39453. }
  39454. Object.defineProperty(PackedRect.prototype, "pos", {
  39455. /**
  39456. * @returns the position of this node into the map
  39457. */
  39458. get: function () {
  39459. return this._pos;
  39460. },
  39461. enumerable: true,
  39462. configurable: true
  39463. });
  39464. Object.defineProperty(PackedRect.prototype, "contentSize", {
  39465. /**
  39466. * @returns the size of the rectangle this node handles
  39467. */
  39468. get: function () {
  39469. return this._contentSize;
  39470. },
  39471. enumerable: true,
  39472. configurable: true
  39473. });
  39474. Object.defineProperty(PackedRect.prototype, "UVs", {
  39475. /**
  39476. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  39477. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  39478. */
  39479. get: function () {
  39480. return this.getUVsForCustomSize(this._root._size);
  39481. },
  39482. enumerable: true,
  39483. configurable: true
  39484. });
  39485. /**
  39486. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations) and then using only a part of the PackRect.
  39487. * This method will return the UVs for this part by given the custom size of what you really use
  39488. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  39489. */
  39490. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  39491. var mainWidth = this._root._size.width;
  39492. var mainHeight = this._root._size.height;
  39493. var topLeft = new BABYLON.Vector2(this._pos.x / mainWidth, this._pos.y / mainHeight);
  39494. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width - 1) / mainWidth, (this._pos.y + customSize.height - 1) / mainHeight);
  39495. var uvs = new Array();
  39496. uvs.push(topLeft);
  39497. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  39498. uvs.push(rightBottom);
  39499. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  39500. return uvs;
  39501. };
  39502. /**
  39503. * Free this rectangle from the map.
  39504. * Call this method when you no longer need the rectangle to be in the map.
  39505. */
  39506. PackedRect.prototype.freeContent = function () {
  39507. if (!this.contentSize) {
  39508. return;
  39509. }
  39510. this._contentSize = null;
  39511. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  39512. this.attemptDefrag();
  39513. };
  39514. Object.defineProperty(PackedRect.prototype, "isUsed", {
  39515. get: function () {
  39516. return this._contentSize != null || this._leftNode != null;
  39517. },
  39518. enumerable: true,
  39519. configurable: true
  39520. });
  39521. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  39522. var node = this.findNode(contentSize);
  39523. // Not enough space...
  39524. if (!node) {
  39525. return null;
  39526. }
  39527. node.splitNode(contentSize);
  39528. return node;
  39529. };
  39530. PackedRect.prototype.findNode = function (size) {
  39531. var resNode = null;
  39532. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  39533. if (this.isUsed) {
  39534. if (this._leftNode) {
  39535. resNode = this._leftNode.findNode(size);
  39536. }
  39537. if (!resNode && this._rightNode) {
  39538. resNode = this._rightNode.findNode(size);
  39539. }
  39540. if (!resNode && this._bottomNode) {
  39541. resNode = this._bottomNode.findNode(size);
  39542. }
  39543. }
  39544. else if (this._initialSize) {
  39545. if ((size.width <= this._initialSize.width) && (size.height <= this._initialSize.height)) {
  39546. resNode = this;
  39547. }
  39548. else {
  39549. return null;
  39550. }
  39551. }
  39552. else if ((size.width <= this._size.width) && (size.height <= this._size.height)) {
  39553. resNode = this;
  39554. }
  39555. return resNode;
  39556. };
  39557. PackedRect.prototype.splitNode = function (contentSize) {
  39558. // If there's no contentSize but an initialSize it means this node were previously allocated, but freed, we need to create a _leftNode as subNode and use to allocate the space we need (and this node will have a right/bottom subNode for the space left as this._initialSize may be greater than contentSize)
  39559. if (!this._contentSize && this._initialSize) {
  39560. this._contentSize = contentSize.clone();
  39561. this._leftNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y), new BABYLON.Size(this._initialSize.width, this._initialSize.height));
  39562. return this._leftNode.splitNode(contentSize);
  39563. }
  39564. else {
  39565. this._contentSize = contentSize.clone();
  39566. this._initialSize = contentSize.clone();
  39567. if (contentSize.width !== this._size.width) {
  39568. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + contentSize.width, this._pos.y), new BABYLON.Size(this._size.width - contentSize.width, contentSize.height));
  39569. }
  39570. if (contentSize.height !== this._size.height) {
  39571. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + contentSize.height), new BABYLON.Size(this._size.width, this._size.height - contentSize.height));
  39572. }
  39573. return this;
  39574. }
  39575. };
  39576. PackedRect.prototype.attemptDefrag = function () {
  39577. if (!this.isUsed && this.isRecursiveFree) {
  39578. this.clearNode();
  39579. if (this._parent) {
  39580. this._parent.attemptDefrag();
  39581. }
  39582. }
  39583. };
  39584. PackedRect.prototype.clearNode = function () {
  39585. this._initialSize = null;
  39586. this._rightNode = null;
  39587. this._bottomNode = null;
  39588. };
  39589. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  39590. get: function () {
  39591. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  39592. },
  39593. enumerable: true,
  39594. configurable: true
  39595. });
  39596. PackedRect.prototype.evalFreeSize = function (size) {
  39597. var levelSize = 0;
  39598. if (!this.isUsed) {
  39599. if (this._initialSize) {
  39600. levelSize = this._initialSize.surface;
  39601. }
  39602. else {
  39603. levelSize = this._size.surface;
  39604. }
  39605. }
  39606. if (this._rightNode) {
  39607. levelSize += this._rightNode.evalFreeSize(0);
  39608. }
  39609. if (this._bottomNode) {
  39610. levelSize += this._bottomNode.evalFreeSize(0);
  39611. }
  39612. return levelSize + size;
  39613. };
  39614. return PackedRect;
  39615. }());
  39616. BABYLON.PackedRect = PackedRect;
  39617. /**
  39618. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  39619. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  39620. * Note that this class allows allocated Rectangles to be freed: that is the map is dynamically maintained so you can add/remove rectangle based on their life-cycle.
  39621. */
  39622. var RectPackingMap = (function (_super) {
  39623. __extends(RectPackingMap, _super);
  39624. /**
  39625. * Create an instance of the object with a dimension using the given size
  39626. * @param size The dimension of the rectangle that will contain all the sub ones.
  39627. */
  39628. function RectPackingMap(size) {
  39629. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  39630. _this._root = _this;
  39631. return _this;
  39632. }
  39633. /**
  39634. * Add a rectangle, finding the best location to store it into the map
  39635. * @param size the dimension of the rectangle to store
  39636. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  39637. */
  39638. RectPackingMap.prototype.addRect = function (size) {
  39639. var node = this.findAndSplitNode(size);
  39640. return node;
  39641. };
  39642. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  39643. /**
  39644. * Return the current space free normalized between [0;1]
  39645. * @returns {}
  39646. */
  39647. get: function () {
  39648. var freeSize = 0;
  39649. freeSize = this.evalFreeSize(freeSize);
  39650. return freeSize / (this._size.width * this._size.height);
  39651. },
  39652. enumerable: true,
  39653. configurable: true
  39654. });
  39655. return RectPackingMap;
  39656. }(PackedRect));
  39657. BABYLON.RectPackingMap = RectPackingMap;
  39658. })(BABYLON || (BABYLON = {}));
  39659. //# sourceMappingURL=babylon.rectPackingMap.js.map
  39660. var BABYLON;
  39661. (function (BABYLON) {
  39662. var DynamicFloatArrayElementInfo = (function () {
  39663. function DynamicFloatArrayElementInfo() {
  39664. }
  39665. return DynamicFloatArrayElementInfo;
  39666. }());
  39667. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  39668. /**
  39669. * The purpose of this class is to store float32 based elements of a given size (defined by the stride argument) in a dynamic fashion, that is, you can add/free elements. You can then access to a defragmented/packed version of the underlying Float32Array by calling the pack() method.
  39670. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  39671. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  39672. * Allocating an Element will return a instance of DynamicFloatArrayElement which contains the offset into the Float32Array of where the element starts, you are then responsible to copy your data using this offset.
  39673. * Beware, calling pack() may change the offset of some Entries because this method will defragment the Float32Array to replace empty elements by moving allocated ones at their location.
  39674. * This method will return an ArrayBufferView on the existing Float32Array that describes the used elements. Use this View to update the WebGLBuffer and NOT the "buffer" field of the class. The pack() method won't shrink/reallocate the buffer to keep it GC friendly, all the empty space will be put at the end of the buffer, the method just ensure there are no "free holes".
  39675. */
  39676. var DynamicFloatArray = (function () {
  39677. /**
  39678. * Construct an instance of the dynamic float array
  39679. * @param stride size of one element in float (i.e. not bytes!)
  39680. * @param initialElementCount the number of available entries at construction
  39681. */
  39682. function DynamicFloatArray(stride, initialElementCount) {
  39683. this.compareValueOffset = null;
  39684. this.sortingAscending = true;
  39685. this._stride = stride;
  39686. this.buffer = new Float32Array(stride * initialElementCount);
  39687. this._lastUsed = 0;
  39688. this._firstFree = 0;
  39689. this._allEntries = new Array(initialElementCount);
  39690. this._freeEntries = new Array(initialElementCount);
  39691. for (var i = 0; i < initialElementCount; i++) {
  39692. var element = new DynamicFloatArrayElementInfo();
  39693. element.offset = i * stride;
  39694. this._allEntries[i] = element;
  39695. this._freeEntries[initialElementCount - i - 1] = element;
  39696. }
  39697. }
  39698. /**
  39699. * Allocate an element in the array.
  39700. * @return the element info instance that contains the offset into the main buffer of the element's location.
  39701. * Beware, this offset may change when you call pack()
  39702. */
  39703. DynamicFloatArray.prototype.allocElement = function () {
  39704. if (this._freeEntries.length === 0) {
  39705. this._growBuffer();
  39706. }
  39707. var el = this._freeEntries.pop();
  39708. this._lastUsed = Math.max(el.offset, this._lastUsed);
  39709. if (el.offset === this._firstFree) {
  39710. if (this._freeEntries.length > 0) {
  39711. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  39712. }
  39713. else {
  39714. this._firstFree += this._stride;
  39715. }
  39716. }
  39717. return el;
  39718. };
  39719. /**
  39720. * Free the element corresponding to the given element info
  39721. * @param elInfo the element that describe the allocated element
  39722. */
  39723. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  39724. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  39725. this._freeEntries.push(elInfo);
  39726. };
  39727. /**
  39728. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  39729. * Instances of DynamicFloatArrayElement may have their 'offset' member changed as data could be copied from one location to another, so be sure to read/write your data based on the value inside this member after you called pack().
  39730. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  39731. */
  39732. DynamicFloatArray.prototype.pack = function () {
  39733. // no free slot? no need to pack
  39734. if (this._freeEntries.length === 0) {
  39735. return this.buffer;
  39736. }
  39737. // If the buffer is already packed the last used will always be lower than the first free
  39738. // The opposite may not be true, we can have a lastUsed greater than firstFree but the array still packed, because when an element is freed, lastUsed is not updated (for speed reason) so we may have a lastUsed of a freed element. But that's ok, well soon realize this case.
  39739. if (this._lastUsed < this._firstFree) {
  39740. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  39741. return elementsBuffer_1;
  39742. }
  39743. var s = this._stride;
  39744. // Make sure there's a free element at the very end, we need it to create a range where we'll move the used elements that may appear before
  39745. var lastFree = new DynamicFloatArrayElementInfo();
  39746. lastFree.offset = this.totalElementCount * s;
  39747. this._freeEntries.push(lastFree);
  39748. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  39749. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39750. var firstFreeSlotOffset = sortedFree[0].offset;
  39751. var freeZoneSize = 1;
  39752. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  39753. var prevOffset = sortedFree[0].offset;
  39754. for (var i = 1; i < sortedFree.length; i++) {
  39755. // If the first free (which means everything before is occupied) is greater or equal the occupied zone size, it means everything is defragmented, we can quit
  39756. if (firstFreeSlotOffset >= occupiedZoneSize) {
  39757. break;
  39758. }
  39759. var curFree = sortedFree[i];
  39760. var curOffset = curFree.offset;
  39761. // Compute the distance between this offset and the previous
  39762. var distance = curOffset - prevOffset;
  39763. // If the distance is the stride size, they are adjacent, it good, move to the next
  39764. if (distance === s) {
  39765. // Free zone is one element bigger
  39766. ++freeZoneSize;
  39767. // as we're about to iterate to the next, the cur becomes the previous...
  39768. prevOffset = curOffset;
  39769. continue;
  39770. }
  39771. // Distance is bigger, which means there's x element between the previous free and this one
  39772. var usedRange = (distance / s) - 1;
  39773. // Two cases the free zone is smaller than the data to move or bigger
  39774. // Copy what can fit in the free zone
  39775. var curMoveOffset = curOffset - s;
  39776. var copyCount = Math.min(freeZoneSize, usedRange);
  39777. for (var j = 0; j < copyCount; j++) {
  39778. var freeI = firstFreeSlotOffset / s;
  39779. var curI = curMoveOffset / s;
  39780. var moveEl = sortedAll[curI];
  39781. this._moveElement(moveEl, firstFreeSlotOffset);
  39782. var replacedEl = sortedAll[freeI];
  39783. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  39784. replacedEl.offset = curMoveOffset;
  39785. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  39786. sortedAll[freeI] = moveEl;
  39787. sortedAll[curI] = replacedEl;
  39788. curMoveOffset -= s;
  39789. firstFreeSlotOffset += s;
  39790. }
  39791. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  39792. if (freeZoneSize <= usedRange) {
  39793. firstFreeSlotOffset = curMoveOffset + s;
  39794. freeZoneSize = 1 + copyCount;
  39795. }
  39796. else {
  39797. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  39798. }
  39799. // as we're about to iterate to the next, the cur becomes the previous...
  39800. prevOffset = curOffset;
  39801. }
  39802. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  39803. this._lastUsed = firstFreeSlotOffset - s;
  39804. this._firstFree = firstFreeSlotOffset;
  39805. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  39806. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  39807. this._allEntries = sortedAll;
  39808. return elementsBuffer;
  39809. };
  39810. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  39811. for (var i = 0; i < this._stride; i++) {
  39812. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  39813. }
  39814. element.offset = destOffset;
  39815. };
  39816. DynamicFloatArray.prototype._growBuffer = function () {
  39817. // Allocate the new buffer with 50% more entries, copy the content of the current one
  39818. var newElCount = Math.floor(this.totalElementCount * 1.5);
  39819. var newBuffer = new Float32Array(newElCount * this._stride);
  39820. newBuffer.set(this.buffer);
  39821. var curCount = this.totalElementCount;
  39822. var addedCount = newElCount - this.totalElementCount;
  39823. for (var i = 0; i < addedCount; i++) {
  39824. var element = new DynamicFloatArrayElementInfo();
  39825. element.offset = (curCount + i) * this.stride;
  39826. this._allEntries.push(element);
  39827. this._freeEntries[addedCount - i - 1] = element;
  39828. }
  39829. this._firstFree = curCount * this.stride;
  39830. this.buffer = newBuffer;
  39831. };
  39832. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  39833. /**
  39834. * Get the total count of entries that can fit in the current buffer
  39835. * @returns the elements count
  39836. */
  39837. get: function () {
  39838. return this._allEntries.length;
  39839. },
  39840. enumerable: true,
  39841. configurable: true
  39842. });
  39843. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  39844. /**
  39845. * Get the count of free entries that can still be allocated without resizing the buffer
  39846. * @returns the free elements count
  39847. */
  39848. get: function () {
  39849. return this._freeEntries.length;
  39850. },
  39851. enumerable: true,
  39852. configurable: true
  39853. });
  39854. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  39855. /**
  39856. * Get the count of allocated elements
  39857. * @returns the allocated elements count
  39858. */
  39859. get: function () {
  39860. return this._allEntries.length - this._freeEntries.length;
  39861. },
  39862. enumerable: true,
  39863. configurable: true
  39864. });
  39865. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  39866. /**
  39867. * Return the size of one element in float
  39868. * @returns the size in float
  39869. */
  39870. get: function () {
  39871. return this._stride;
  39872. },
  39873. enumerable: true,
  39874. configurable: true
  39875. });
  39876. DynamicFloatArray.prototype.sort = function () {
  39877. var _this = this;
  39878. if (!this.compareValueOffset) {
  39879. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  39880. }
  39881. var count = this.usedElementCount;
  39882. // Do we have to (re)create the sort table?
  39883. if (!this._sortTable || this._sortTable.length < count) {
  39884. // Small heuristic... We don't want to allocate totalElementCount right away because it may have 50 for 3 used elements, but on the other side we don't want to allocate just 3 when we just need 2, so double this value to give us some air to breath...
  39885. var newCount = Math.min(this.totalElementCount, count * 2);
  39886. this._sortTable = new Array(newCount);
  39887. }
  39888. if (!this._sortedTable || this._sortedTable.length !== count) {
  39889. this._sortedTable = new Array(count);
  39890. }
  39891. // Because, you know...
  39892. this.pack();
  39893. //let stride = this.stride;
  39894. //for (let i = 0; i < count; i++) {
  39895. // let si = this._sortTable[i];
  39896. // if (!si) {
  39897. // si = new SortInfo();
  39898. // this._sortTable[i] = si;
  39899. // }
  39900. // si.entry = this._allEntries[i];
  39901. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  39902. // si.swapedOffset = null;
  39903. // this._sortedTable[i] = si;
  39904. //}
  39905. var curOffset = 0;
  39906. var stride = this.stride;
  39907. for (var i = 0; i < count; i++, curOffset += stride) {
  39908. var si = this._sortTable[i];
  39909. if (!si) {
  39910. si = new SortInfo();
  39911. this._sortTable[i] = si;
  39912. }
  39913. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  39914. si.offset = curOffset;
  39915. si.swapedOffset = null;
  39916. this._sortedTable[i] = si;
  39917. }
  39918. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  39919. if (this.sortingAscending) {
  39920. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  39921. }
  39922. else {
  39923. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  39924. }
  39925. var swapElements = function (src, dst) {
  39926. for (var i = 0; i < stride; i++) {
  39927. var tps = _this.buffer[dst + i];
  39928. _this.buffer[dst + i] = _this.buffer[src + i];
  39929. _this.buffer[src + i] = tps;
  39930. }
  39931. };
  39932. // The fun part begin, sortedTable give us the ordered layout to obtain, to get that we have to move elements, but when we move an element:
  39933. // it replaces an existing one.I don't want to allocate a new Float32Array and do a raw copy, because it's awful (GC - wise),
  39934. // and I still want something with a good algorithm complexity.
  39935. // So here's the deal: we are going to swap elements, but we have to track the change of location of the element being replaced,
  39936. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  39937. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  39938. // When we'll look for and element, we'll check if its swapedOffset is set, if so we reiterate the operation with the one there
  39939. // until we find a SortInfo object without a swapedOffset which means we got the right location
  39940. // Yes, we may have to do multiple iterations to find the right location, but hey, it won't be huge: <3 in most cases, and it's better
  39941. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  39942. for (var i = 0; i < count; i++) {
  39943. // Get the element to move
  39944. var sourceSI = this._sortedTable[i];
  39945. var destSI = this._sortTable[i];
  39946. var sourceOff = sourceSI.offset;
  39947. // If the source changed location, find the new one
  39948. if (sourceSI.swapedOffset) {
  39949. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  39950. var curSI = sourceSI;
  39951. while (curSI.swapedOffset) {
  39952. curSI = this._sortTable[curSI.swapedOffset / stride];
  39953. }
  39954. // Finally get the right location
  39955. sourceOff = curSI.offset;
  39956. }
  39957. // Tag the element being replaced with its new location
  39958. destSI.swapedOffset = sourceOff;
  39959. // Swap elements (only if needed)
  39960. if (sourceOff !== destSI.offset) {
  39961. swapElements(sourceOff, destSI.offset);
  39962. }
  39963. // Update the offset in the corresponding DFAE
  39964. //sourceSI.entry.offset = destSI.entry.offset;
  39965. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  39966. }
  39967. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  39968. return true;
  39969. };
  39970. return DynamicFloatArray;
  39971. }());
  39972. BABYLON.DynamicFloatArray = DynamicFloatArray;
  39973. var SortInfo = (function () {
  39974. function SortInfo() {
  39975. this.compareData = this.offset = this.swapedOffset = null;
  39976. }
  39977. return SortInfo;
  39978. }());
  39979. })(BABYLON || (BABYLON = {}));
  39980. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  39981. var BABYLON;
  39982. (function (BABYLON) {
  39983. /**
  39984. * This class given information about a given character.
  39985. */
  39986. var CharInfo = (function () {
  39987. function CharInfo() {
  39988. }
  39989. return CharInfo;
  39990. }());
  39991. BABYLON.CharInfo = CharInfo;
  39992. var FontTexture = (function (_super) {
  39993. __extends(FontTexture, _super);
  39994. /**
  39995. * Create a new instance of the FontTexture class
  39996. * @param name the name of the texture
  39997. * @param font the font to use, use the W3C CSS notation
  39998. * @param scene the scene that owns the texture
  39999. * @param maxCharCount the approximative maximum count of characters that could fit in the texture. This is an approximation because most of the fonts are proportional (each char has its own Width). The 'W' character's width is used to compute the size of the texture based on the given maxCharCount
  40000. * @param samplingMode the texture sampling mode
  40001. * @param superSample if true the FontTexture will be created with a font of a size twice bigger than the given one but all properties (lineHeight, charWidth, etc.) will be according to the original size. This is made to improve the text quality.
  40002. */
  40003. function FontTexture(name, font, scene, maxCharCount, samplingMode, superSample, signedDistanceField) {
  40004. if (maxCharCount === void 0) { maxCharCount = 200; }
  40005. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40006. if (superSample === void 0) { superSample = false; }
  40007. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40008. var _this = _super.call(this, null, scene, true, false, samplingMode) || this;
  40009. _this._charInfos = {};
  40010. _this._curCharCount = 0;
  40011. _this._lastUpdateCharCount = -1;
  40012. _this._usedCounter = 1;
  40013. _this.name = name;
  40014. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40015. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40016. _this._sdfScale = 8;
  40017. _this._signedDistanceField = signedDistanceField;
  40018. _this._superSample = false;
  40019. // SDF will use supersample no matter what, the resolution is otherwise too poor to produce correct result
  40020. if (superSample || signedDistanceField) {
  40021. var sfont = _this.getSuperSampleFont(font);
  40022. if (sfont) {
  40023. _this._superSample = true;
  40024. font = sfont;
  40025. }
  40026. }
  40027. // First canvas creation to determine the size of the texture to create
  40028. _this._canvas = document.createElement("canvas");
  40029. _this._context = _this._canvas.getContext("2d");
  40030. _this._context.font = font;
  40031. _this._context.fillStyle = "white";
  40032. _this._context.textBaseline = "top";
  40033. _this._cachedFontId = null;
  40034. var res = _this.getFontHeight(font);
  40035. _this._lineHeightSuper = res.height + 4;
  40036. _this._lineHeight = _this._superSample ? (Math.ceil(_this._lineHeightSuper / 2)) : _this._lineHeightSuper;
  40037. _this._offset = res.offset - 1;
  40038. _this._xMargin = 1 + Math.ceil(_this._lineHeightSuper / 15); // Right now this empiric formula seems to work...
  40039. _this._yMargin = _this._xMargin;
  40040. var maxCharWidth = _this._context.measureText("W").width;
  40041. _this._spaceWidthSuper = _this._context.measureText(" ").width;
  40042. _this._spaceWidth = _this._superSample ? (_this._spaceWidthSuper / 2) : _this._spaceWidthSuper;
  40043. // This is an approximate size, but should always be able to fit at least the maxCharCount
  40044. var totalEstSurface = (_this._lineHeightSuper + _this._yMargin) * (maxCharWidth + _this._xMargin) * maxCharCount;
  40045. var edge = Math.sqrt(totalEstSurface);
  40046. var textSize = Math.pow(2, Math.ceil(Math.log(edge) / Math.log(2)));
  40047. // Create the texture that will store the font characters
  40048. _this._texture = scene.getEngine().createDynamicTexture(textSize, textSize, false, samplingMode);
  40049. var textureSize = _this.getSize();
  40050. _this.hasAlpha = _this._signedDistanceField === false;
  40051. // Recreate a new canvas with the final size: the one matching the texture (resizing the previous one doesn't work as one would expect...)
  40052. _this._canvas = document.createElement("canvas");
  40053. _this._canvas.width = textureSize.width;
  40054. _this._canvas.height = textureSize.height;
  40055. _this._context = _this._canvas.getContext("2d");
  40056. _this._context.textBaseline = "top";
  40057. _this._context.font = font;
  40058. _this._context.fillStyle = "white";
  40059. _this._context.imageSmoothingEnabled = false;
  40060. _this._context.clearRect(0, 0, textureSize.width, textureSize.height);
  40061. // Create a canvas for the signed distance field mode, we only have to store one char, the purpose is to render a char scaled _sdfScale times
  40062. // into this 2D context, then get the bitmap data, create the sdf char and push the result in the _context (which hold the whole Font Texture content)
  40063. // So you can see this context as an intermediate one, because it is.
  40064. if (_this._signedDistanceField) {
  40065. var sdfC = document.createElement("canvas");
  40066. var s = _this._sdfScale;
  40067. sdfC.width = maxCharWidth * s;
  40068. sdfC.height = _this._lineHeightSuper * s;
  40069. var sdfCtx = sdfC.getContext("2d");
  40070. sdfCtx.scale(s, s);
  40071. sdfCtx.textBaseline = "top";
  40072. sdfCtx.font = font;
  40073. sdfCtx.fillStyle = "white";
  40074. sdfCtx.imageSmoothingEnabled = false;
  40075. _this._sdfCanvas = sdfC;
  40076. _this._sdfContext = sdfCtx;
  40077. }
  40078. _this._currentFreePosition = BABYLON.Vector2.Zero();
  40079. // Add the basic ASCII based characters
  40080. for (var i = 0x20; i < 0x7F; i++) {
  40081. var c = String.fromCharCode(i);
  40082. _this.getChar(c);
  40083. }
  40084. _this.update();
  40085. return _this;
  40086. }
  40087. Object.defineProperty(FontTexture.prototype, "isSuperSampled", {
  40088. get: function () {
  40089. return this._superSample;
  40090. },
  40091. enumerable: true,
  40092. configurable: true
  40093. });
  40094. Object.defineProperty(FontTexture.prototype, "isSignedDistanceField", {
  40095. get: function () {
  40096. return this._signedDistanceField;
  40097. },
  40098. enumerable: true,
  40099. configurable: true
  40100. });
  40101. Object.defineProperty(FontTexture.prototype, "spaceWidth", {
  40102. get: function () {
  40103. return this._spaceWidth;
  40104. },
  40105. enumerable: true,
  40106. configurable: true
  40107. });
  40108. Object.defineProperty(FontTexture.prototype, "lineHeight", {
  40109. get: function () {
  40110. return this._lineHeight;
  40111. },
  40112. enumerable: true,
  40113. configurable: true
  40114. });
  40115. FontTexture.GetCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40116. if (supersample === void 0) { supersample = false; }
  40117. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40118. var s = scene;
  40119. if (!s.__fontTextureCache__) {
  40120. s.__fontTextureCache__ = new BABYLON.StringDictionary();
  40121. }
  40122. var dic = s.__fontTextureCache__;
  40123. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40124. var ft = dic.get(lfn);
  40125. if (ft) {
  40126. ++ft._usedCounter;
  40127. return ft;
  40128. }
  40129. ft = new FontTexture(null, fontName, scene, supersample ? 100 : 200, BABYLON.Texture.BILINEAR_SAMPLINGMODE, supersample, signedDistanceField);
  40130. ft._cachedFontId = lfn;
  40131. dic.add(lfn, ft);
  40132. return ft;
  40133. };
  40134. FontTexture.ReleaseCachedFontTexture = function (scene, fontName, supersample, signedDistanceField) {
  40135. if (supersample === void 0) { supersample = false; }
  40136. if (signedDistanceField === void 0) { signedDistanceField = false; }
  40137. var s = scene;
  40138. var dic = s.__fontTextureCache__;
  40139. if (!dic) {
  40140. return;
  40141. }
  40142. var lfn = fontName.toLocaleLowerCase() + (supersample ? "_+SS" : "_-SS") + (signedDistanceField ? "_+SDF" : "_-SDF");
  40143. var font = dic.get(lfn);
  40144. if (--font._usedCounter === 0) {
  40145. dic.remove(lfn);
  40146. font.dispose();
  40147. }
  40148. };
  40149. /**
  40150. * Make sure the given char is present in the font map.
  40151. * @param char the character to get or add
  40152. * @return the CharInfo instance corresponding to the given character
  40153. */
  40154. FontTexture.prototype.getChar = function (char) {
  40155. if (char.length !== 1) {
  40156. return null;
  40157. }
  40158. var info = this._charInfos[char];
  40159. if (info) {
  40160. return info;
  40161. }
  40162. info = new CharInfo();
  40163. var measure = this._context.measureText(char);
  40164. var textureSize = this.getSize();
  40165. // we reached the end of the current line?
  40166. var width = Math.round(measure.width);
  40167. if (this._currentFreePosition.x + width + this._xMargin > textureSize.width) {
  40168. this._currentFreePosition.x = 0;
  40169. this._currentFreePosition.y += this._lineHeightSuper + this._yMargin;
  40170. // No more room?
  40171. if (this._currentFreePosition.y > textureSize.height) {
  40172. return this.getChar("!");
  40173. }
  40174. }
  40175. // In sdf mode we render the character in an intermediate 2D context which scale the character this._sdfScale times (which is required to compute the sdf map accurately)
  40176. if (this._signedDistanceField) {
  40177. this._sdfContext.clearRect(0, 0, this._sdfCanvas.width, this._sdfCanvas.height);
  40178. this._sdfContext.fillText(char, 0, -this._offset);
  40179. var data = this._sdfContext.getImageData(0, 0, width * this._sdfScale, this._sdfCanvas.height);
  40180. var res = this._computeSDFChar(data);
  40181. this._context.putImageData(res, this._currentFreePosition.x, this._currentFreePosition.y);
  40182. }
  40183. else {
  40184. // Draw the character in the HTML canvas
  40185. this._context.fillText(char, this._currentFreePosition.x, this._currentFreePosition.y - this._offset);
  40186. }
  40187. // Fill the CharInfo object
  40188. info.topLeftUV = new BABYLON.Vector2(this._currentFreePosition.x / textureSize.width, this._currentFreePosition.y / textureSize.height);
  40189. info.bottomRightUV = new BABYLON.Vector2((this._currentFreePosition.x + width) / textureSize.width, info.topLeftUV.y + ((this._lineHeightSuper + 2) / textureSize.height));
  40190. if (this._signedDistanceField) {
  40191. var off = 1 / textureSize.width;
  40192. info.topLeftUV.addInPlace(new BABYLON.Vector2(off, off));
  40193. info.bottomRightUV.addInPlace(new BABYLON.Vector2(off, off));
  40194. }
  40195. info.charWidth = this._superSample ? (width / 2) : width;
  40196. // Add the info structure
  40197. this._charInfos[char] = info;
  40198. this._curCharCount++;
  40199. // Set the next position
  40200. this._currentFreePosition.x += width + this._xMargin;
  40201. return info;
  40202. };
  40203. FontTexture.prototype._computeSDFChar = function (source) {
  40204. var scl = this._sdfScale;
  40205. var sw = source.width;
  40206. var sh = source.height;
  40207. var dw = sw / scl;
  40208. var dh = sh / scl;
  40209. var roffx = 0;
  40210. var roffy = 0;
  40211. // We shouldn't look beyond half of the biggest between width and height
  40212. var radius = scl;
  40213. var br = radius - 1;
  40214. var lookupSrc = function (dx, dy, offX, offY, lookVis) {
  40215. var sx = dx * scl;
  40216. var sy = dy * scl;
  40217. // Looking out of the area? return true to make the test going on
  40218. if (((sx + offX) < 0) || ((sx + offX) >= sw) || ((sy + offY) < 0) || ((sy + offY) >= sh)) {
  40219. return true;
  40220. }
  40221. // Get the pixel we want
  40222. var val = source.data[(((sy + offY) * sw) + (sx + offX)) * 4];
  40223. var res = (val > 0) === lookVis;
  40224. if (!res) {
  40225. roffx = offX;
  40226. roffy = offY;
  40227. }
  40228. return res;
  40229. };
  40230. var lookupArea = function (dx, dy, lookVis) {
  40231. // Fast rejection test, if we have the same result in N, S, W, E at a distance which is the radius-1 then it means the data will be consistent in this area. That's because we've scale the rendering of the letter "radius" times, so a letter's pixel will be at least radius wide
  40232. if (lookupSrc(dx, dy, 0, br, lookVis) &&
  40233. lookupSrc(dx, dy, 0, -br, lookVis) &&
  40234. lookupSrc(dx, dy, -br, 0, lookVis) &&
  40235. lookupSrc(dx, dy, br, 0, lookVis)) {
  40236. return 0;
  40237. }
  40238. for (var i = 1; i <= radius; i++) {
  40239. // Quick test N, S, W, E
  40240. if (!lookupSrc(dx, dy, 0, i, lookVis) || !lookupSrc(dx, dy, 0, -i, lookVis) || !lookupSrc(dx, dy, -i, 0, lookVis) || !lookupSrc(dx, dy, i, 0, lookVis)) {
  40241. return i * i; // Squared Distance is simple to compute in this case
  40242. }
  40243. // Test the frame area (except the N, S, W, E spots) from the nearest point from the center to the further one
  40244. for (var j = 1; j <= i; j++) {
  40245. if (!lookupSrc(dx, dy, -j, i, lookVis) || !lookupSrc(dx, dy, j, i, lookVis) ||
  40246. !lookupSrc(dx, dy, i, -j, lookVis) || !lookupSrc(dx, dy, i, j, lookVis) ||
  40247. !lookupSrc(dx, dy, -j, -i, lookVis) || !lookupSrc(dx, dy, j, -i, lookVis) ||
  40248. !lookupSrc(dx, dy, -i, -j, lookVis) || !lookupSrc(dx, dy, -i, j, lookVis)) {
  40249. // We found the nearest texel having and opposite state, store the squared length
  40250. var res_1 = (i * i) + (j * j);
  40251. var count = 1;
  40252. // To improve quality we will sample the texels around this one, so it's 8 samples, we consider only the one having an opposite state, add them to the current res and will will compute the average at the end
  40253. if (!lookupSrc(dx, dy, roffx - 1, roffy, lookVis)) {
  40254. res_1 += (roffx - 1) * (roffx - 1) + roffy * roffy;
  40255. ++count;
  40256. }
  40257. if (!lookupSrc(dx, dy, roffx + 1, roffy, lookVis)) {
  40258. res_1 += (roffx + 1) * (roffx + 1) + roffy * roffy;
  40259. ++count;
  40260. }
  40261. if (!lookupSrc(dx, dy, roffx, roffy - 1, lookVis)) {
  40262. res_1 += roffx * roffx + (roffy - 1) * (roffy - 1);
  40263. ++count;
  40264. }
  40265. if (!lookupSrc(dx, dy, roffx, roffy + 1, lookVis)) {
  40266. res_1 += roffx * roffx + (roffy + 1) * (roffy + 1);
  40267. ++count;
  40268. }
  40269. if (!lookupSrc(dx, dy, roffx - 1, roffy - 1, lookVis)) {
  40270. res_1 += (roffx - 1) * (roffx - 1) + (roffy - 1) * (roffy - 1);
  40271. ++count;
  40272. }
  40273. if (!lookupSrc(dx, dy, roffx + 1, roffy + 1, lookVis)) {
  40274. res_1 += (roffx + 1) * (roffx + 1) + (roffy + 1) * (roffy + 1);
  40275. ++count;
  40276. }
  40277. if (!lookupSrc(dx, dy, roffx + 1, roffy - 1, lookVis)) {
  40278. res_1 += (roffx + 1) * (roffx + 1) + (roffy - 1) * (roffy - 1);
  40279. ++count;
  40280. }
  40281. if (!lookupSrc(dx, dy, roffx - 1, roffy + 1, lookVis)) {
  40282. res_1 += (roffx - 1) * (roffx - 1) + (roffy + 1) * (roffy + 1);
  40283. ++count;
  40284. }
  40285. // Compute the average based on the accumulated distance
  40286. return res_1 / count;
  40287. }
  40288. }
  40289. }
  40290. return 0;
  40291. };
  40292. var tmp = new Array(dw * dh);
  40293. for (var y = 0; y < dh; y++) {
  40294. for (var x = 0; x < dw; x++) {
  40295. var curState = lookupSrc(x, y, 0, 0, true);
  40296. var d = lookupArea(x, y, curState);
  40297. if (d === 0) {
  40298. d = radius * radius * 2;
  40299. }
  40300. tmp[(y * dw) + x] = curState ? d : -d;
  40301. }
  40302. }
  40303. var res = this._context.createImageData(dw, dh);
  40304. var size = dw * dh;
  40305. for (var j = 0; j < size; j++) {
  40306. var d = tmp[j];
  40307. var sign = (d < 0) ? -1 : 1;
  40308. d = Math.sqrt(Math.abs(d)) * sign;
  40309. d *= 127.5 / radius;
  40310. d += 127.5;
  40311. if (d < 0) {
  40312. d = 0;
  40313. }
  40314. else if (d > 255) {
  40315. d = 255;
  40316. }
  40317. d += 0.5;
  40318. res.data[j * 4 + 0] = d;
  40319. res.data[j * 4 + 1] = d;
  40320. res.data[j * 4 + 2] = d;
  40321. res.data[j * 4 + 3] = 255;
  40322. }
  40323. return res;
  40324. };
  40325. FontTexture.prototype.measureText = function (text, tabulationSize) {
  40326. if (tabulationSize === void 0) { tabulationSize = 4; }
  40327. var maxWidth = 0;
  40328. var curWidth = 0;
  40329. var lineCount = 1;
  40330. var charxpos = 0;
  40331. // Parse each char of the string
  40332. for (var _i = 0, text_1 = text; _i < text_1.length; _i++) {
  40333. var char = text_1[_i];
  40334. // Next line feed?
  40335. if (char === "\n") {
  40336. maxWidth = Math.max(maxWidth, curWidth);
  40337. charxpos = 0;
  40338. curWidth = 0;
  40339. ++lineCount;
  40340. continue;
  40341. }
  40342. // Tabulation ?
  40343. if (char === "\t") {
  40344. var nextPos = charxpos + tabulationSize;
  40345. nextPos = nextPos - (nextPos % tabulationSize);
  40346. curWidth += (nextPos - charxpos) * this.spaceWidth;
  40347. charxpos = nextPos;
  40348. continue;
  40349. }
  40350. if (char < " ") {
  40351. continue;
  40352. }
  40353. curWidth += this.getChar(char).charWidth;
  40354. ++charxpos;
  40355. }
  40356. maxWidth = Math.max(maxWidth, curWidth);
  40357. return new BABYLON.Size(maxWidth, lineCount * this.lineHeight);
  40358. };
  40359. FontTexture.prototype.getSuperSampleFont = function (font) {
  40360. // Eternal thank to http://stackoverflow.com/a/10136041/802124
  40361. var regex = /^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\"\sa-z]+?)\s*$/;
  40362. var res = font.toLocaleLowerCase().match(regex);
  40363. if (res == null) {
  40364. return null;
  40365. }
  40366. var size = parseInt(res[4]);
  40367. res[4] = (size * 2).toString() + (res[4].match(/\D+/) || []).pop();
  40368. var newFont = "";
  40369. for (var j = 1; j < res.length; j++) {
  40370. if (res[j] != null) {
  40371. newFont += res[j] + " ";
  40372. }
  40373. }
  40374. return newFont;
  40375. };
  40376. // More info here: https://videlais.com/2014/03/16/the-many-and-varied-problems-with-measuring-font-height-for-html5-canvas/
  40377. FontTexture.prototype.getFontHeight = function (font) {
  40378. var fontDraw = document.createElement("canvas");
  40379. var ctx = fontDraw.getContext('2d');
  40380. ctx.fillRect(0, 0, fontDraw.width, fontDraw.height);
  40381. ctx.textBaseline = 'top';
  40382. ctx.fillStyle = 'white';
  40383. ctx.font = font;
  40384. ctx.fillText('jH|', 0, 0);
  40385. var pixels = ctx.getImageData(0, 0, fontDraw.width, fontDraw.height).data;
  40386. var start = -1;
  40387. var end = -1;
  40388. for (var row = 0; row < fontDraw.height; row++) {
  40389. for (var column = 0; column < fontDraw.width; column++) {
  40390. var index = (row * fontDraw.width + column) * 4;
  40391. if (pixels[index] === 0) {
  40392. if (column === fontDraw.width - 1 && start !== -1) {
  40393. end = row;
  40394. row = fontDraw.height;
  40395. break;
  40396. }
  40397. continue;
  40398. }
  40399. else {
  40400. if (start === -1) {
  40401. start = row;
  40402. }
  40403. break;
  40404. }
  40405. }
  40406. }
  40407. return { height: (end - start) + 1, offset: start - 1 };
  40408. };
  40409. Object.defineProperty(FontTexture.prototype, "canRescale", {
  40410. get: function () {
  40411. return false;
  40412. },
  40413. enumerable: true,
  40414. configurable: true
  40415. });
  40416. FontTexture.prototype.getContext = function () {
  40417. return this._context;
  40418. };
  40419. /**
  40420. * Call this method when you've call getChar() at least one time, this will update the texture if needed.
  40421. * Don't be afraid to call it, if no new character was added, this method simply does nothing.
  40422. */
  40423. FontTexture.prototype.update = function () {
  40424. // Update only if there's new char added since the previous update
  40425. if (this._lastUpdateCharCount < this._curCharCount) {
  40426. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, false, true);
  40427. this._lastUpdateCharCount = this._curCharCount;
  40428. }
  40429. };
  40430. // cloning should be prohibited, there's no point to duplicate this texture at all
  40431. FontTexture.prototype.clone = function () {
  40432. return null;
  40433. };
  40434. /**
  40435. * For FontTexture retrieved using GetCachedFontTexture, use this method when you transfer this object's lifetime to another party in order to share this resource.
  40436. * When the other party is done with this object, decCachedFontTextureCounter must be called.
  40437. */
  40438. FontTexture.prototype.incCachedFontTextureCounter = function () {
  40439. ++this._usedCounter;
  40440. };
  40441. /**
  40442. * Use this method only in conjunction with incCachedFontTextureCounter, call it when you no longer need to use this shared resource.
  40443. */
  40444. FontTexture.prototype.decCachedFontTextureCounter = function () {
  40445. var s = this.getScene();
  40446. var dic = s.__fontTextureCache__;
  40447. if (!dic) {
  40448. return;
  40449. }
  40450. if (--this._usedCounter === 0) {
  40451. dic.remove(this._cachedFontId);
  40452. this.dispose();
  40453. }
  40454. };
  40455. return FontTexture;
  40456. }(BABYLON.Texture));
  40457. BABYLON.FontTexture = FontTexture;
  40458. })(BABYLON || (BABYLON = {}));
  40459. //# sourceMappingURL=babylon.fontTexture.js.map
  40460. var BABYLON;
  40461. (function (BABYLON) {
  40462. var MapTexture = (function (_super) {
  40463. __extends(MapTexture, _super);
  40464. function MapTexture(name, scene, size, samplingMode, useMipMap) {
  40465. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  40466. if (useMipMap === void 0) { useMipMap = false; }
  40467. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  40468. _this.name = name;
  40469. _this._size = size;
  40470. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40471. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  40472. // Create the rectPackMap that will allocate portion of the texture
  40473. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height));
  40474. // Create the texture that will store the content
  40475. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  40476. return _this;
  40477. }
  40478. /**
  40479. * Allocate a rectangle of a given size in the texture map
  40480. * @param size the size of the rectangle to allocation
  40481. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  40482. */
  40483. MapTexture.prototype.allocateRect = function (size) {
  40484. return this._rectPackingMap.addRect(size);
  40485. };
  40486. /**
  40487. * Free a given rectangle from the texture map
  40488. * @param rectInfo the instance corresponding to the rect to free.
  40489. */
  40490. MapTexture.prototype.freeRect = function (rectInfo) {
  40491. if (rectInfo) {
  40492. rectInfo.freeContent();
  40493. }
  40494. };
  40495. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  40496. /**
  40497. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  40498. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  40499. * @returns {}
  40500. */
  40501. get: function () {
  40502. return this._rectPackingMap.freeSpace;
  40503. },
  40504. enumerable: true,
  40505. configurable: true
  40506. });
  40507. /**
  40508. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  40509. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  40510. * Don't forget to call unbindTexture when you're done rendering
  40511. * @param rect the zone to render to
  40512. * @param clear true to clear the portion's color/depth data
  40513. */
  40514. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  40515. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  40516. };
  40517. /**
  40518. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  40519. * Use this method when you want to render into the texture map with a clipspace set to the location and size of the given rect.
  40520. * Don't forget to call unbindTexture when you're done rendering
  40521. * @param pos the position into the texture
  40522. * @param size the portion to fit the clip space to
  40523. * @param clear true to clear the portion's color/depth data
  40524. */
  40525. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  40526. var engine = this.getScene().getEngine();
  40527. engine.bindFramebuffer(this._texture);
  40528. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  40529. if (clear) {
  40530. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  40531. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  40532. }
  40533. };
  40534. /**
  40535. * Unbind the texture map from the rendering engine.
  40536. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  40537. * @param dumpForDebug if set to true the content of the texture map will be dumped to a picture file that will be sent to the internet browser.
  40538. */
  40539. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  40540. // Dump ?
  40541. if (dumpForDebug) {
  40542. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  40543. }
  40544. var engine = this.getScene().getEngine();
  40545. if (this._replacedViewport) {
  40546. engine.setViewport(this._replacedViewport);
  40547. this._replacedViewport = null;
  40548. }
  40549. engine.unBindFramebuffer(this._texture);
  40550. };
  40551. Object.defineProperty(MapTexture.prototype, "canRescale", {
  40552. get: function () {
  40553. return false;
  40554. },
  40555. enumerable: true,
  40556. configurable: true
  40557. });
  40558. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  40559. // Anyway, there's not much point to use this method for this kind of texture I guess
  40560. MapTexture.prototype.clone = function () {
  40561. return null;
  40562. };
  40563. return MapTexture;
  40564. }(BABYLON.Texture));
  40565. BABYLON.MapTexture = MapTexture;
  40566. })(BABYLON || (BABYLON = {}));
  40567. //# sourceMappingURL=babylon.mapTexture.js.map
  40568. var BABYLON;
  40569. (function (BABYLON) {
  40570. var ShaderMaterial = (function (_super) {
  40571. __extends(ShaderMaterial, _super);
  40572. function ShaderMaterial(name, scene, shaderPath, options) {
  40573. var _this = _super.call(this, name, scene) || this;
  40574. _this._textures = {};
  40575. _this._textureArrays = {};
  40576. _this._floats = {};
  40577. _this._floatsArrays = {};
  40578. _this._colors3 = {};
  40579. _this._colors4 = {};
  40580. _this._vectors2 = {};
  40581. _this._vectors3 = {};
  40582. _this._vectors4 = {};
  40583. _this._matrices = {};
  40584. _this._matrices3x3 = {};
  40585. _this._matrices2x2 = {};
  40586. _this._vectors3Arrays = {};
  40587. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  40588. _this._shaderPath = shaderPath;
  40589. options.needAlphaBlending = options.needAlphaBlending || false;
  40590. options.needAlphaTesting = options.needAlphaTesting || false;
  40591. options.attributes = options.attributes || ["position", "normal", "uv"];
  40592. options.uniforms = options.uniforms || ["worldViewProjection"];
  40593. options.samplers = options.samplers || [];
  40594. options.defines = options.defines || [];
  40595. _this._options = options;
  40596. return _this;
  40597. }
  40598. ShaderMaterial.prototype.getClassName = function () {
  40599. return "ShaderMaterial";
  40600. };
  40601. ShaderMaterial.prototype.needAlphaBlending = function () {
  40602. return this._options.needAlphaBlending;
  40603. };
  40604. ShaderMaterial.prototype.needAlphaTesting = function () {
  40605. return this._options.needAlphaTesting;
  40606. };
  40607. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  40608. if (this._options.uniforms.indexOf(uniformName) === -1) {
  40609. this._options.uniforms.push(uniformName);
  40610. }
  40611. };
  40612. ShaderMaterial.prototype.setTexture = function (name, texture) {
  40613. if (this._options.samplers.indexOf(name) === -1) {
  40614. this._options.samplers.push(name);
  40615. }
  40616. this._textures[name] = texture;
  40617. return this;
  40618. };
  40619. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  40620. if (this._options.samplers.indexOf(name) === -1) {
  40621. this._options.samplers.push(name);
  40622. }
  40623. this._checkUniform(name);
  40624. this._textureArrays[name] = textures;
  40625. return this;
  40626. };
  40627. ShaderMaterial.prototype.setFloat = function (name, value) {
  40628. this._checkUniform(name);
  40629. this._floats[name] = value;
  40630. return this;
  40631. };
  40632. ShaderMaterial.prototype.setFloats = function (name, value) {
  40633. this._checkUniform(name);
  40634. this._floatsArrays[name] = value;
  40635. return this;
  40636. };
  40637. ShaderMaterial.prototype.setColor3 = function (name, value) {
  40638. this._checkUniform(name);
  40639. this._colors3[name] = value;
  40640. return this;
  40641. };
  40642. ShaderMaterial.prototype.setColor4 = function (name, value) {
  40643. this._checkUniform(name);
  40644. this._colors4[name] = value;
  40645. return this;
  40646. };
  40647. ShaderMaterial.prototype.setVector2 = function (name, value) {
  40648. this._checkUniform(name);
  40649. this._vectors2[name] = value;
  40650. return this;
  40651. };
  40652. ShaderMaterial.prototype.setVector3 = function (name, value) {
  40653. this._checkUniform(name);
  40654. this._vectors3[name] = value;
  40655. return this;
  40656. };
  40657. ShaderMaterial.prototype.setVector4 = function (name, value) {
  40658. this._checkUniform(name);
  40659. this._vectors4[name] = value;
  40660. return this;
  40661. };
  40662. ShaderMaterial.prototype.setMatrix = function (name, value) {
  40663. this._checkUniform(name);
  40664. this._matrices[name] = value;
  40665. return this;
  40666. };
  40667. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  40668. this._checkUniform(name);
  40669. this._matrices3x3[name] = value;
  40670. return this;
  40671. };
  40672. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  40673. this._checkUniform(name);
  40674. this._matrices2x2[name] = value;
  40675. return this;
  40676. };
  40677. ShaderMaterial.prototype.setArray3 = function (name, value) {
  40678. this._checkUniform(name);
  40679. this._vectors3Arrays[name] = value;
  40680. return this;
  40681. };
  40682. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  40683. if (!mesh) {
  40684. return true;
  40685. }
  40686. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  40687. return false;
  40688. }
  40689. return false;
  40690. };
  40691. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  40692. var scene = this.getScene();
  40693. var engine = scene.getEngine();
  40694. if (!this.checkReadyOnEveryCall) {
  40695. if (this._renderId === scene.getRenderId()) {
  40696. if (this._checkCache(scene, mesh, useInstances)) {
  40697. return true;
  40698. }
  40699. }
  40700. }
  40701. // Instances
  40702. var defines = [];
  40703. var fallbacks = new BABYLON.EffectFallbacks();
  40704. if (useInstances) {
  40705. defines.push("#define INSTANCES");
  40706. }
  40707. for (var index = 0; index < this._options.defines.length; index++) {
  40708. defines.push(this._options.defines[index]);
  40709. }
  40710. // Bones
  40711. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  40712. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  40713. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  40714. fallbacks.addCPUSkinningFallback(0, mesh);
  40715. }
  40716. // Alpha test
  40717. if (engine.getAlphaTesting()) {
  40718. defines.push("#define ALPHATEST");
  40719. }
  40720. var previousEffect = this._effect;
  40721. var join = defines.join("\n");
  40722. this._effect = engine.createEffect(this._shaderPath, this._options.attributes, this._options.uniforms, this._options.samplers, join, fallbacks, this.onCompiled, this.onError);
  40723. if (!this._effect.isReady()) {
  40724. return false;
  40725. }
  40726. if (previousEffect !== this._effect) {
  40727. scene.resetCachedMaterial();
  40728. }
  40729. this._renderId = scene.getRenderId();
  40730. return true;
  40731. };
  40732. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  40733. var scene = this.getScene();
  40734. if (this._options.uniforms.indexOf("world") !== -1) {
  40735. this._effect.setMatrix("world", world);
  40736. }
  40737. if (this._options.uniforms.indexOf("worldView") !== -1) {
  40738. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  40739. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  40740. }
  40741. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  40742. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  40743. }
  40744. };
  40745. ShaderMaterial.prototype.bind = function (world, mesh) {
  40746. // Std values
  40747. this.bindOnlyWorldMatrix(world);
  40748. if (this.getScene().getCachedMaterial() !== this) {
  40749. if (this._options.uniforms.indexOf("view") !== -1) {
  40750. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  40751. }
  40752. if (this._options.uniforms.indexOf("projection") !== -1) {
  40753. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  40754. }
  40755. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  40756. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  40757. }
  40758. // Bones
  40759. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  40760. var name;
  40761. // Texture
  40762. for (name in this._textures) {
  40763. this._effect.setTexture(name, this._textures[name]);
  40764. }
  40765. // Texture arrays
  40766. for (name in this._textureArrays) {
  40767. this._effect.setTextureArray(name, this._textureArrays[name]);
  40768. }
  40769. // Float
  40770. for (name in this._floats) {
  40771. this._effect.setFloat(name, this._floats[name]);
  40772. }
  40773. // Float s
  40774. for (name in this._floatsArrays) {
  40775. this._effect.setArray(name, this._floatsArrays[name]);
  40776. }
  40777. // Color3
  40778. for (name in this._colors3) {
  40779. this._effect.setColor3(name, this._colors3[name]);
  40780. }
  40781. // Color4
  40782. for (name in this._colors4) {
  40783. var color = this._colors4[name];
  40784. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  40785. }
  40786. // Vector2
  40787. for (name in this._vectors2) {
  40788. this._effect.setVector2(name, this._vectors2[name]);
  40789. }
  40790. // Vector3
  40791. for (name in this._vectors3) {
  40792. this._effect.setVector3(name, this._vectors3[name]);
  40793. }
  40794. // Vector4
  40795. for (name in this._vectors4) {
  40796. this._effect.setVector4(name, this._vectors4[name]);
  40797. }
  40798. // Matrix
  40799. for (name in this._matrices) {
  40800. this._effect.setMatrix(name, this._matrices[name]);
  40801. }
  40802. // Matrix 3x3
  40803. for (name in this._matrices3x3) {
  40804. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  40805. }
  40806. // Matrix 2x2
  40807. for (name in this._matrices2x2) {
  40808. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  40809. }
  40810. // Vector3Array
  40811. for (name in this._vectors3Arrays) {
  40812. this._effect.setArray3(name, this._vectors3Arrays[name]);
  40813. }
  40814. }
  40815. _super.prototype.bind.call(this, world, mesh);
  40816. };
  40817. ShaderMaterial.prototype.clone = function (name) {
  40818. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  40819. return newShaderMaterial;
  40820. };
  40821. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  40822. if (forceDisposeTextures) {
  40823. var name;
  40824. for (name in this._textures) {
  40825. this._textures[name].dispose();
  40826. }
  40827. for (name in this._textureArrays) {
  40828. var array = this._textureArrays[name];
  40829. for (var index = 0; index < array.length; index++) {
  40830. array[index].dispose();
  40831. }
  40832. }
  40833. }
  40834. this._textures = {};
  40835. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  40836. };
  40837. ShaderMaterial.prototype.serialize = function () {
  40838. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  40839. serializationObject.customType = "BABYLON.ShaderMaterial";
  40840. serializationObject.options = this._options;
  40841. serializationObject.shaderPath = this._shaderPath;
  40842. var name;
  40843. // Texture
  40844. serializationObject.textures = {};
  40845. for (name in this._textures) {
  40846. serializationObject.textures[name] = this._textures[name].serialize();
  40847. }
  40848. // Texture arrays
  40849. serializationObject.textureArrays = {};
  40850. for (name in this._textureArrays) {
  40851. serializationObject.textureArrays[name] = [];
  40852. var array = this._textureArrays[name];
  40853. for (var index = 0; index < array.length; index++) {
  40854. serializationObject.textureArrays[name].push(array[index].serialize());
  40855. }
  40856. }
  40857. // Float
  40858. serializationObject.floats = {};
  40859. for (name in this._floats) {
  40860. serializationObject.floats[name] = this._floats[name];
  40861. }
  40862. // Float s
  40863. serializationObject.floatArrays = {};
  40864. for (name in this._floatsArrays) {
  40865. serializationObject.floatArrays[name] = this._floatsArrays[name];
  40866. }
  40867. // Color3
  40868. serializationObject.colors3 = {};
  40869. for (name in this._colors3) {
  40870. serializationObject.colors3[name] = this._colors3[name].asArray();
  40871. }
  40872. // Color4
  40873. serializationObject.colors4 = {};
  40874. for (name in this._colors4) {
  40875. serializationObject.colors4[name] = this._colors4[name].asArray();
  40876. }
  40877. // Vector2
  40878. serializationObject.vectors2 = {};
  40879. for (name in this._vectors2) {
  40880. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  40881. }
  40882. // Vector3
  40883. serializationObject.vectors3 = {};
  40884. for (name in this._vectors3) {
  40885. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  40886. }
  40887. // Vector4
  40888. serializationObject.vectors4 = {};
  40889. for (name in this._vectors4) {
  40890. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  40891. }
  40892. // Matrix
  40893. serializationObject.matrices = {};
  40894. for (name in this._matrices) {
  40895. serializationObject.matrices[name] = this._matrices[name].asArray();
  40896. }
  40897. // Matrix 3x3
  40898. serializationObject.matrices3x3 = {};
  40899. for (name in this._matrices3x3) {
  40900. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  40901. }
  40902. // Matrix 2x2
  40903. serializationObject.matrices2x2 = {};
  40904. for (name in this._matrices2x2) {
  40905. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  40906. }
  40907. // Vector3Array
  40908. serializationObject.vectors3Arrays = {};
  40909. for (name in this._vectors3Arrays) {
  40910. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  40911. }
  40912. return serializationObject;
  40913. };
  40914. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  40915. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  40916. var name;
  40917. // Texture
  40918. for (name in source.textures) {
  40919. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  40920. }
  40921. // Texture arrays
  40922. for (name in source.textureArrays) {
  40923. var array = source.textureArrays[name];
  40924. var textureArray = new Array();
  40925. for (var index = 0; index < array.length; index++) {
  40926. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  40927. }
  40928. material.setTextureArray(name, textureArray);
  40929. }
  40930. // Float
  40931. for (name in source.floats) {
  40932. material.setFloat(name, source.floats[name]);
  40933. }
  40934. // Float s
  40935. for (name in source.floatsArrays) {
  40936. material.setFloats(name, source.floatsArrays[name]);
  40937. }
  40938. // Color3
  40939. for (name in source.colors3) {
  40940. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  40941. }
  40942. // Color4
  40943. for (name in source.colors4) {
  40944. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  40945. }
  40946. // Vector2
  40947. for (name in source.vectors2) {
  40948. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  40949. }
  40950. // Vector3
  40951. for (name in source.vectors3) {
  40952. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  40953. }
  40954. // Vector4
  40955. for (name in source.vectors4) {
  40956. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  40957. }
  40958. // Matrix
  40959. for (name in source.matrices) {
  40960. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  40961. }
  40962. // Matrix 3x3
  40963. for (name in source.matrices3x3) {
  40964. material.setMatrix3x3(name, source.matrices3x3[name]);
  40965. }
  40966. // Matrix 2x2
  40967. for (name in source.matrices2x2) {
  40968. material.setMatrix2x2(name, source.matrices2x2[name]);
  40969. }
  40970. // Vector3Array
  40971. for (name in source.vectors3Arrays) {
  40972. material.setArray3(name, source.vectors3Arrays[name]);
  40973. }
  40974. return material;
  40975. };
  40976. return ShaderMaterial;
  40977. }(BABYLON.Material));
  40978. BABYLON.ShaderMaterial = ShaderMaterial;
  40979. })(BABYLON || (BABYLON = {}));
  40980. //# sourceMappingURL=babylon.shaderMaterial.js.map
  40981. var BABYLON;
  40982. (function (BABYLON) {
  40983. var Internals;
  40984. (function (Internals) {
  40985. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  40986. // All values and structures referenced from:
  40987. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  40988. var DDS_MAGIC = 0x20534444;
  40989. 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;
  40990. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  40991. 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;
  40992. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  40993. function FourCCToInt32(value) {
  40994. return value.charCodeAt(0) +
  40995. (value.charCodeAt(1) << 8) +
  40996. (value.charCodeAt(2) << 16) +
  40997. (value.charCodeAt(3) << 24);
  40998. }
  40999. function Int32ToFourCC(value) {
  41000. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  41001. }
  41002. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  41003. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  41004. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  41005. var headerLengthInt = 31; // The header length in 32 bit ints
  41006. // Offsets into the header array
  41007. var off_magic = 0;
  41008. var off_size = 1;
  41009. var off_flags = 2;
  41010. var off_height = 3;
  41011. var off_width = 4;
  41012. var off_mipmapCount = 7;
  41013. var off_pfFlags = 20;
  41014. var off_pfFourCC = 21;
  41015. var off_RGBbpp = 22;
  41016. var off_RMask = 23;
  41017. var off_GMask = 24;
  41018. var off_BMask = 25;
  41019. var off_AMask = 26;
  41020. var off_caps1 = 27;
  41021. var off_caps2 = 28;
  41022. ;
  41023. var DDSTools = (function () {
  41024. function DDSTools() {
  41025. }
  41026. DDSTools.GetDDSInfo = function (arrayBuffer) {
  41027. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  41028. var mipmapCount = 1;
  41029. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  41030. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41031. }
  41032. return {
  41033. width: header[off_width],
  41034. height: header[off_height],
  41035. mipmapCount: mipmapCount,
  41036. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  41037. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  41038. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  41039. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP
  41040. };
  41041. };
  41042. DDSTools.GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41043. var byteArray = new Uint8Array(dataLength);
  41044. var srcData = new Uint8Array(arrayBuffer);
  41045. var index = 0;
  41046. for (var y = height - 1; y >= 0; y--) {
  41047. for (var x = 0; x < width; x++) {
  41048. var srcPos = dataOffset + (x + y * width) * 4;
  41049. byteArray[index + 2] = srcData[srcPos];
  41050. byteArray[index + 1] = srcData[srcPos + 1];
  41051. byteArray[index] = srcData[srcPos + 2];
  41052. byteArray[index + 3] = srcData[srcPos + 3];
  41053. index += 4;
  41054. }
  41055. }
  41056. return byteArray;
  41057. };
  41058. DDSTools.GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41059. var byteArray = new Uint8Array(dataLength);
  41060. var srcData = new Uint8Array(arrayBuffer);
  41061. var index = 0;
  41062. for (var y = height - 1; y >= 0; y--) {
  41063. for (var x = 0; x < width; x++) {
  41064. var srcPos = dataOffset + (x + y * width) * 3;
  41065. byteArray[index + 2] = srcData[srcPos];
  41066. byteArray[index + 1] = srcData[srcPos + 1];
  41067. byteArray[index] = srcData[srcPos + 2];
  41068. index += 3;
  41069. }
  41070. }
  41071. return byteArray;
  41072. };
  41073. DDSTools.GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  41074. var byteArray = new Uint8Array(dataLength);
  41075. var srcData = new Uint8Array(arrayBuffer);
  41076. var index = 0;
  41077. for (var y = height - 1; y >= 0; y--) {
  41078. for (var x = 0; x < width; x++) {
  41079. var srcPos = dataOffset + (x + y * width);
  41080. byteArray[index] = srcData[srcPos];
  41081. index++;
  41082. }
  41083. }
  41084. return byteArray;
  41085. };
  41086. DDSTools.UploadDDSLevels = function (gl, ext, arrayBuffer, info, loadMipmaps, faces) {
  41087. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, width, height, dataLength, dataOffset, byteArray, mipmapCount, i;
  41088. if (header[off_magic] != DDS_MAGIC) {
  41089. BABYLON.Tools.Error("Invalid magic number in DDS header");
  41090. return;
  41091. }
  41092. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  41093. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  41094. return;
  41095. }
  41096. if (info.isFourCC) {
  41097. fourCC = header[off_pfFourCC];
  41098. switch (fourCC) {
  41099. case FOURCC_DXT1:
  41100. blockBytes = 8;
  41101. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  41102. break;
  41103. case FOURCC_DXT3:
  41104. blockBytes = 16;
  41105. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  41106. break;
  41107. case FOURCC_DXT5:
  41108. blockBytes = 16;
  41109. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  41110. break;
  41111. default:
  41112. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  41113. return;
  41114. }
  41115. }
  41116. mipmapCount = 1;
  41117. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  41118. mipmapCount = Math.max(1, header[off_mipmapCount]);
  41119. }
  41120. var bpp = header[off_RGBbpp];
  41121. for (var face = 0; face < faces; face++) {
  41122. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  41123. width = header[off_width];
  41124. height = header[off_height];
  41125. dataOffset = header[off_size] + 4;
  41126. for (i = 0; i < mipmapCount; ++i) {
  41127. if (info.isRGB) {
  41128. if (bpp === 24) {
  41129. dataLength = width * height * 3;
  41130. byteArray = DDSTools.GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41131. gl.texImage2D(sampler, i, gl.RGB, width, height, 0, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  41132. }
  41133. else {
  41134. dataLength = width * height * 4;
  41135. byteArray = DDSTools.GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41136. gl.texImage2D(sampler, i, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  41137. }
  41138. }
  41139. else if (info.isLuminance) {
  41140. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  41141. var unpaddedRowSize = width;
  41142. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  41143. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  41144. byteArray = DDSTools.GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  41145. gl.texImage2D(sampler, i, gl.LUMINANCE, width, height, 0, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  41146. }
  41147. else {
  41148. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  41149. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  41150. gl.compressedTexImage2D(sampler, i, internalFormat, width, height, 0, byteArray);
  41151. }
  41152. dataOffset += dataLength;
  41153. width *= 0.5;
  41154. height *= 0.5;
  41155. width = Math.max(1.0, width);
  41156. height = Math.max(1.0, height);
  41157. }
  41158. }
  41159. };
  41160. return DDSTools;
  41161. }());
  41162. Internals.DDSTools = DDSTools;
  41163. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  41164. })(BABYLON || (BABYLON = {}));
  41165. //# sourceMappingURL=babylon.tools.dds.js.map
  41166. var BABYLON;
  41167. (function (BABYLON) {
  41168. var CannonJSPlugin = (function () {
  41169. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  41170. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  41171. if (iterations === void 0) { iterations = 10; }
  41172. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  41173. this.name = "CannonJSPlugin";
  41174. this._physicsMaterials = [];
  41175. this._fixedTimeStep = 1 / 60;
  41176. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41177. this._currentCollisionGroup = 2;
  41178. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  41179. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  41180. this._tmpPosition = BABYLON.Vector3.Zero();
  41181. this._tmpQuaternion = new BABYLON.Quaternion();
  41182. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  41183. this._tmpDeltaRotation = new BABYLON.Quaternion();
  41184. this._tmpUnityRotation = new BABYLON.Quaternion();
  41185. if (!this.isSupported()) {
  41186. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  41187. return;
  41188. }
  41189. this.world = new CANNON.World();
  41190. this.world.broadphase = new CANNON.NaiveBroadphase();
  41191. this.world.solver.iterations = iterations;
  41192. }
  41193. CannonJSPlugin.prototype.setGravity = function (gravity) {
  41194. this.world.gravity.copy(gravity);
  41195. };
  41196. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  41197. this._fixedTimeStep = timeStep;
  41198. };
  41199. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  41200. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  41201. };
  41202. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41203. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41204. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41205. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41206. };
  41207. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41208. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  41209. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  41210. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  41211. };
  41212. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41213. //parent-child relationship. Does this impostor has a parent impostor?
  41214. if (impostor.parent) {
  41215. if (impostor.physicsBody) {
  41216. this.removePhysicsBody(impostor);
  41217. //TODO is that needed?
  41218. impostor.forceUpdate();
  41219. }
  41220. return;
  41221. }
  41222. //should a new body be created for this impostor?
  41223. if (impostor.isBodyInitRequired()) {
  41224. var shape = this._createShape(impostor);
  41225. //unregister events, if body is being changed
  41226. var oldBody = impostor.physicsBody;
  41227. if (oldBody) {
  41228. this.removePhysicsBody(impostor);
  41229. }
  41230. //create the body and material
  41231. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  41232. var bodyCreationObject = {
  41233. mass: impostor.getParam("mass"),
  41234. material: material
  41235. };
  41236. // A simple extend, in case native options were used.
  41237. var nativeOptions = impostor.getParam("nativeOptions");
  41238. for (var key in nativeOptions) {
  41239. if (nativeOptions.hasOwnProperty(key)) {
  41240. bodyCreationObject[key] = nativeOptions[key];
  41241. }
  41242. }
  41243. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  41244. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  41245. this.world.addEventListener("preStep", impostor.beforeStep);
  41246. this.world.addEventListener("postStep", impostor.afterStep);
  41247. impostor.physicsBody.addShape(shape);
  41248. this.world.add(impostor.physicsBody);
  41249. //try to keep the body moving in the right direction by taking old properties.
  41250. //Should be tested!
  41251. if (oldBody) {
  41252. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  41253. impostor.physicsBody[param].copy(oldBody[param]);
  41254. });
  41255. }
  41256. this._processChildMeshes(impostor);
  41257. }
  41258. //now update the body's transformation
  41259. this._updatePhysicsBodyTransformation(impostor);
  41260. };
  41261. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  41262. var _this = this;
  41263. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  41264. if (meshChildren.length) {
  41265. var processMesh = function (localPosition, mesh) {
  41266. var childImpostor = mesh.getPhysicsImpostor();
  41267. if (childImpostor) {
  41268. var parent = childImpostor.parent;
  41269. if (parent !== mainImpostor) {
  41270. var localPosition = mesh.position;
  41271. if (childImpostor.physicsBody) {
  41272. _this.removePhysicsBody(childImpostor);
  41273. childImpostor.physicsBody = null;
  41274. }
  41275. childImpostor.parent = mainImpostor;
  41276. childImpostor.resetUpdateFlags();
  41277. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  41278. //Add the mass of the children.
  41279. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  41280. }
  41281. }
  41282. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  41283. };
  41284. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  41285. }
  41286. };
  41287. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41288. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  41289. this.world.removeEventListener("preStep", impostor.beforeStep);
  41290. this.world.removeEventListener("postStep", impostor.afterStep);
  41291. this.world.remove(impostor.physicsBody);
  41292. };
  41293. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41294. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41295. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41296. if (!mainBody || !connectedBody) {
  41297. return;
  41298. }
  41299. var constraint;
  41300. var jointData = impostorJoint.joint.jointData;
  41301. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  41302. var constraintData = {
  41303. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  41304. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  41305. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  41306. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  41307. maxForce: jointData.nativeParams.maxForce,
  41308. collideConnected: !!jointData.collision
  41309. };
  41310. //Not needed, Cannon has a collideConnected flag
  41311. /*if (!jointData.collision) {
  41312. //add 1st body to a collision group of its own, if it is not in 1
  41313. if (mainBody.collisionFilterGroup === 1) {
  41314. mainBody.collisionFilterGroup = this._currentCollisionGroup;
  41315. this._currentCollisionGroup <<= 1;
  41316. }
  41317. if (connectedBody.collisionFilterGroup === 1) {
  41318. connectedBody.collisionFilterGroup = this._currentCollisionGroup;
  41319. this._currentCollisionGroup <<= 1;
  41320. }
  41321. //add their mask to the collisionFilterMask of each other:
  41322. connectedBody.collisionFilterMask = connectedBody.collisionFilterMask | ~mainBody.collisionFilterGroup;
  41323. mainBody.collisionFilterMask = mainBody.collisionFilterMask | ~connectedBody.collisionFilterGroup;
  41324. }*/
  41325. switch (impostorJoint.joint.type) {
  41326. case BABYLON.PhysicsJoint.HingeJoint:
  41327. case BABYLON.PhysicsJoint.Hinge2Joint:
  41328. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  41329. break;
  41330. case BABYLON.PhysicsJoint.DistanceJoint:
  41331. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  41332. break;
  41333. case BABYLON.PhysicsJoint.SpringJoint:
  41334. var springData = jointData;
  41335. constraint = new CANNON.Spring(mainBody, connectedBody, {
  41336. restLength: springData.length,
  41337. stiffness: springData.stiffness,
  41338. damping: springData.damping,
  41339. localAnchorA: constraintData.pivotA,
  41340. localAnchorB: constraintData.pivotB
  41341. });
  41342. break;
  41343. case BABYLON.PhysicsJoint.LockJoint:
  41344. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  41345. break;
  41346. case BABYLON.PhysicsJoint.PointToPointJoint:
  41347. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41348. default:
  41349. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  41350. break;
  41351. }
  41352. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  41353. constraint.collideConnected = !!jointData.collision;
  41354. impostorJoint.joint.physicsJoint = constraint;
  41355. //don't add spring as constraint, as it is not one.
  41356. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  41357. this.world.addConstraint(constraint);
  41358. }
  41359. else {
  41360. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  41361. constraint.applyForce();
  41362. });
  41363. }
  41364. };
  41365. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41366. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  41367. };
  41368. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  41369. var index;
  41370. var mat;
  41371. for (index = 0; index < this._physicsMaterials.length; index++) {
  41372. mat = this._physicsMaterials[index];
  41373. if (mat.friction === friction && mat.restitution === restitution) {
  41374. return mat;
  41375. }
  41376. }
  41377. var currentMat = new CANNON.Material(name);
  41378. currentMat.friction = friction;
  41379. currentMat.restitution = restitution;
  41380. this._physicsMaterials.push(currentMat);
  41381. return currentMat;
  41382. };
  41383. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  41384. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  41385. };
  41386. CannonJSPlugin.prototype._createShape = function (impostor) {
  41387. var object = impostor.object;
  41388. var returnValue;
  41389. var extendSize = impostor.getObjectExtendSize();
  41390. switch (impostor.type) {
  41391. case BABYLON.PhysicsEngine.SphereImpostor:
  41392. var radiusX = extendSize.x;
  41393. var radiusY = extendSize.y;
  41394. var radiusZ = extendSize.z;
  41395. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  41396. break;
  41397. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  41398. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41399. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  41400. break;
  41401. case BABYLON.PhysicsImpostor.BoxImpostor:
  41402. var box = extendSize.scale(0.5);
  41403. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  41404. break;
  41405. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41406. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  41407. returnValue = new CANNON.Plane();
  41408. break;
  41409. case BABYLON.PhysicsImpostor.MeshImpostor:
  41410. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  41411. var rawFaces = object.getIndices ? object.getIndices() : [];
  41412. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  41413. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  41414. break;
  41415. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  41416. returnValue = this._createHeightmap(object);
  41417. break;
  41418. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41419. returnValue = new CANNON.Particle();
  41420. break;
  41421. }
  41422. return returnValue;
  41423. };
  41424. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  41425. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41426. var matrix = [];
  41427. //For now pointDepth will not be used and will be automatically calculated.
  41428. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  41429. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  41430. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSize.x, object.getBoundingInfo().boundingBox.extendSize.z);
  41431. var elementSize = dim * 2 / arraySize;
  41432. var minY = object.getBoundingInfo().boundingBox.extendSize.y;
  41433. for (var i = 0; i < pos.length; i = i + 3) {
  41434. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  41435. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  41436. var y = pos[i + 1] + minY;
  41437. if (!matrix[x]) {
  41438. matrix[x] = [];
  41439. }
  41440. if (!matrix[x][z]) {
  41441. matrix[x][z] = y;
  41442. }
  41443. matrix[x][z] = Math.max(y, matrix[x][z]);
  41444. }
  41445. for (var x = 0; x <= arraySize; ++x) {
  41446. if (!matrix[x]) {
  41447. var loc = 1;
  41448. while (!matrix[(x + loc) % arraySize]) {
  41449. loc++;
  41450. }
  41451. matrix[x] = matrix[(x + loc) % arraySize].slice();
  41452. }
  41453. for (var z = 0; z <= arraySize; ++z) {
  41454. if (!matrix[x][z]) {
  41455. var loc = 1;
  41456. var newValue;
  41457. while (newValue === undefined) {
  41458. newValue = matrix[x][(z + loc++) % arraySize];
  41459. }
  41460. matrix[x][z] = newValue;
  41461. }
  41462. }
  41463. }
  41464. var shape = new CANNON.Heightfield(matrix, {
  41465. elementSize: elementSize
  41466. });
  41467. //For future reference, needed for body transformation
  41468. shape.minY = minY;
  41469. return shape;
  41470. };
  41471. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  41472. var object = impostor.object;
  41473. //make sure it is updated...
  41474. object.computeWorldMatrix && object.computeWorldMatrix(true);
  41475. // The delta between the mesh position and the mesh bounding box center
  41476. var center = impostor.getObjectCenter();
  41477. var extendSize = impostor.getObjectExtendSize();
  41478. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  41479. this._tmpPosition.copyFrom(center);
  41480. var quaternion = object.rotationQuaternion;
  41481. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  41482. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  41483. //-90 DEG in X, precalculated
  41484. quaternion = quaternion.multiply(this._minus90X);
  41485. //Invert! (Precalculated, 90 deg in X)
  41486. //No need to clone. this will never change.
  41487. impostor.setDeltaRotation(this._plus90X);
  41488. }
  41489. //If it is a heightfield, if should be centered.
  41490. if (impostor.type === BABYLON.PhysicsEngine.HeightmapImpostor) {
  41491. var mesh = object;
  41492. //calculate the correct body position:
  41493. var rotationQuaternion = mesh.rotationQuaternion;
  41494. mesh.rotationQuaternion = this._tmpUnityRotation;
  41495. mesh.computeWorldMatrix(true);
  41496. //get original center with no rotation
  41497. var c = center.clone();
  41498. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  41499. //rotation is back
  41500. mesh.rotationQuaternion = rotationQuaternion;
  41501. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  41502. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSize.x, 0, -mesh.getBoundingInfo().boundingBox.extendSize.z);
  41503. mesh.setPivotMatrix(p);
  41504. mesh.computeWorldMatrix(true);
  41505. //calculate the translation
  41506. var translation = mesh.getBoundingInfo().boundingBox.center.subtract(center).subtract(mesh.position).negate();
  41507. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSize.y, translation.z);
  41508. //add it inverted to the delta
  41509. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.center.subtract(c));
  41510. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSize.y;
  41511. mesh.setPivotMatrix(oldPivot);
  41512. mesh.computeWorldMatrix(true);
  41513. }
  41514. else if (impostor.type === BABYLON.PhysicsEngine.MeshImpostor) {
  41515. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  41516. this._tmpPosition.copyFrom(object.position);
  41517. }
  41518. impostor.setDeltaPosition(this._tmpDeltaPosition);
  41519. //Now update the impostor object
  41520. impostor.physicsBody.position.copy(this._tmpPosition);
  41521. impostor.physicsBody.quaternion.copy(quaternion);
  41522. };
  41523. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41524. impostor.object.position.copyFrom(impostor.physicsBody.position);
  41525. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  41526. };
  41527. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41528. impostor.physicsBody.position.copy(newPosition);
  41529. impostor.physicsBody.quaternion.copy(newRotation);
  41530. };
  41531. CannonJSPlugin.prototype.isSupported = function () {
  41532. return window.CANNON !== undefined;
  41533. };
  41534. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41535. impostor.physicsBody.velocity.copy(velocity);
  41536. };
  41537. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41538. impostor.physicsBody.angularVelocity.copy(velocity);
  41539. };
  41540. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41541. var v = impostor.physicsBody.velocity;
  41542. if (!v)
  41543. return null;
  41544. return new BABYLON.Vector3(v.x, v.y, v.z);
  41545. };
  41546. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41547. var v = impostor.physicsBody.angularVelocity;
  41548. if (!v)
  41549. return null;
  41550. return new BABYLON.Vector3(v.x, v.y, v.z);
  41551. };
  41552. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41553. impostor.physicsBody.mass = mass;
  41554. impostor.physicsBody.updateMassProperties();
  41555. };
  41556. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  41557. impostor.physicsBody.sleep();
  41558. };
  41559. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  41560. impostor.physicsBody.wakeUp();
  41561. };
  41562. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41563. joint.physicsJoint.distance = maxDistance;
  41564. };
  41565. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  41566. if (!motorIndex) {
  41567. joint.physicsJoint.enableMotor();
  41568. }
  41569. };
  41570. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  41571. if (!motorIndex) {
  41572. joint.physicsJoint.disableMotor();
  41573. }
  41574. };
  41575. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41576. if (!motorIndex) {
  41577. joint.physicsJoint.enableMotor();
  41578. joint.physicsJoint.setMotorSpeed(speed);
  41579. if (maxForce) {
  41580. this.setLimit(joint, maxForce);
  41581. }
  41582. }
  41583. };
  41584. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  41585. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  41586. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  41587. };
  41588. CannonJSPlugin.prototype.dispose = function () {
  41589. //nothing to do, actually.
  41590. };
  41591. return CannonJSPlugin;
  41592. }());
  41593. BABYLON.CannonJSPlugin = CannonJSPlugin;
  41594. })(BABYLON || (BABYLON = {}));
  41595. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  41596. var BABYLON;
  41597. (function (BABYLON) {
  41598. var OimoJSPlugin = (function () {
  41599. function OimoJSPlugin(iterations) {
  41600. this.name = "OimoJSPlugin";
  41601. this._tmpImpostorsArray = [];
  41602. this._tmpPositionVector = BABYLON.Vector3.Zero();
  41603. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  41604. this.world.worldscale(1);
  41605. this.world.clear();
  41606. //making sure no stats are calculated
  41607. this.world.isNoStat = true;
  41608. }
  41609. OimoJSPlugin.prototype.setGravity = function (gravity) {
  41610. this.world.gravity.copy(gravity);
  41611. };
  41612. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  41613. this.world.timeStep = timeStep;
  41614. };
  41615. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  41616. var _this = this;
  41617. impostors.forEach(function (impostor) {
  41618. impostor.beforeStep();
  41619. });
  41620. this.world.step();
  41621. impostors.forEach(function (impostor) {
  41622. impostor.afterStep();
  41623. //update the ordered impostors array
  41624. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  41625. });
  41626. //check for collisions
  41627. var contact = this.world.contacts;
  41628. while (contact !== null) {
  41629. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  41630. contact = contact.next;
  41631. continue;
  41632. }
  41633. //is this body colliding with any other? get the impostor
  41634. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  41635. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  41636. if (!mainImpostor || !collidingImpostor) {
  41637. contact = contact.next;
  41638. continue;
  41639. }
  41640. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  41641. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  41642. contact = contact.next;
  41643. }
  41644. };
  41645. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  41646. var mass = impostor.physicsBody.massInfo.mass;
  41647. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  41648. };
  41649. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  41650. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  41651. this.applyImpulse(impostor, force, contactPoint);
  41652. };
  41653. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  41654. var _this = this;
  41655. //parent-child relationship. Does this impostor has a parent impostor?
  41656. if (impostor.parent) {
  41657. if (impostor.physicsBody) {
  41658. this.removePhysicsBody(impostor);
  41659. //TODO is that needed?
  41660. impostor.forceUpdate();
  41661. }
  41662. return;
  41663. }
  41664. if (impostor.isBodyInitRequired()) {
  41665. var bodyConfig = {
  41666. name: impostor.uniqueId,
  41667. //Oimo must have mass, also for static objects.
  41668. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  41669. size: [],
  41670. type: [],
  41671. pos: [],
  41672. rot: [],
  41673. move: impostor.getParam("mass") !== 0,
  41674. //Supporting older versions of Oimo
  41675. world: this.world
  41676. };
  41677. var impostors = [impostor];
  41678. var addToArray = function (parent) {
  41679. if (!parent.getChildMeshes)
  41680. return;
  41681. parent.getChildMeshes().forEach(function (m) {
  41682. if (m.physicsImpostor) {
  41683. impostors.push(m.physicsImpostor);
  41684. m.physicsImpostor._init();
  41685. }
  41686. });
  41687. };
  41688. addToArray(impostor.object);
  41689. var checkWithEpsilon_1 = function (value) {
  41690. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  41691. };
  41692. impostors.forEach(function (i) {
  41693. //get the correct bounding box
  41694. var oldQuaternion = i.object.rotationQuaternion;
  41695. var rot = new OIMO.Euler().setFromQuaternion({
  41696. x: impostor.object.rotationQuaternion.x,
  41697. y: impostor.object.rotationQuaternion.y,
  41698. z: impostor.object.rotationQuaternion.z,
  41699. s: impostor.object.rotationQuaternion.w
  41700. });
  41701. var extendSize = i.getObjectExtendSize();
  41702. if (i === impostor) {
  41703. var center = impostor.getObjectCenter();
  41704. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  41705. //Can also use Array.prototype.push.apply
  41706. bodyConfig.pos.push(center.x);
  41707. bodyConfig.pos.push(center.y);
  41708. bodyConfig.pos.push(center.z);
  41709. //tmp solution
  41710. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  41711. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  41712. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  41713. }
  41714. else {
  41715. bodyConfig.pos.push(i.object.position.x);
  41716. bodyConfig.pos.push(i.object.position.y);
  41717. bodyConfig.pos.push(i.object.position.z);
  41718. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  41719. bodyConfig.rot.push(0);
  41720. bodyConfig.rot.push(0);
  41721. bodyConfig.rot.push(0);
  41722. }
  41723. // register mesh
  41724. switch (i.type) {
  41725. case BABYLON.PhysicsImpostor.ParticleImpostor:
  41726. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  41727. case BABYLON.PhysicsImpostor.SphereImpostor:
  41728. var radiusX = extendSize.x;
  41729. var radiusY = extendSize.y;
  41730. var radiusZ = extendSize.z;
  41731. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  41732. bodyConfig.type.push('sphere');
  41733. //due to the way oimo works with compounds, add 3 times
  41734. bodyConfig.size.push(size);
  41735. bodyConfig.size.push(size);
  41736. bodyConfig.size.push(size);
  41737. break;
  41738. case BABYLON.PhysicsImpostor.CylinderImpostor:
  41739. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  41740. var sizeY = checkWithEpsilon_1(extendSize.y);
  41741. bodyConfig.type.push('cylinder');
  41742. bodyConfig.size.push(sizeX);
  41743. bodyConfig.size.push(sizeY);
  41744. //due to the way oimo works with compounds, add one more value.
  41745. bodyConfig.size.push(sizeY);
  41746. break;
  41747. case BABYLON.PhysicsImpostor.PlaneImpostor:
  41748. case BABYLON.PhysicsImpostor.BoxImpostor:
  41749. default:
  41750. var sizeX = checkWithEpsilon_1(extendSize.x);
  41751. var sizeY = checkWithEpsilon_1(extendSize.y);
  41752. var sizeZ = checkWithEpsilon_1(extendSize.z);
  41753. bodyConfig.type.push('box');
  41754. bodyConfig.size.push(sizeX);
  41755. bodyConfig.size.push(sizeY);
  41756. bodyConfig.size.push(sizeZ);
  41757. break;
  41758. }
  41759. //actually not needed, but hey...
  41760. i.object.rotationQuaternion = oldQuaternion;
  41761. });
  41762. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  41763. }
  41764. else {
  41765. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  41766. }
  41767. impostor.setDeltaPosition(this._tmpPositionVector);
  41768. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  41769. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  41770. };
  41771. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  41772. //impostor.physicsBody.dispose();
  41773. //Same as : (older oimo versions)
  41774. this.world.removeRigidBody(impostor.physicsBody);
  41775. };
  41776. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  41777. var mainBody = impostorJoint.mainImpostor.physicsBody;
  41778. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  41779. if (!mainBody || !connectedBody) {
  41780. return;
  41781. }
  41782. var jointData = impostorJoint.joint.jointData;
  41783. var options = jointData.nativeParams || {};
  41784. var type;
  41785. var nativeJointData = {
  41786. body1: mainBody,
  41787. body2: connectedBody,
  41788. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  41789. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  41790. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  41791. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  41792. min: options.min,
  41793. max: options.max,
  41794. collision: options.collision || jointData.collision,
  41795. spring: options.spring,
  41796. //supporting older version of Oimo
  41797. world: this.world
  41798. };
  41799. switch (impostorJoint.joint.type) {
  41800. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  41801. type = "jointBall";
  41802. break;
  41803. case BABYLON.PhysicsJoint.SpringJoint:
  41804. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  41805. var springData = jointData;
  41806. nativeJointData.min = springData.length || nativeJointData.min;
  41807. //Max should also be set, just make sure it is at least min
  41808. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  41809. case BABYLON.PhysicsJoint.DistanceJoint:
  41810. type = "jointDistance";
  41811. nativeJointData.max = jointData.maxDistance;
  41812. break;
  41813. case BABYLON.PhysicsJoint.PrismaticJoint:
  41814. type = "jointPrisme";
  41815. break;
  41816. case BABYLON.PhysicsJoint.SliderJoint:
  41817. type = "jointSlide";
  41818. break;
  41819. case BABYLON.PhysicsJoint.WheelJoint:
  41820. type = "jointWheel";
  41821. break;
  41822. case BABYLON.PhysicsJoint.HingeJoint:
  41823. default:
  41824. type = "jointHinge";
  41825. break;
  41826. }
  41827. nativeJointData.type = type;
  41828. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  41829. };
  41830. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  41831. //Bug in Oimo prevents us from disposing a joint in the playground
  41832. //joint.joint.physicsJoint.dispose();
  41833. //So we will bruteforce it!
  41834. try {
  41835. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  41836. }
  41837. catch (e) {
  41838. BABYLON.Tools.Warn(e);
  41839. }
  41840. };
  41841. OimoJSPlugin.prototype.isSupported = function () {
  41842. return OIMO !== undefined;
  41843. };
  41844. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  41845. if (!impostor.physicsBody.sleeping) {
  41846. //TODO check that
  41847. if (impostor.physicsBody.shapes.next) {
  41848. var parentShape = this._getLastShape(impostor.physicsBody);
  41849. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  41850. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  41851. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  41852. }
  41853. else {
  41854. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  41855. }
  41856. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  41857. impostor.object.rotationQuaternion.normalize();
  41858. }
  41859. };
  41860. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  41861. var body = impostor.physicsBody;
  41862. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  41863. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  41864. body.syncShapes();
  41865. body.awake();
  41866. };
  41867. OimoJSPlugin.prototype._getLastShape = function (body) {
  41868. var lastShape = body.shapes;
  41869. while (lastShape.next) {
  41870. lastShape = lastShape.next;
  41871. }
  41872. return lastShape;
  41873. };
  41874. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  41875. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  41876. };
  41877. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  41878. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  41879. };
  41880. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  41881. var v = impostor.physicsBody.linearVelocity;
  41882. if (!v)
  41883. return null;
  41884. return new BABYLON.Vector3(v.x, v.y, v.z);
  41885. };
  41886. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  41887. var v = impostor.physicsBody.angularVelocity;
  41888. if (!v)
  41889. return null;
  41890. return new BABYLON.Vector3(v.x, v.y, v.z);
  41891. };
  41892. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  41893. var staticBody = mass === 0;
  41894. //this will actually set the body's density and not its mass.
  41895. //But this is how oimo treats the mass variable.
  41896. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  41897. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  41898. };
  41899. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  41900. impostor.physicsBody.sleep();
  41901. };
  41902. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  41903. impostor.physicsBody.awake();
  41904. };
  41905. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  41906. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  41907. if (minDistance !== void 0) {
  41908. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  41909. }
  41910. };
  41911. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  41912. //TODO separate rotational and transational motors.
  41913. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41914. if (motor) {
  41915. motor.setMotor(speed, maxForce);
  41916. }
  41917. };
  41918. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  41919. //TODO separate rotational and transational motors.
  41920. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  41921. if (motor) {
  41922. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  41923. }
  41924. };
  41925. OimoJSPlugin.prototype.dispose = function () {
  41926. this.world.clear();
  41927. };
  41928. return OimoJSPlugin;
  41929. }());
  41930. BABYLON.OimoJSPlugin = OimoJSPlugin;
  41931. })(BABYLON || (BABYLON = {}));
  41932. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  41933. var BABYLON;
  41934. (function (BABYLON) {
  41935. var DisplayPassPostProcess = (function (_super) {
  41936. __extends(DisplayPassPostProcess, _super);
  41937. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  41938. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  41939. }
  41940. return DisplayPassPostProcess;
  41941. }(BABYLON.PostProcess));
  41942. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  41943. })(BABYLON || (BABYLON = {}));
  41944. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  41945. var BABYLON;
  41946. (function (BABYLON) {
  41947. var SimplificationSettings = (function () {
  41948. function SimplificationSettings(quality, distance, optimizeMesh) {
  41949. this.quality = quality;
  41950. this.distance = distance;
  41951. this.optimizeMesh = optimizeMesh;
  41952. }
  41953. return SimplificationSettings;
  41954. }());
  41955. BABYLON.SimplificationSettings = SimplificationSettings;
  41956. var SimplificationQueue = (function () {
  41957. function SimplificationQueue() {
  41958. this.running = false;
  41959. this._simplificationArray = [];
  41960. }
  41961. SimplificationQueue.prototype.addTask = function (task) {
  41962. this._simplificationArray.push(task);
  41963. };
  41964. SimplificationQueue.prototype.executeNext = function () {
  41965. var task = this._simplificationArray.pop();
  41966. if (task) {
  41967. this.running = true;
  41968. this.runSimplification(task);
  41969. }
  41970. else {
  41971. this.running = false;
  41972. }
  41973. };
  41974. SimplificationQueue.prototype.runSimplification = function (task) {
  41975. var _this = this;
  41976. if (task.parallelProcessing) {
  41977. //parallel simplifier
  41978. task.settings.forEach(function (setting) {
  41979. var simplifier = _this.getSimplifier(task);
  41980. simplifier.simplify(setting, function (newMesh) {
  41981. task.mesh.addLODLevel(setting.distance, newMesh);
  41982. newMesh.isVisible = true;
  41983. //check if it is the last
  41984. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  41985. //all done, run the success callback.
  41986. task.successCallback();
  41987. }
  41988. _this.executeNext();
  41989. });
  41990. });
  41991. }
  41992. else {
  41993. //single simplifier.
  41994. var simplifier = this.getSimplifier(task);
  41995. var runDecimation = function (setting, callback) {
  41996. simplifier.simplify(setting, function (newMesh) {
  41997. task.mesh.addLODLevel(setting.distance, newMesh);
  41998. newMesh.isVisible = true;
  41999. //run the next quality level
  42000. callback();
  42001. });
  42002. };
  42003. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  42004. runDecimation(task.settings[loop.index], function () {
  42005. loop.executeNext();
  42006. });
  42007. }, function () {
  42008. //execution ended, run the success callback.
  42009. if (task.successCallback) {
  42010. task.successCallback();
  42011. }
  42012. _this.executeNext();
  42013. });
  42014. }
  42015. };
  42016. SimplificationQueue.prototype.getSimplifier = function (task) {
  42017. switch (task.simplificationType) {
  42018. case SimplificationType.QUADRATIC:
  42019. default:
  42020. return new QuadraticErrorSimplification(task.mesh);
  42021. }
  42022. };
  42023. return SimplificationQueue;
  42024. }());
  42025. BABYLON.SimplificationQueue = SimplificationQueue;
  42026. /**
  42027. * The implemented types of simplification.
  42028. * At the moment only Quadratic Error Decimation is implemented.
  42029. */
  42030. var SimplificationType;
  42031. (function (SimplificationType) {
  42032. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  42033. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  42034. var DecimationTriangle = (function () {
  42035. function DecimationTriangle(vertices) {
  42036. this.vertices = vertices;
  42037. this.error = new Array(4);
  42038. this.deleted = false;
  42039. this.isDirty = false;
  42040. this.deletePending = false;
  42041. this.borderFactor = 0;
  42042. }
  42043. return DecimationTriangle;
  42044. }());
  42045. BABYLON.DecimationTriangle = DecimationTriangle;
  42046. var DecimationVertex = (function () {
  42047. function DecimationVertex(position, id) {
  42048. this.position = position;
  42049. this.id = id;
  42050. this.isBorder = true;
  42051. this.q = new QuadraticMatrix();
  42052. this.triangleCount = 0;
  42053. this.triangleStart = 0;
  42054. this.originalOffsets = [];
  42055. }
  42056. DecimationVertex.prototype.updatePosition = function (newPosition) {
  42057. this.position.copyFrom(newPosition);
  42058. };
  42059. return DecimationVertex;
  42060. }());
  42061. BABYLON.DecimationVertex = DecimationVertex;
  42062. var QuadraticMatrix = (function () {
  42063. function QuadraticMatrix(data) {
  42064. this.data = new Array(10);
  42065. for (var i = 0; i < 10; ++i) {
  42066. if (data && data[i]) {
  42067. this.data[i] = data[i];
  42068. }
  42069. else {
  42070. this.data[i] = 0;
  42071. }
  42072. }
  42073. }
  42074. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  42075. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  42076. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  42077. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  42078. return det;
  42079. };
  42080. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  42081. for (var i = 0; i < 10; ++i) {
  42082. this.data[i] += matrix.data[i];
  42083. }
  42084. };
  42085. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  42086. for (var i = 0; i < 10; ++i) {
  42087. this.data[i] += data[i];
  42088. }
  42089. };
  42090. QuadraticMatrix.prototype.add = function (matrix) {
  42091. var m = new QuadraticMatrix();
  42092. for (var i = 0; i < 10; ++i) {
  42093. m.data[i] = this.data[i] + matrix.data[i];
  42094. }
  42095. return m;
  42096. };
  42097. QuadraticMatrix.FromData = function (a, b, c, d) {
  42098. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  42099. };
  42100. //returning an array to avoid garbage collection
  42101. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  42102. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  42103. };
  42104. return QuadraticMatrix;
  42105. }());
  42106. BABYLON.QuadraticMatrix = QuadraticMatrix;
  42107. var Reference = (function () {
  42108. function Reference(vertexId, triangleId) {
  42109. this.vertexId = vertexId;
  42110. this.triangleId = triangleId;
  42111. }
  42112. return Reference;
  42113. }());
  42114. BABYLON.Reference = Reference;
  42115. /**
  42116. * An implementation of the Quadratic Error simplification algorithm.
  42117. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  42118. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  42119. * @author RaananW
  42120. */
  42121. var QuadraticErrorSimplification = (function () {
  42122. function QuadraticErrorSimplification(_mesh) {
  42123. this._mesh = _mesh;
  42124. this.initialized = false;
  42125. this.syncIterations = 5000;
  42126. this.aggressiveness = 7;
  42127. this.decimationIterations = 100;
  42128. this.boundingBoxEpsilon = BABYLON.Epsilon;
  42129. }
  42130. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  42131. var _this = this;
  42132. this.initDecimatedMesh();
  42133. //iterating through the submeshes array, one after the other.
  42134. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  42135. _this.initWithMesh(loop.index, function () {
  42136. _this.runDecimation(settings, loop.index, function () {
  42137. loop.executeNext();
  42138. });
  42139. }, settings.optimizeMesh);
  42140. }, function () {
  42141. setTimeout(function () {
  42142. successCallback(_this._reconstructedMesh);
  42143. }, 0);
  42144. });
  42145. };
  42146. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  42147. var _this = this;
  42148. var gCount = 0;
  42149. triangle.vertices.forEach(function (vertex) {
  42150. var count = 0;
  42151. var vPos = vertex.position;
  42152. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  42153. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  42154. ++count;
  42155. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  42156. ++count;
  42157. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  42158. ++count;
  42159. if (count > 1) {
  42160. ++gCount;
  42161. }
  42162. ;
  42163. });
  42164. if (gCount > 1) {
  42165. console.log(triangle, gCount);
  42166. }
  42167. return gCount > 1;
  42168. };
  42169. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  42170. var _this = this;
  42171. var targetCount = ~~(this.triangles.length * settings.quality);
  42172. var deletedTriangles = 0;
  42173. var triangleCount = this.triangles.length;
  42174. var iterationFunction = function (iteration, callback) {
  42175. setTimeout(function () {
  42176. if (iteration % 5 === 0) {
  42177. _this.updateMesh(iteration === 0);
  42178. }
  42179. for (var i = 0; i < _this.triangles.length; ++i) {
  42180. _this.triangles[i].isDirty = false;
  42181. }
  42182. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  42183. var trianglesIterator = function (i) {
  42184. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  42185. var t = _this.triangles[tIdx];
  42186. if (!t)
  42187. return;
  42188. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  42189. return;
  42190. }
  42191. for (var j = 0; j < 3; ++j) {
  42192. if (t.error[j] < threshold) {
  42193. var deleted0 = [];
  42194. var deleted1 = [];
  42195. var v0 = t.vertices[j];
  42196. var v1 = t.vertices[(j + 1) % 3];
  42197. if (v0.isBorder || v1.isBorder)
  42198. continue;
  42199. var p = BABYLON.Vector3.Zero();
  42200. var n = BABYLON.Vector3.Zero();
  42201. var uv = BABYLON.Vector2.Zero();
  42202. var color = new BABYLON.Color4(0, 0, 0, 1);
  42203. _this.calculateError(v0, v1, p, n, uv, color);
  42204. var delTr = [];
  42205. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  42206. continue;
  42207. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  42208. continue;
  42209. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  42210. continue;
  42211. var uniqueArray = [];
  42212. delTr.forEach(function (deletedT) {
  42213. if (uniqueArray.indexOf(deletedT) === -1) {
  42214. deletedT.deletePending = true;
  42215. uniqueArray.push(deletedT);
  42216. }
  42217. });
  42218. if (uniqueArray.length % 2 !== 0) {
  42219. continue;
  42220. }
  42221. v0.q = v1.q.add(v0.q);
  42222. v0.updatePosition(p);
  42223. var tStart = _this.references.length;
  42224. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  42225. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  42226. var tCount = _this.references.length - tStart;
  42227. if (tCount <= v0.triangleCount) {
  42228. if (tCount) {
  42229. for (var c = 0; c < tCount; c++) {
  42230. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  42231. }
  42232. }
  42233. }
  42234. else {
  42235. v0.triangleStart = tStart;
  42236. }
  42237. v0.triangleCount = tCount;
  42238. break;
  42239. }
  42240. }
  42241. };
  42242. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  42243. }, 0);
  42244. };
  42245. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  42246. if (triangleCount - deletedTriangles <= targetCount)
  42247. loop.breakLoop();
  42248. else {
  42249. iterationFunction(loop.index, function () {
  42250. loop.executeNext();
  42251. });
  42252. }
  42253. }, function () {
  42254. setTimeout(function () {
  42255. //reconstruct this part of the mesh
  42256. _this.reconstructMesh(submeshIndex);
  42257. successCallback();
  42258. }, 0);
  42259. });
  42260. };
  42261. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  42262. var _this = this;
  42263. this.vertices = [];
  42264. this.triangles = [];
  42265. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  42266. var indices = this._mesh.getIndices();
  42267. var submesh = this._mesh.subMeshes[submeshIndex];
  42268. var findInVertices = function (positionToSearch) {
  42269. if (optimizeMesh) {
  42270. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  42271. if (_this.vertices[ii].position.equals(positionToSearch)) {
  42272. return _this.vertices[ii];
  42273. }
  42274. }
  42275. }
  42276. return null;
  42277. };
  42278. var vertexReferences = [];
  42279. var vertexInit = function (i) {
  42280. var offset = i + submesh.verticesStart;
  42281. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  42282. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  42283. vertex.originalOffsets.push(offset);
  42284. if (vertex.id === _this.vertices.length) {
  42285. _this.vertices.push(vertex);
  42286. }
  42287. vertexReferences.push(vertex.id);
  42288. };
  42289. //var totalVertices = mesh.getTotalVertices();
  42290. var totalVertices = submesh.verticesCount;
  42291. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  42292. var indicesInit = function (i) {
  42293. var offset = (submesh.indexStart / 3) + i;
  42294. var pos = (offset * 3);
  42295. var i0 = indices[pos + 0];
  42296. var i1 = indices[pos + 1];
  42297. var i2 = indices[pos + 2];
  42298. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  42299. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  42300. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  42301. var triangle = new DecimationTriangle([v0, v1, v2]);
  42302. triangle.originalOffset = pos;
  42303. _this.triangles.push(triangle);
  42304. };
  42305. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  42306. _this.init(callback);
  42307. });
  42308. });
  42309. };
  42310. QuadraticErrorSimplification.prototype.init = function (callback) {
  42311. var _this = this;
  42312. var triangleInit1 = function (i) {
  42313. var t = _this.triangles[i];
  42314. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  42315. for (var j = 0; j < 3; j++) {
  42316. 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))));
  42317. }
  42318. };
  42319. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  42320. var triangleInit2 = function (i) {
  42321. var t = _this.triangles[i];
  42322. for (var j = 0; j < 3; ++j) {
  42323. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  42324. }
  42325. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42326. };
  42327. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  42328. _this.initialized = true;
  42329. callback();
  42330. });
  42331. });
  42332. };
  42333. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  42334. var newTriangles = [];
  42335. var i;
  42336. for (i = 0; i < this.vertices.length; ++i) {
  42337. this.vertices[i].triangleCount = 0;
  42338. }
  42339. var t;
  42340. var j;
  42341. for (i = 0; i < this.triangles.length; ++i) {
  42342. if (!this.triangles[i].deleted) {
  42343. t = this.triangles[i];
  42344. for (j = 0; j < 3; ++j) {
  42345. t.vertices[j].triangleCount = 1;
  42346. }
  42347. newTriangles.push(t);
  42348. }
  42349. }
  42350. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  42351. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  42352. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  42353. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  42354. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  42355. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  42356. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  42357. var vertexCount = 0;
  42358. for (i = 0; i < this.vertices.length; ++i) {
  42359. var vertex = this.vertices[i];
  42360. vertex.id = vertexCount;
  42361. if (vertex.triangleCount) {
  42362. vertex.originalOffsets.forEach(function (originalOffset) {
  42363. newPositionData.push(vertex.position.x);
  42364. newPositionData.push(vertex.position.y);
  42365. newPositionData.push(vertex.position.z);
  42366. newNormalData.push(normalData[originalOffset * 3]);
  42367. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  42368. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  42369. if (uvs && uvs.length) {
  42370. newUVsData.push(uvs[(originalOffset * 2)]);
  42371. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  42372. }
  42373. else if (colorsData && colorsData.length) {
  42374. newColorsData.push(colorsData[(originalOffset * 4)]);
  42375. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  42376. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  42377. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  42378. }
  42379. ++vertexCount;
  42380. });
  42381. }
  42382. }
  42383. var startingIndex = this._reconstructedMesh.getTotalIndices();
  42384. var startingVertex = this._reconstructedMesh.getTotalVertices();
  42385. var submeshesArray = this._reconstructedMesh.subMeshes;
  42386. this._reconstructedMesh.subMeshes = [];
  42387. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  42388. var originalIndices = this._mesh.getIndices();
  42389. for (i = 0; i < newTriangles.length; ++i) {
  42390. t = newTriangles[i]; //now get the new referencing point for each vertex
  42391. [0, 1, 2].forEach(function (idx) {
  42392. var id = originalIndices[t.originalOffset + idx];
  42393. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  42394. if (offset < 0)
  42395. offset = 0;
  42396. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  42397. });
  42398. }
  42399. //overwriting the old vertex buffers and indices.
  42400. this._reconstructedMesh.setIndices(newIndicesArray);
  42401. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  42402. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  42403. if (newUVsData.length > 0)
  42404. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  42405. if (newColorsData.length > 0)
  42406. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  42407. //create submesh
  42408. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  42409. if (submeshIndex > 0) {
  42410. this._reconstructedMesh.subMeshes = [];
  42411. submeshesArray.forEach(function (submesh) {
  42412. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  42413. });
  42414. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  42415. }
  42416. };
  42417. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  42418. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  42419. this._reconstructedMesh.material = this._mesh.material;
  42420. this._reconstructedMesh.parent = this._mesh.parent;
  42421. this._reconstructedMesh.isVisible = false;
  42422. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  42423. };
  42424. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  42425. for (var i = 0; i < vertex1.triangleCount; ++i) {
  42426. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  42427. if (t.deleted)
  42428. continue;
  42429. var s = this.references[vertex1.triangleStart + i].vertexId;
  42430. var v1 = t.vertices[(s + 1) % 3];
  42431. var v2 = t.vertices[(s + 2) % 3];
  42432. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  42433. deletedArray[i] = true;
  42434. delTr.push(t);
  42435. continue;
  42436. }
  42437. var d1 = v1.position.subtract(point);
  42438. d1 = d1.normalize();
  42439. var d2 = v2.position.subtract(point);
  42440. d2 = d2.normalize();
  42441. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  42442. return true;
  42443. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  42444. deletedArray[i] = false;
  42445. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  42446. return true;
  42447. }
  42448. return false;
  42449. };
  42450. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  42451. var newDeleted = deletedTriangles;
  42452. for (var i = 0; i < vertex.triangleCount; ++i) {
  42453. var ref = this.references[vertex.triangleStart + i];
  42454. var t = this.triangles[ref.triangleId];
  42455. if (t.deleted)
  42456. continue;
  42457. if (deletedArray[i] && t.deletePending) {
  42458. t.deleted = true;
  42459. newDeleted++;
  42460. continue;
  42461. }
  42462. t.vertices[ref.vertexId] = origVertex;
  42463. t.isDirty = true;
  42464. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  42465. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  42466. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  42467. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  42468. this.references.push(ref);
  42469. }
  42470. return newDeleted;
  42471. };
  42472. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  42473. for (var i = 0; i < this.vertices.length; ++i) {
  42474. var vCount = [];
  42475. var vId = [];
  42476. var v = this.vertices[i];
  42477. var j;
  42478. for (j = 0; j < v.triangleCount; ++j) {
  42479. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  42480. for (var ii = 0; ii < 3; ii++) {
  42481. var ofs = 0;
  42482. var vv = triangle.vertices[ii];
  42483. while (ofs < vCount.length) {
  42484. if (vId[ofs] === vv.id)
  42485. break;
  42486. ++ofs;
  42487. }
  42488. if (ofs === vCount.length) {
  42489. vCount.push(1);
  42490. vId.push(vv.id);
  42491. }
  42492. else {
  42493. vCount[ofs]++;
  42494. }
  42495. }
  42496. }
  42497. for (j = 0; j < vCount.length; ++j) {
  42498. if (vCount[j] === 1) {
  42499. this.vertices[vId[j]].isBorder = true;
  42500. }
  42501. else {
  42502. this.vertices[vId[j]].isBorder = false;
  42503. }
  42504. }
  42505. }
  42506. };
  42507. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  42508. if (identifyBorders === void 0) { identifyBorders = false; }
  42509. var i;
  42510. if (!identifyBorders) {
  42511. var newTrianglesVector = [];
  42512. for (i = 0; i < this.triangles.length; ++i) {
  42513. if (!this.triangles[i].deleted) {
  42514. newTrianglesVector.push(this.triangles[i]);
  42515. }
  42516. }
  42517. this.triangles = newTrianglesVector;
  42518. }
  42519. for (i = 0; i < this.vertices.length; ++i) {
  42520. this.vertices[i].triangleCount = 0;
  42521. this.vertices[i].triangleStart = 0;
  42522. }
  42523. var t;
  42524. var j;
  42525. var v;
  42526. for (i = 0; i < this.triangles.length; ++i) {
  42527. t = this.triangles[i];
  42528. for (j = 0; j < 3; ++j) {
  42529. v = t.vertices[j];
  42530. v.triangleCount++;
  42531. }
  42532. }
  42533. var tStart = 0;
  42534. for (i = 0; i < this.vertices.length; ++i) {
  42535. this.vertices[i].triangleStart = tStart;
  42536. tStart += this.vertices[i].triangleCount;
  42537. this.vertices[i].triangleCount = 0;
  42538. }
  42539. var newReferences = new Array(this.triangles.length * 3);
  42540. for (i = 0; i < this.triangles.length; ++i) {
  42541. t = this.triangles[i];
  42542. for (j = 0; j < 3; ++j) {
  42543. v = t.vertices[j];
  42544. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  42545. v.triangleCount++;
  42546. }
  42547. }
  42548. this.references = newReferences;
  42549. if (identifyBorders) {
  42550. this.identifyBorder();
  42551. }
  42552. };
  42553. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  42554. var x = point.x;
  42555. var y = point.y;
  42556. var z = point.z;
  42557. 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
  42558. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  42559. };
  42560. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  42561. var q = vertex1.q.add(vertex2.q);
  42562. var border = vertex1.isBorder && vertex2.isBorder;
  42563. var error = 0;
  42564. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  42565. if (qDet !== 0 && !border) {
  42566. if (!pointResult) {
  42567. pointResult = BABYLON.Vector3.Zero();
  42568. }
  42569. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  42570. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  42571. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  42572. error = this.vertexError(q, pointResult);
  42573. }
  42574. else {
  42575. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  42576. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  42577. var error1 = this.vertexError(q, vertex1.position);
  42578. var error2 = this.vertexError(q, vertex2.position);
  42579. var error3 = this.vertexError(q, p3);
  42580. error = Math.min(error1, error2, error3);
  42581. if (error === error1) {
  42582. if (pointResult) {
  42583. pointResult.copyFrom(vertex1.position);
  42584. }
  42585. }
  42586. else if (error === error2) {
  42587. if (pointResult) {
  42588. pointResult.copyFrom(vertex2.position);
  42589. }
  42590. }
  42591. else {
  42592. if (pointResult) {
  42593. pointResult.copyFrom(p3);
  42594. }
  42595. }
  42596. }
  42597. return error;
  42598. };
  42599. return QuadraticErrorSimplification;
  42600. }());
  42601. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  42602. })(BABYLON || (BABYLON = {}));
  42603. //# sourceMappingURL=babylon.meshSimplification.js.map
  42604. var BABYLON;
  42605. (function (BABYLON) {
  42606. var serializedGeometries = [];
  42607. var serializeGeometry = function (geometry, serializationGeometries) {
  42608. if (serializedGeometries[geometry.id]) {
  42609. return;
  42610. }
  42611. if (geometry.doNotSerialize) {
  42612. return;
  42613. }
  42614. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  42615. serializationGeometries.boxes.push(geometry.serialize());
  42616. }
  42617. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  42618. serializationGeometries.spheres.push(geometry.serialize());
  42619. }
  42620. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  42621. serializationGeometries.cylinders.push(geometry.serialize());
  42622. }
  42623. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  42624. serializationGeometries.toruses.push(geometry.serialize());
  42625. }
  42626. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  42627. serializationGeometries.grounds.push(geometry.serialize());
  42628. }
  42629. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  42630. serializationGeometries.planes.push(geometry.serialize());
  42631. }
  42632. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  42633. serializationGeometries.torusKnots.push(geometry.serialize());
  42634. }
  42635. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  42636. throw new Error("Unknown primitive type");
  42637. }
  42638. else {
  42639. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  42640. }
  42641. serializedGeometries[geometry.id] = true;
  42642. };
  42643. var serializeMesh = function (mesh, serializationScene) {
  42644. var serializationObject = {};
  42645. serializationObject.name = mesh.name;
  42646. serializationObject.id = mesh.id;
  42647. if (BABYLON.Tags.HasTags(mesh)) {
  42648. serializationObject.tags = BABYLON.Tags.GetTags(mesh);
  42649. }
  42650. serializationObject.position = mesh.position.asArray();
  42651. if (mesh.rotationQuaternion) {
  42652. serializationObject.rotationQuaternion = mesh.rotationQuaternion.asArray();
  42653. }
  42654. else if (mesh.rotation) {
  42655. serializationObject.rotation = mesh.rotation.asArray();
  42656. }
  42657. serializationObject.scaling = mesh.scaling.asArray();
  42658. serializationObject.localMatrix = mesh.getPivotMatrix().asArray();
  42659. serializationObject.isEnabled = mesh.isEnabled();
  42660. serializationObject.isVisible = mesh.isVisible;
  42661. serializationObject.infiniteDistance = mesh.infiniteDistance;
  42662. serializationObject.pickable = mesh.isPickable;
  42663. serializationObject.receiveShadows = mesh.receiveShadows;
  42664. serializationObject.billboardMode = mesh.billboardMode;
  42665. serializationObject.visibility = mesh.visibility;
  42666. serializationObject.checkCollisions = mesh.checkCollisions;
  42667. serializationObject.isBlocker = mesh.isBlocker;
  42668. // Parent
  42669. if (mesh.parent) {
  42670. serializationObject.parentId = mesh.parent.id;
  42671. }
  42672. // Geometry
  42673. var geometry = mesh._geometry;
  42674. if (geometry) {
  42675. var geometryId = geometry.id;
  42676. serializationObject.geometryId = geometryId;
  42677. if (!mesh.getScene().getGeometryByID(geometryId)) {
  42678. // 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
  42679. serializeGeometry(geometry, serializationScene.geometries);
  42680. }
  42681. // SubMeshes
  42682. serializationObject.subMeshes = [];
  42683. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  42684. var subMesh = mesh.subMeshes[subIndex];
  42685. serializationObject.subMeshes.push({
  42686. materialIndex: subMesh.materialIndex,
  42687. verticesStart: subMesh.verticesStart,
  42688. verticesCount: subMesh.verticesCount,
  42689. indexStart: subMesh.indexStart,
  42690. indexCount: subMesh.indexCount
  42691. });
  42692. }
  42693. }
  42694. // Material
  42695. if (mesh.material) {
  42696. serializationObject.materialId = mesh.material.id;
  42697. }
  42698. else {
  42699. mesh.material = null;
  42700. }
  42701. // Skeleton
  42702. if (mesh.skeleton) {
  42703. serializationObject.skeletonId = mesh.skeleton.id;
  42704. }
  42705. // Physics
  42706. //TODO implement correct serialization for physics impostors.
  42707. if (mesh.getPhysicsImpostor()) {
  42708. serializationObject.physicsMass = mesh.getPhysicsMass();
  42709. serializationObject.physicsFriction = mesh.getPhysicsFriction();
  42710. serializationObject.physicsRestitution = mesh.getPhysicsRestitution();
  42711. serializationObject.physicsImpostor = mesh.getPhysicsImpostor().type;
  42712. }
  42713. // Metadata
  42714. if (mesh.metadata) {
  42715. serializationObject.metadata = mesh.metadata;
  42716. }
  42717. // Instances
  42718. serializationObject.instances = [];
  42719. for (var index = 0; index < mesh.instances.length; index++) {
  42720. var instance = mesh.instances[index];
  42721. var serializationInstance = {
  42722. name: instance.name,
  42723. position: instance.position.asArray(),
  42724. scaling: instance.scaling.asArray()
  42725. };
  42726. if (instance.rotationQuaternion) {
  42727. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  42728. }
  42729. else if (instance.rotation) {
  42730. serializationInstance.rotation = instance.rotation.asArray();
  42731. }
  42732. serializationObject.instances.push(serializationInstance);
  42733. // Animations
  42734. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  42735. serializationInstance.ranges = instance.serializeAnimationRanges();
  42736. }
  42737. // Animations
  42738. BABYLON.Animation.AppendSerializedAnimations(mesh, serializationObject);
  42739. serializationObject.ranges = mesh.serializeAnimationRanges();
  42740. // Layer mask
  42741. serializationObject.layerMask = mesh.layerMask;
  42742. // Alpha
  42743. serializationObject.alphaIndex = mesh.alphaIndex;
  42744. serializationObject.hasVertexAlpha = mesh.hasVertexAlpha;
  42745. // Overlay
  42746. serializationObject.overlayAlpha = mesh.overlayAlpha;
  42747. serializationObject.overlayColor = mesh.overlayColor.asArray();
  42748. serializationObject.renderOverlay = mesh.renderOverlay;
  42749. // Fog
  42750. serializationObject.applyFog = mesh.applyFog;
  42751. // Action Manager
  42752. if (mesh.actionManager) {
  42753. serializationObject.actions = mesh.actionManager.serialize(mesh.name);
  42754. }
  42755. return serializationObject;
  42756. };
  42757. var finalizeSingleMesh = function (mesh, serializationObject) {
  42758. //only works if the mesh is already loaded
  42759. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42760. //serialize material
  42761. if (mesh.material) {
  42762. if (mesh.material instanceof BABYLON.StandardMaterial) {
  42763. serializationObject.materials = serializationObject.materials || [];
  42764. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42765. serializationObject.materials.push(mesh.material.serialize());
  42766. }
  42767. }
  42768. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  42769. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  42770. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  42771. serializationObject.multiMaterials.push(mesh.material.serialize());
  42772. }
  42773. }
  42774. }
  42775. //serialize geometry
  42776. var geometry = mesh._geometry;
  42777. if (geometry) {
  42778. if (!serializationObject.geometries) {
  42779. serializationObject.geometries = {};
  42780. serializationObject.geometries.boxes = [];
  42781. serializationObject.geometries.spheres = [];
  42782. serializationObject.geometries.cylinders = [];
  42783. serializationObject.geometries.toruses = [];
  42784. serializationObject.geometries.grounds = [];
  42785. serializationObject.geometries.planes = [];
  42786. serializationObject.geometries.torusKnots = [];
  42787. serializationObject.geometries.vertexData = [];
  42788. }
  42789. serializeGeometry(geometry, serializationObject.geometries);
  42790. }
  42791. // Skeletons
  42792. if (mesh.skeleton) {
  42793. serializationObject.skeletons = serializationObject.skeletons || [];
  42794. serializationObject.skeletons.push(mesh.skeleton.serialize());
  42795. }
  42796. //serialize the actual mesh
  42797. serializationObject.meshes = serializationObject.meshes || [];
  42798. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42799. }
  42800. };
  42801. var SceneSerializer = (function () {
  42802. function SceneSerializer() {
  42803. }
  42804. SceneSerializer.ClearCache = function () {
  42805. serializedGeometries = [];
  42806. };
  42807. SceneSerializer.Serialize = function (scene) {
  42808. var serializationObject = {};
  42809. // Scene
  42810. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  42811. serializationObject.autoClear = scene.autoClear;
  42812. serializationObject.clearColor = scene.clearColor.asArray();
  42813. serializationObject.ambientColor = scene.ambientColor.asArray();
  42814. serializationObject.gravity = scene.gravity.asArray();
  42815. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  42816. serializationObject.workerCollisions = scene.workerCollisions;
  42817. // Fog
  42818. if (scene.fogMode && scene.fogMode !== 0) {
  42819. serializationObject.fogMode = scene.fogMode;
  42820. serializationObject.fogColor = scene.fogColor.asArray();
  42821. serializationObject.fogStart = scene.fogStart;
  42822. serializationObject.fogEnd = scene.fogEnd;
  42823. serializationObject.fogDensity = scene.fogDensity;
  42824. }
  42825. //Physics
  42826. if (scene.isPhysicsEnabled()) {
  42827. serializationObject.physicsEnabled = true;
  42828. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  42829. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  42830. }
  42831. // Metadata
  42832. if (scene.metadata) {
  42833. serializationObject.metadata = scene.metadata;
  42834. }
  42835. // Lights
  42836. serializationObject.lights = [];
  42837. var index;
  42838. var light;
  42839. for (index = 0; index < scene.lights.length; index++) {
  42840. light = scene.lights[index];
  42841. if (!light.doNotSerialize) {
  42842. serializationObject.lights.push(light.serialize());
  42843. }
  42844. }
  42845. // Cameras
  42846. serializationObject.cameras = [];
  42847. for (index = 0; index < scene.cameras.length; index++) {
  42848. var camera = scene.cameras[index];
  42849. if (!camera.doNotSerialize) {
  42850. serializationObject.cameras.push(camera.serialize());
  42851. }
  42852. }
  42853. if (scene.activeCamera) {
  42854. serializationObject.activeCameraID = scene.activeCamera.id;
  42855. }
  42856. // Animations
  42857. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  42858. // Materials
  42859. serializationObject.materials = [];
  42860. serializationObject.multiMaterials = [];
  42861. var material;
  42862. for (index = 0; index < scene.materials.length; index++) {
  42863. material = scene.materials[index];
  42864. if (!material.doNotSerialize) {
  42865. serializationObject.materials.push(material.serialize());
  42866. }
  42867. }
  42868. // MultiMaterials
  42869. serializationObject.multiMaterials = [];
  42870. for (index = 0; index < scene.multiMaterials.length; index++) {
  42871. var multiMaterial = scene.multiMaterials[index];
  42872. serializationObject.multiMaterials.push(multiMaterial.serialize());
  42873. }
  42874. // Skeletons
  42875. serializationObject.skeletons = [];
  42876. for (index = 0; index < scene.skeletons.length; index++) {
  42877. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  42878. }
  42879. // Geometries
  42880. serializationObject.geometries = {};
  42881. serializationObject.geometries.boxes = [];
  42882. serializationObject.geometries.spheres = [];
  42883. serializationObject.geometries.cylinders = [];
  42884. serializationObject.geometries.toruses = [];
  42885. serializationObject.geometries.grounds = [];
  42886. serializationObject.geometries.planes = [];
  42887. serializationObject.geometries.torusKnots = [];
  42888. serializationObject.geometries.vertexData = [];
  42889. serializedGeometries = [];
  42890. var geometries = scene.getGeometries();
  42891. for (index = 0; index < geometries.length; index++) {
  42892. var geometry = geometries[index];
  42893. if (geometry.isReady()) {
  42894. serializeGeometry(geometry, serializationObject.geometries);
  42895. }
  42896. }
  42897. // Meshes
  42898. serializationObject.meshes = [];
  42899. for (index = 0; index < scene.meshes.length; index++) {
  42900. var abstractMesh = scene.meshes[index];
  42901. if (abstractMesh instanceof BABYLON.Mesh) {
  42902. var mesh = abstractMesh;
  42903. if (!mesh.doNotSerialize) {
  42904. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  42905. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  42906. }
  42907. }
  42908. }
  42909. }
  42910. // Particles Systems
  42911. serializationObject.particleSystems = [];
  42912. for (index = 0; index < scene.particleSystems.length; index++) {
  42913. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  42914. }
  42915. // Lens flares
  42916. serializationObject.lensFlareSystems = [];
  42917. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  42918. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  42919. }
  42920. // Shadows
  42921. serializationObject.shadowGenerators = [];
  42922. for (index = 0; index < scene.lights.length; index++) {
  42923. light = scene.lights[index];
  42924. var shadowGenerator = light.getShadowGenerator();
  42925. // Only support serialization for official generator so far.
  42926. if (shadowGenerator && shadowGenerator instanceof BABYLON.ShadowGenerator) {
  42927. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  42928. }
  42929. }
  42930. // Action Manager
  42931. if (scene.actionManager) {
  42932. serializationObject.actions = scene.actionManager.serialize("scene");
  42933. }
  42934. // Audio
  42935. serializationObject.sounds = [];
  42936. for (index = 0; index < scene.soundTracks.length; index++) {
  42937. var soundtrack = scene.soundTracks[index];
  42938. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  42939. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  42940. }
  42941. }
  42942. return serializationObject;
  42943. };
  42944. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  42945. if (withParents === void 0) { withParents = false; }
  42946. if (withChildren === void 0) { withChildren = false; }
  42947. var serializationObject = {};
  42948. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  42949. if (withParents || withChildren) {
  42950. //deliberate for loop! not for each, appended should be processed as well.
  42951. for (var i = 0; i < toSerialize.length; ++i) {
  42952. if (withChildren) {
  42953. toSerialize[i].getDescendants().forEach(function (node) {
  42954. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  42955. toSerialize.push(node);
  42956. }
  42957. });
  42958. }
  42959. //make sure the array doesn't contain the object already
  42960. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  42961. toSerialize.push(toSerialize[i].parent);
  42962. }
  42963. }
  42964. }
  42965. toSerialize.forEach(function (mesh) {
  42966. finalizeSingleMesh(mesh, serializationObject);
  42967. });
  42968. return serializationObject;
  42969. };
  42970. return SceneSerializer;
  42971. }());
  42972. BABYLON.SceneSerializer = SceneSerializer;
  42973. })(BABYLON || (BABYLON = {}));
  42974. //# sourceMappingURL=babylon.sceneSerializer.js.map
  42975. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  42976. // Huge respect for a such great lib.
  42977. // Earcut license:
  42978. // Copyright (c) 2016, Mapbox
  42979. //
  42980. // Permission to use, copy, modify, and/or distribute this software for any purpose
  42981. // with or without fee is hereby granted, provided that the above copyright notice
  42982. // and this permission notice appear in all copies.
  42983. //
  42984. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  42985. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  42986. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  42987. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  42988. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  42989. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  42990. // THIS SOFTWARE.
  42991. var Earcut;
  42992. (function (Earcut) {
  42993. /**
  42994. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  42995. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  42996. * @param holeIndices is an array of hole indices if any (e.g. [5, 8] for a 12- vertice input would mean one hole with vertices 5–7 and another with 8–11).
  42997. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  42998. */
  42999. function earcut(data, holeIndices, dim) {
  43000. dim = dim || 2;
  43001. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  43002. if (!outerNode)
  43003. return triangles;
  43004. var minX, minY, maxX, maxY, x, y, size;
  43005. if (hasHoles)
  43006. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  43007. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  43008. if (data.length > 80 * dim) {
  43009. minX = maxX = data[0];
  43010. minY = maxY = data[1];
  43011. for (var i = dim; i < outerLen; i += dim) {
  43012. x = data[i];
  43013. y = data[i + 1];
  43014. if (x < minX)
  43015. minX = x;
  43016. if (y < minY)
  43017. minY = y;
  43018. if (x > maxX)
  43019. maxX = x;
  43020. if (y > maxY)
  43021. maxY = y;
  43022. }
  43023. // minX, minY and size are later used to transform coords into integers for z-order calculation
  43024. size = Math.max(maxX - minX, maxY - minY);
  43025. }
  43026. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  43027. return triangles;
  43028. }
  43029. Earcut.earcut = earcut;
  43030. // create a circular doubly linked list from polygon points in the specified winding order
  43031. function linkedList(data, start, end, dim, clockwise) {
  43032. var i, last;
  43033. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  43034. for (i = start; i < end; i += dim)
  43035. last = insertNode(i, data[i], data[i + 1], last);
  43036. }
  43037. else {
  43038. for (i = end - dim; i >= start; i -= dim)
  43039. last = insertNode(i, data[i], data[i + 1], last);
  43040. }
  43041. if (last && equals(last, last.next)) {
  43042. removeNode(last);
  43043. last = last.next;
  43044. }
  43045. return last;
  43046. }
  43047. // eliminate colinear or duplicate points
  43048. function filterPoints(start, end) {
  43049. if (!start)
  43050. return start;
  43051. if (!end)
  43052. end = start;
  43053. var p = start, again;
  43054. do {
  43055. again = false;
  43056. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  43057. removeNode(p);
  43058. p = end = p.prev;
  43059. if (p === p.next)
  43060. return null;
  43061. again = true;
  43062. }
  43063. else {
  43064. p = p.next;
  43065. }
  43066. } while (again || p !== end);
  43067. return end;
  43068. }
  43069. // main ear slicing loop which triangulates a polygon (given as a linked list)
  43070. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  43071. if (!ear)
  43072. return;
  43073. // interlink polygon nodes in z-order
  43074. if (!pass && size)
  43075. indexCurve(ear, minX, minY, size);
  43076. var stop = ear, prev, next;
  43077. // iterate through ears, slicing them one by one
  43078. while (ear.prev !== ear.next) {
  43079. prev = ear.prev;
  43080. next = ear.next;
  43081. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  43082. // cut off the triangle
  43083. triangles.push(prev.i / dim);
  43084. triangles.push(ear.i / dim);
  43085. triangles.push(next.i / dim);
  43086. removeNode(ear);
  43087. // skipping the next vertice leads to less sliver triangles
  43088. ear = next.next;
  43089. stop = next.next;
  43090. continue;
  43091. }
  43092. ear = next;
  43093. // if we looped through the whole remaining polygon and can't find any more ears
  43094. if (ear === stop) {
  43095. // try filtering points and slicing again
  43096. if (!pass) {
  43097. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  43098. }
  43099. else if (pass === 1) {
  43100. ear = cureLocalIntersections(ear, triangles, dim);
  43101. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  43102. }
  43103. else if (pass === 2) {
  43104. splitEarcut(ear, triangles, dim, minX, minY, size);
  43105. }
  43106. break;
  43107. }
  43108. }
  43109. }
  43110. // check whether a polygon node forms a valid ear with adjacent nodes
  43111. function isEar(ear) {
  43112. var a = ear.prev, b = ear, c = ear.next;
  43113. if (area(a, b, c) >= 0)
  43114. return false; // reflex, can't be an ear
  43115. // now make sure we don't have other points inside the potential ear
  43116. var p = ear.next.next;
  43117. while (p !== ear.prev) {
  43118. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43119. area(p.prev, p, p.next) >= 0)
  43120. return false;
  43121. p = p.next;
  43122. }
  43123. return true;
  43124. }
  43125. function isEarHashed(ear, minX, minY, size) {
  43126. var a = ear.prev, b = ear, c = ear.next;
  43127. if (area(a, b, c) >= 0)
  43128. return false; // reflex, can't be an ear
  43129. // triangle bbox; min & max are calculated like this for speed
  43130. var minTX = a.x < b.x ? (a.x < c.x ? a.x : c.x) : (b.x < c.x ? b.x : c.x), minTY = a.y < b.y ? (a.y < c.y ? a.y : c.y) : (b.y < c.y ? b.y : c.y), maxTX = a.x > b.x ? (a.x > c.x ? a.x : c.x) : (b.x > c.x ? b.x : c.x), maxTY = a.y > b.y ? (a.y > c.y ? a.y : c.y) : (b.y > c.y ? b.y : c.y);
  43131. // z-order range for the current triangle bbox;
  43132. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  43133. // first look for points inside the triangle in increasing z-order
  43134. var p = ear.nextZ;
  43135. while (p && p.z <= maxZ) {
  43136. if (p !== ear.prev &&
  43137. p !== ear.next &&
  43138. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43139. area(p.prev, p, p.next) >= 0)
  43140. return false;
  43141. p = p.nextZ;
  43142. }
  43143. // then look for points in decreasing z-order
  43144. p = ear.prevZ;
  43145. while (p && p.z >= minZ) {
  43146. if (p !== ear.prev &&
  43147. p !== ear.next &&
  43148. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  43149. area(p.prev, p, p.next) >= 0)
  43150. return false;
  43151. p = p.prevZ;
  43152. }
  43153. return true;
  43154. }
  43155. // go through all polygon nodes and cure small local self-intersections
  43156. function cureLocalIntersections(start, triangles, dim) {
  43157. var p = start;
  43158. do {
  43159. var a = p.prev, b = p.next.next;
  43160. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  43161. triangles.push(a.i / dim);
  43162. triangles.push(p.i / dim);
  43163. triangles.push(b.i / dim);
  43164. // remove two nodes involved
  43165. removeNode(p);
  43166. removeNode(p.next);
  43167. p = start = b;
  43168. }
  43169. p = p.next;
  43170. } while (p !== start);
  43171. return p;
  43172. }
  43173. // try splitting polygon into two and triangulate them independently
  43174. function splitEarcut(start, triangles, dim, minX, minY, size) {
  43175. // look for a valid diagonal that divides the polygon into two
  43176. var a = start;
  43177. do {
  43178. var b = a.next.next;
  43179. while (b !== a.prev) {
  43180. if (a.i !== b.i && isValidDiagonal(a, b)) {
  43181. // split the polygon in two by the diagonal
  43182. var c = splitPolygon(a, b);
  43183. // filter colinear points around the cuts
  43184. a = filterPoints(a, a.next);
  43185. c = filterPoints(c, c.next);
  43186. // run earcut on each half
  43187. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  43188. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  43189. return;
  43190. }
  43191. b = b.next;
  43192. }
  43193. a = a.next;
  43194. } while (a !== start);
  43195. }
  43196. // link every hole into the outer loop, producing a single-ring polygon without holes
  43197. function eliminateHoles(data, holeIndices, outerNode, dim) {
  43198. var queue = [], i, len, start, end, list;
  43199. for (i = 0, len = holeIndices.length; i < len; i++) {
  43200. start = holeIndices[i] * dim;
  43201. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43202. list = linkedList(data, start, end, dim, false);
  43203. if (list === list.next)
  43204. list.steiner = true;
  43205. queue.push(getLeftmost(list));
  43206. }
  43207. queue.sort(compareX);
  43208. // process holes from left to right
  43209. for (i = 0; i < queue.length; i++) {
  43210. eliminateHole(queue[i], outerNode);
  43211. outerNode = filterPoints(outerNode, outerNode.next);
  43212. }
  43213. return outerNode;
  43214. }
  43215. function compareX(a, b) {
  43216. return a.x - b.x;
  43217. }
  43218. // find a bridge between vertices that connects hole with an outer ring and and link it
  43219. function eliminateHole(hole, outerNode) {
  43220. outerNode = findHoleBridge(hole, outerNode);
  43221. if (outerNode) {
  43222. var b = splitPolygon(outerNode, hole);
  43223. filterPoints(b, b.next);
  43224. }
  43225. }
  43226. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  43227. function findHoleBridge(hole, outerNode) {
  43228. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  43229. // find a segment intersected by a ray from the hole's leftmost point to the left;
  43230. // segment's endpoint with lesser x will be potential connection point
  43231. do {
  43232. if (hy <= p.y && hy >= p.next.y) {
  43233. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  43234. if (x <= hx && x > qx) {
  43235. qx = x;
  43236. if (x === hx) {
  43237. if (hy === p.y)
  43238. return p;
  43239. if (hy === p.next.y)
  43240. return p.next;
  43241. }
  43242. m = p.x < p.next.x ? p : p.next;
  43243. }
  43244. }
  43245. p = p.next;
  43246. } while (p !== outerNode);
  43247. if (!m)
  43248. return null;
  43249. if (hx === qx)
  43250. return m.prev; // hole touches outer segment; pick lower endpoint
  43251. // look for points inside the triangle of hole point, segment intersection and endpoint;
  43252. // if there are no points found, we have a valid connection;
  43253. // otherwise choose the point of the minimum angle with the ray as connection point
  43254. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  43255. p = m.next;
  43256. while (p !== stop) {
  43257. if (hx >= p.x &&
  43258. p.x >= mx &&
  43259. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  43260. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  43261. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  43262. m = p;
  43263. tanMin = tan;
  43264. }
  43265. }
  43266. p = p.next;
  43267. }
  43268. return m;
  43269. }
  43270. // interlink polygon nodes in z-order
  43271. function indexCurve(start, minX, minY, size) {
  43272. var p = start;
  43273. do {
  43274. if (p.z === null)
  43275. p.z = zOrder(p.x, p.y, minX, minY, size);
  43276. p.prevZ = p.prev;
  43277. p.nextZ = p.next;
  43278. p = p.next;
  43279. } while (p !== start);
  43280. p.prevZ.nextZ = null;
  43281. p.prevZ = null;
  43282. sortLinked(p);
  43283. }
  43284. // Simon Tatham's linked list merge sort algorithm
  43285. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  43286. function sortLinked(list) {
  43287. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  43288. do {
  43289. p = list;
  43290. list = null;
  43291. tail = null;
  43292. numMerges = 0;
  43293. while (p) {
  43294. numMerges++;
  43295. q = p;
  43296. pSize = 0;
  43297. for (i = 0; i < inSize; i++) {
  43298. pSize++;
  43299. q = q.nextZ;
  43300. if (!q)
  43301. break;
  43302. }
  43303. qSize = inSize;
  43304. while (pSize > 0 || (qSize > 0 && q)) {
  43305. if (pSize === 0) {
  43306. e = q;
  43307. q = q.nextZ;
  43308. qSize--;
  43309. }
  43310. else if (qSize === 0 || !q) {
  43311. e = p;
  43312. p = p.nextZ;
  43313. pSize--;
  43314. }
  43315. else if (p.z <= q.z) {
  43316. e = p;
  43317. p = p.nextZ;
  43318. pSize--;
  43319. }
  43320. else {
  43321. e = q;
  43322. q = q.nextZ;
  43323. qSize--;
  43324. }
  43325. if (tail)
  43326. tail.nextZ = e;
  43327. else
  43328. list = e;
  43329. e.prevZ = tail;
  43330. tail = e;
  43331. }
  43332. p = q;
  43333. }
  43334. tail.nextZ = null;
  43335. inSize *= 2;
  43336. } while (numMerges > 1);
  43337. return list;
  43338. }
  43339. // z-order of a point given coords and size of the data bounding box
  43340. function zOrder(x, y, minX, minY, size) {
  43341. // coords are transformed into non-negative 15-bit integer range
  43342. x = 32767 * (x - minX) / size;
  43343. y = 32767 * (y - minY) / size;
  43344. x = (x | (x << 8)) & 0x00FF00FF;
  43345. x = (x | (x << 4)) & 0x0F0F0F0F;
  43346. x = (x | (x << 2)) & 0x33333333;
  43347. x = (x | (x << 1)) & 0x55555555;
  43348. y = (y | (y << 8)) & 0x00FF00FF;
  43349. y = (y | (y << 4)) & 0x0F0F0F0F;
  43350. y = (y | (y << 2)) & 0x33333333;
  43351. y = (y | (y << 1)) & 0x55555555;
  43352. return x | (y << 1);
  43353. }
  43354. // find the leftmost node of a polygon ring
  43355. function getLeftmost(start) {
  43356. var p = start, leftmost = start;
  43357. do {
  43358. if (p.x < leftmost.x)
  43359. leftmost = p;
  43360. p = p.next;
  43361. } while (p !== start);
  43362. return leftmost;
  43363. }
  43364. // check if a point lies within a convex triangle
  43365. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  43366. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  43367. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  43368. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  43369. }
  43370. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  43371. function isValidDiagonal(a, b) {
  43372. return a.next.i !== b.i &&
  43373. a.prev.i !== b.i &&
  43374. !intersectsPolygon(a, b) &&
  43375. locallyInside(a, b) &&
  43376. locallyInside(b, a) &&
  43377. middleInside(a, b);
  43378. }
  43379. // signed area of a triangle
  43380. function area(p, q, r) {
  43381. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  43382. }
  43383. // check if two points are equal
  43384. function equals(p1, p2) {
  43385. return p1.x === p2.x && p1.y === p2.y;
  43386. }
  43387. // check if two segments intersect
  43388. function intersects(p1, q1, p2, q2) {
  43389. if ((equals(p1, q1) && equals(p2, q2)) ||
  43390. (equals(p1, q2) && equals(p2, q1)))
  43391. return true;
  43392. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  43393. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  43394. }
  43395. // check if a polygon diagonal intersects any polygon segments
  43396. function intersectsPolygon(a, b) {
  43397. var p = a;
  43398. do {
  43399. if (p.i !== a.i &&
  43400. p.next.i !== a.i &&
  43401. p.i !== b.i &&
  43402. p.next.i !== b.i &&
  43403. intersects(p, p.next, a, b))
  43404. return true;
  43405. p = p.next;
  43406. } while (p !== a);
  43407. return false;
  43408. }
  43409. // check if a polygon diagonal is locally inside the polygon
  43410. function locallyInside(a, b) {
  43411. return area(a.prev, a, a.next) < 0
  43412. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  43413. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  43414. }
  43415. // check if the middle point of a polygon diagonal is inside the polygon
  43416. function middleInside(a, b) {
  43417. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  43418. do {
  43419. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  43420. inside = !inside;
  43421. p = p.next;
  43422. } while (p !== a);
  43423. return inside;
  43424. }
  43425. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  43426. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  43427. function splitPolygon(a, b) {
  43428. var a2 = new Node(a.i, a.x, a.y), b2 = new Node(b.i, b.x, b.y), an = a.next, bp = b.prev;
  43429. a.next = b;
  43430. b.prev = a;
  43431. a2.next = an;
  43432. an.prev = a2;
  43433. b2.next = a2;
  43434. a2.prev = b2;
  43435. bp.next = b2;
  43436. b2.prev = bp;
  43437. return b2;
  43438. }
  43439. // create a node and optionally link it with previous one (in a circular doubly linked list)
  43440. function insertNode(i, x, y, last) {
  43441. var p = new Node(i, x, y);
  43442. if (!last) {
  43443. p.prev = p;
  43444. p.next = p;
  43445. }
  43446. else {
  43447. p.next = last.next;
  43448. p.prev = last;
  43449. last.next.prev = p;
  43450. last.next = p;
  43451. }
  43452. return p;
  43453. }
  43454. function removeNode(p) {
  43455. p.next.prev = p.prev;
  43456. p.prev.next = p.next;
  43457. if (p.prevZ)
  43458. p.prevZ.nextZ = p.nextZ;
  43459. if (p.nextZ)
  43460. p.nextZ.prevZ = p.prevZ;
  43461. }
  43462. function Node(i, x, y) {
  43463. // vertice index in coordinates array
  43464. this.i = i;
  43465. // vertex coordinates
  43466. this.x = x;
  43467. this.y = y;
  43468. // previous and next vertice nodes in a polygon ring
  43469. this.prev = null;
  43470. this.next = null;
  43471. // z-order curve value
  43472. this.z = null;
  43473. // previous and next nodes in z-order
  43474. this.prevZ = null;
  43475. this.nextZ = null;
  43476. // indicates whether this is a steiner point
  43477. this.steiner = false;
  43478. }
  43479. /**
  43480. * return a percentage difference between the polygon area and its triangulation area;
  43481. * used to verify correctness of triangulation
  43482. */
  43483. function deviation(data, holeIndices, dim, triangles) {
  43484. var hasHoles = holeIndices && holeIndices.length;
  43485. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  43486. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  43487. if (hasHoles) {
  43488. for (var i = 0, len = holeIndices.length; i < len; i++) {
  43489. var start = holeIndices[i] * dim;
  43490. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  43491. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  43492. }
  43493. }
  43494. var trianglesArea = 0;
  43495. for (i = 0; i < triangles.length; i += 3) {
  43496. var a = triangles[i] * dim;
  43497. var b = triangles[i + 1] * dim;
  43498. var c = triangles[i + 2] * dim;
  43499. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  43500. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  43501. }
  43502. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  43503. }
  43504. Earcut.deviation = deviation;
  43505. ;
  43506. function signedArea(data, start, end, dim) {
  43507. var sum = 0;
  43508. for (var i = start, j = end - dim; i < end; i += dim) {
  43509. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  43510. j = i;
  43511. }
  43512. return sum;
  43513. }
  43514. /**
  43515. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  43516. */
  43517. function flatten(data) {
  43518. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  43519. for (var i = 0; i < data.length; i++) {
  43520. for (var j = 0; j < data[i].length; j++) {
  43521. for (var d = 0; d < dim; d++)
  43522. result.vertices.push(data[i][j][d]);
  43523. }
  43524. if (i > 0) {
  43525. holeIndex += data[i - 1].length;
  43526. result.holes.push(holeIndex);
  43527. }
  43528. }
  43529. return result;
  43530. }
  43531. Earcut.flatten = flatten;
  43532. ;
  43533. })(Earcut || (Earcut = {}));
  43534. //# sourceMappingURL=babylon.earcut.js.map
  43535. var BABYLON;
  43536. (function (BABYLON) {
  43537. // Unique ID when we import meshes from Babylon to CSG
  43538. var currentCSGMeshId = 0;
  43539. // # class Vertex
  43540. // Represents a vertex of a polygon. Use your own vertex class instead of this
  43541. // one to provide additional features like texture coordinates and vertex
  43542. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  43543. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  43544. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  43545. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  43546. // is not used anywhere else.
  43547. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  43548. var Vertex = (function () {
  43549. function Vertex(pos, normal, uv) {
  43550. this.pos = pos;
  43551. this.normal = normal;
  43552. this.uv = uv;
  43553. }
  43554. Vertex.prototype.clone = function () {
  43555. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  43556. };
  43557. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  43558. // orientation of a polygon is flipped.
  43559. Vertex.prototype.flip = function () {
  43560. this.normal = this.normal.scale(-1);
  43561. };
  43562. // Create a new vertex between this vertex and `other` by linearly
  43563. // interpolating all properties using a parameter of `t`. Subclasses should
  43564. // override this to interpolate additional properties.
  43565. Vertex.prototype.interpolate = function (other, t) {
  43566. 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));
  43567. };
  43568. return Vertex;
  43569. }());
  43570. // # class Plane
  43571. // Represents a plane in 3D space.
  43572. var Plane = (function () {
  43573. function Plane(normal, w) {
  43574. this.normal = normal;
  43575. this.w = w;
  43576. }
  43577. Plane.FromPoints = function (a, b, c) {
  43578. var v0 = c.subtract(a);
  43579. var v1 = b.subtract(a);
  43580. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  43581. return null;
  43582. }
  43583. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  43584. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  43585. };
  43586. Plane.prototype.clone = function () {
  43587. return new Plane(this.normal.clone(), this.w);
  43588. };
  43589. Plane.prototype.flip = function () {
  43590. this.normal.scaleInPlace(-1);
  43591. this.w = -this.w;
  43592. };
  43593. // Split `polygon` by this plane if needed, then put the polygon or polygon
  43594. // fragments in the appropriate lists. Coplanar polygons go into either
  43595. // `coplanarFront` or `coplanarBack` depending on their orientation with
  43596. // respect to this plane. Polygons in front or in back of this plane go into
  43597. // either `front` or `back`.
  43598. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  43599. var COPLANAR = 0;
  43600. var FRONT = 1;
  43601. var BACK = 2;
  43602. var SPANNING = 3;
  43603. // Classify each point as well as the entire polygon into one of the above
  43604. // four classes.
  43605. var polygonType = 0;
  43606. var types = [];
  43607. var i;
  43608. var t;
  43609. for (i = 0; i < polygon.vertices.length; i++) {
  43610. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  43611. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  43612. polygonType |= type;
  43613. types.push(type);
  43614. }
  43615. // Put the polygon in the correct list, splitting it when necessary.
  43616. switch (polygonType) {
  43617. case COPLANAR:
  43618. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  43619. break;
  43620. case FRONT:
  43621. front.push(polygon);
  43622. break;
  43623. case BACK:
  43624. back.push(polygon);
  43625. break;
  43626. case SPANNING:
  43627. var f = [], b = [];
  43628. for (i = 0; i < polygon.vertices.length; i++) {
  43629. var j = (i + 1) % polygon.vertices.length;
  43630. var ti = types[i], tj = types[j];
  43631. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  43632. if (ti !== BACK)
  43633. f.push(vi);
  43634. if (ti !== FRONT)
  43635. b.push(ti !== BACK ? vi.clone() : vi);
  43636. if ((ti | tj) === SPANNING) {
  43637. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  43638. var v = vi.interpolate(vj, t);
  43639. f.push(v);
  43640. b.push(v.clone());
  43641. }
  43642. }
  43643. var poly;
  43644. if (f.length >= 3) {
  43645. poly = new Polygon(f, polygon.shared);
  43646. if (poly.plane)
  43647. front.push(poly);
  43648. }
  43649. if (b.length >= 3) {
  43650. poly = new Polygon(b, polygon.shared);
  43651. if (poly.plane)
  43652. back.push(poly);
  43653. }
  43654. break;
  43655. }
  43656. };
  43657. return Plane;
  43658. }());
  43659. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  43660. // point is on the plane.
  43661. Plane.EPSILON = 1e-5;
  43662. // # class Polygon
  43663. // Represents a convex polygon. The vertices used to initialize a polygon must
  43664. // be coplanar and form a convex loop.
  43665. //
  43666. // Each convex polygon has a `shared` property, which is shared between all
  43667. // polygons that are clones of each other or were split from the same polygon.
  43668. // This can be used to define per-polygon properties (such as surface color).
  43669. var Polygon = (function () {
  43670. function Polygon(vertices, shared) {
  43671. this.vertices = vertices;
  43672. this.shared = shared;
  43673. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  43674. }
  43675. Polygon.prototype.clone = function () {
  43676. var vertices = this.vertices.map(function (v) { return v.clone(); });
  43677. return new Polygon(vertices, this.shared);
  43678. };
  43679. Polygon.prototype.flip = function () {
  43680. this.vertices.reverse().map(function (v) { v.flip(); });
  43681. this.plane.flip();
  43682. };
  43683. return Polygon;
  43684. }());
  43685. // # class Node
  43686. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  43687. // by picking a polygon to split along. That polygon (and all other coplanar
  43688. // polygons) are added directly to that node and the other polygons are added to
  43689. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  43690. // no distinction between internal and leaf nodes.
  43691. var Node = (function () {
  43692. function Node(polygons) {
  43693. this.plane = null;
  43694. this.front = null;
  43695. this.back = null;
  43696. this.polygons = [];
  43697. if (polygons) {
  43698. this.build(polygons);
  43699. }
  43700. }
  43701. Node.prototype.clone = function () {
  43702. var node = new Node();
  43703. node.plane = this.plane && this.plane.clone();
  43704. node.front = this.front && this.front.clone();
  43705. node.back = this.back && this.back.clone();
  43706. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  43707. return node;
  43708. };
  43709. // Convert solid space to empty space and empty space to solid space.
  43710. Node.prototype.invert = function () {
  43711. for (var i = 0; i < this.polygons.length; i++) {
  43712. this.polygons[i].flip();
  43713. }
  43714. if (this.plane) {
  43715. this.plane.flip();
  43716. }
  43717. if (this.front) {
  43718. this.front.invert();
  43719. }
  43720. if (this.back) {
  43721. this.back.invert();
  43722. }
  43723. var temp = this.front;
  43724. this.front = this.back;
  43725. this.back = temp;
  43726. };
  43727. // Recursively remove all polygons in `polygons` that are inside this BSP
  43728. // tree.
  43729. Node.prototype.clipPolygons = function (polygons) {
  43730. if (!this.plane)
  43731. return polygons.slice();
  43732. var front = [], back = [];
  43733. for (var i = 0; i < polygons.length; i++) {
  43734. this.plane.splitPolygon(polygons[i], front, back, front, back);
  43735. }
  43736. if (this.front) {
  43737. front = this.front.clipPolygons(front);
  43738. }
  43739. if (this.back) {
  43740. back = this.back.clipPolygons(back);
  43741. }
  43742. else {
  43743. back = [];
  43744. }
  43745. return front.concat(back);
  43746. };
  43747. // Remove all polygons in this BSP tree that are inside the other BSP tree
  43748. // `bsp`.
  43749. Node.prototype.clipTo = function (bsp) {
  43750. this.polygons = bsp.clipPolygons(this.polygons);
  43751. if (this.front)
  43752. this.front.clipTo(bsp);
  43753. if (this.back)
  43754. this.back.clipTo(bsp);
  43755. };
  43756. // Return a list of all polygons in this BSP tree.
  43757. Node.prototype.allPolygons = function () {
  43758. var polygons = this.polygons.slice();
  43759. if (this.front)
  43760. polygons = polygons.concat(this.front.allPolygons());
  43761. if (this.back)
  43762. polygons = polygons.concat(this.back.allPolygons());
  43763. return polygons;
  43764. };
  43765. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  43766. // new polygons are filtered down to the bottom of the tree and become new
  43767. // nodes there. Each set of polygons is partitioned using the first polygon
  43768. // (no heuristic is used to pick a good split).
  43769. Node.prototype.build = function (polygons) {
  43770. if (!polygons.length)
  43771. return;
  43772. if (!this.plane)
  43773. this.plane = polygons[0].plane.clone();
  43774. var front = [], back = [];
  43775. for (var i = 0; i < polygons.length; i++) {
  43776. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  43777. }
  43778. if (front.length) {
  43779. if (!this.front)
  43780. this.front = new Node();
  43781. this.front.build(front);
  43782. }
  43783. if (back.length) {
  43784. if (!this.back)
  43785. this.back = new Node();
  43786. this.back.build(back);
  43787. }
  43788. };
  43789. return Node;
  43790. }());
  43791. var CSG = (function () {
  43792. function CSG() {
  43793. this.polygons = new Array();
  43794. }
  43795. // Convert BABYLON.Mesh to BABYLON.CSG
  43796. CSG.FromMesh = function (mesh) {
  43797. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  43798. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  43799. if (mesh instanceof BABYLON.Mesh) {
  43800. mesh.computeWorldMatrix(true);
  43801. matrix = mesh.getWorldMatrix();
  43802. meshPosition = mesh.position.clone();
  43803. meshRotation = mesh.rotation.clone();
  43804. if (mesh.rotationQuaternion) {
  43805. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  43806. }
  43807. meshScaling = mesh.scaling.clone();
  43808. }
  43809. else {
  43810. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  43811. }
  43812. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43813. var subMeshes = mesh.subMeshes;
  43814. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  43815. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  43816. vertices = [];
  43817. for (var j = 0; j < 3; j++) {
  43818. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  43819. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  43820. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  43821. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  43822. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  43823. vertex = new Vertex(position, normal, uv);
  43824. vertices.push(vertex);
  43825. }
  43826. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  43827. // To handle the case of degenerated triangle
  43828. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  43829. if (polygon.plane)
  43830. polygons.push(polygon);
  43831. }
  43832. }
  43833. var csg = CSG.FromPolygons(polygons);
  43834. csg.matrix = matrix;
  43835. csg.position = meshPosition;
  43836. csg.rotation = meshRotation;
  43837. csg.scaling = meshScaling;
  43838. csg.rotationQuaternion = meshRotationQuaternion;
  43839. currentCSGMeshId++;
  43840. return csg;
  43841. };
  43842. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  43843. CSG.FromPolygons = function (polygons) {
  43844. var csg = new CSG();
  43845. csg.polygons = polygons;
  43846. return csg;
  43847. };
  43848. CSG.prototype.clone = function () {
  43849. var csg = new CSG();
  43850. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  43851. csg.copyTransformAttributes(this);
  43852. return csg;
  43853. };
  43854. CSG.prototype.toPolygons = function () {
  43855. return this.polygons;
  43856. };
  43857. CSG.prototype.union = function (csg) {
  43858. var a = new Node(this.clone().polygons);
  43859. var b = new Node(csg.clone().polygons);
  43860. a.clipTo(b);
  43861. b.clipTo(a);
  43862. b.invert();
  43863. b.clipTo(a);
  43864. b.invert();
  43865. a.build(b.allPolygons());
  43866. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43867. };
  43868. CSG.prototype.unionInPlace = function (csg) {
  43869. var a = new Node(this.polygons);
  43870. var b = new Node(csg.polygons);
  43871. a.clipTo(b);
  43872. b.clipTo(a);
  43873. b.invert();
  43874. b.clipTo(a);
  43875. b.invert();
  43876. a.build(b.allPolygons());
  43877. this.polygons = a.allPolygons();
  43878. };
  43879. CSG.prototype.subtract = function (csg) {
  43880. var a = new Node(this.clone().polygons);
  43881. var b = new Node(csg.clone().polygons);
  43882. a.invert();
  43883. a.clipTo(b);
  43884. b.clipTo(a);
  43885. b.invert();
  43886. b.clipTo(a);
  43887. b.invert();
  43888. a.build(b.allPolygons());
  43889. a.invert();
  43890. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43891. };
  43892. CSG.prototype.subtractInPlace = function (csg) {
  43893. var a = new Node(this.polygons);
  43894. var b = new Node(csg.polygons);
  43895. a.invert();
  43896. a.clipTo(b);
  43897. b.clipTo(a);
  43898. b.invert();
  43899. b.clipTo(a);
  43900. b.invert();
  43901. a.build(b.allPolygons());
  43902. a.invert();
  43903. this.polygons = a.allPolygons();
  43904. };
  43905. CSG.prototype.intersect = function (csg) {
  43906. var a = new Node(this.clone().polygons);
  43907. var b = new Node(csg.clone().polygons);
  43908. a.invert();
  43909. b.clipTo(a);
  43910. b.invert();
  43911. a.clipTo(b);
  43912. b.clipTo(a);
  43913. a.build(b.allPolygons());
  43914. a.invert();
  43915. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  43916. };
  43917. CSG.prototype.intersectInPlace = function (csg) {
  43918. var a = new Node(this.polygons);
  43919. var b = new Node(csg.polygons);
  43920. a.invert();
  43921. b.clipTo(a);
  43922. b.invert();
  43923. a.clipTo(b);
  43924. b.clipTo(a);
  43925. a.build(b.allPolygons());
  43926. a.invert();
  43927. this.polygons = a.allPolygons();
  43928. };
  43929. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  43930. // not modified.
  43931. CSG.prototype.inverse = function () {
  43932. var csg = this.clone();
  43933. csg.inverseInPlace();
  43934. return csg;
  43935. };
  43936. CSG.prototype.inverseInPlace = function () {
  43937. this.polygons.map(function (p) { p.flip(); });
  43938. };
  43939. // This is used to keep meshes transformations so they can be restored
  43940. // when we build back a Babylon Mesh
  43941. // NB : All CSG operations are performed in world coordinates
  43942. CSG.prototype.copyTransformAttributes = function (csg) {
  43943. this.matrix = csg.matrix;
  43944. this.position = csg.position;
  43945. this.rotation = csg.rotation;
  43946. this.scaling = csg.scaling;
  43947. this.rotationQuaternion = csg.rotationQuaternion;
  43948. return this;
  43949. };
  43950. // Build Raw mesh from CSG
  43951. // Coordinates here are in world space
  43952. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  43953. var matrix = this.matrix.clone();
  43954. matrix.invert();
  43955. 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;
  43956. if (keepSubMeshes) {
  43957. // Sort Polygons, since subMeshes are indices range
  43958. polygons.sort(function (a, b) {
  43959. if (a.shared.meshId === b.shared.meshId) {
  43960. return a.shared.subMeshId - b.shared.subMeshId;
  43961. }
  43962. else {
  43963. return a.shared.meshId - b.shared.meshId;
  43964. }
  43965. });
  43966. }
  43967. for (var i = 0, il = polygons.length; i < il; i++) {
  43968. polygon = polygons[i];
  43969. // Building SubMeshes
  43970. if (!subMesh_dict[polygon.shared.meshId]) {
  43971. subMesh_dict[polygon.shared.meshId] = {};
  43972. }
  43973. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  43974. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  43975. indexStart: +Infinity,
  43976. indexEnd: -Infinity,
  43977. materialIndex: polygon.shared.materialIndex
  43978. };
  43979. }
  43980. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  43981. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  43982. polygonIndices[0] = 0;
  43983. polygonIndices[1] = j - 1;
  43984. polygonIndices[2] = j;
  43985. for (var k = 0; k < 3; k++) {
  43986. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  43987. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  43988. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  43989. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  43990. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  43991. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  43992. // Check if 2 points can be merged
  43993. if (!(typeof vertex_idx !== 'undefined' &&
  43994. normals[vertex_idx * 3] === localNormal.x &&
  43995. normals[vertex_idx * 3 + 1] === localNormal.y &&
  43996. normals[vertex_idx * 3 + 2] === localNormal.z &&
  43997. uvs[vertex_idx * 2] === uv.x &&
  43998. uvs[vertex_idx * 2 + 1] === uv.y)) {
  43999. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  44000. uvs.push(uv.x, uv.y);
  44001. normals.push(normal.x, normal.y, normal.z);
  44002. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  44003. }
  44004. indices.push(vertex_idx);
  44005. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  44006. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  44007. currentIndex++;
  44008. }
  44009. }
  44010. }
  44011. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  44012. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  44013. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  44014. mesh.setIndices(indices);
  44015. if (keepSubMeshes) {
  44016. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  44017. var materialIndexOffset = 0, materialMaxIndex;
  44018. mesh.subMeshes = new Array();
  44019. for (var m in subMesh_dict) {
  44020. materialMaxIndex = -1;
  44021. for (var sm in subMesh_dict[m]) {
  44022. subMesh_obj = subMesh_dict[m][sm];
  44023. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  44024. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  44025. }
  44026. materialIndexOffset += ++materialMaxIndex;
  44027. }
  44028. }
  44029. return mesh;
  44030. };
  44031. // Build Mesh from CSG taking material and transforms into account
  44032. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  44033. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  44034. mesh.material = material;
  44035. mesh.position.copyFrom(this.position);
  44036. mesh.rotation.copyFrom(this.rotation);
  44037. if (this.rotationQuaternion) {
  44038. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  44039. }
  44040. mesh.scaling.copyFrom(this.scaling);
  44041. mesh.computeWorldMatrix(true);
  44042. return mesh;
  44043. };
  44044. return CSG;
  44045. }());
  44046. BABYLON.CSG = CSG;
  44047. })(BABYLON || (BABYLON = {}));
  44048. //# sourceMappingURL=babylon.csg.js.map
  44049. var BABYLON;
  44050. (function (BABYLON) {
  44051. var VRDistortionCorrectionPostProcess = (function (_super) {
  44052. __extends(VRDistortionCorrectionPostProcess, _super);
  44053. //ANY
  44054. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  44055. var _this = _super.call(this, name, "vrDistortionCorrection", [
  44056. 'LensCenter',
  44057. 'Scale',
  44058. 'ScaleIn',
  44059. 'HmdWarpParam'
  44060. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  44061. _this._isRightEye = isRightEye;
  44062. _this._distortionFactors = vrMetrics.distortionK;
  44063. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  44064. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  44065. _this.onSizeChangedObservable.add(function () {
  44066. _this.aspectRatio = _this.width * .5 / _this.height;
  44067. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  44068. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  44069. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  44070. });
  44071. _this.onApplyObservable.add(function (effect) {
  44072. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  44073. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  44074. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  44075. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  44076. });
  44077. return _this;
  44078. }
  44079. return VRDistortionCorrectionPostProcess;
  44080. }(BABYLON.PostProcess));
  44081. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  44082. })(BABYLON || (BABYLON = {}));
  44083. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  44084. // Mainly based on these 2 articles :
  44085. // 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
  44086. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  44087. var BABYLON;
  44088. (function (BABYLON) {
  44089. var JoystickAxis;
  44090. (function (JoystickAxis) {
  44091. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  44092. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  44093. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  44094. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  44095. var VirtualJoystick = (function () {
  44096. function VirtualJoystick(leftJoystick) {
  44097. var _this = this;
  44098. if (leftJoystick) {
  44099. this._leftJoystick = true;
  44100. }
  44101. else {
  44102. this._leftJoystick = false;
  44103. }
  44104. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  44105. VirtualJoystick._globalJoystickIndex++;
  44106. // By default left & right arrow keys are moving the X
  44107. // and up & down keys are moving the Y
  44108. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44109. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44110. this.reverseLeftRight = false;
  44111. this.reverseUpDown = false;
  44112. // collections of pointers
  44113. this._touches = new BABYLON.StringDictionary();
  44114. this.deltaPosition = BABYLON.Vector3.Zero();
  44115. this._joystickSensibility = 25;
  44116. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44117. this._rotationSpeed = 25;
  44118. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  44119. this._rotateOnAxisRelativeToMesh = false;
  44120. this._onResize = function (evt) {
  44121. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44122. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44123. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  44124. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  44125. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  44126. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  44127. };
  44128. // injecting a canvas element on top of the canvas 3D game
  44129. if (!VirtualJoystick.vjCanvas) {
  44130. window.addEventListener("resize", this._onResize, false);
  44131. VirtualJoystick.vjCanvas = document.createElement("canvas");
  44132. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  44133. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  44134. VirtualJoystick.vjCanvas.width = window.innerWidth;
  44135. VirtualJoystick.vjCanvas.height = window.innerHeight;
  44136. VirtualJoystick.vjCanvas.style.width = "100%";
  44137. VirtualJoystick.vjCanvas.style.height = "100%";
  44138. VirtualJoystick.vjCanvas.style.position = "absolute";
  44139. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  44140. VirtualJoystick.vjCanvas.style.top = "0px";
  44141. VirtualJoystick.vjCanvas.style.left = "0px";
  44142. VirtualJoystick.vjCanvas.style.zIndex = "5";
  44143. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  44144. // Support for jQuery PEP polyfill
  44145. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  44146. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  44147. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  44148. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44149. document.body.appendChild(VirtualJoystick.vjCanvas);
  44150. }
  44151. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  44152. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  44153. this.pressed = false;
  44154. // default joystick color
  44155. this._joystickColor = "cyan";
  44156. this._joystickPointerID = -1;
  44157. // current joystick position
  44158. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  44159. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  44160. // origin joystick position
  44161. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  44162. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  44163. this._onPointerDownHandlerRef = function (evt) {
  44164. _this._onPointerDown(evt);
  44165. };
  44166. this._onPointerMoveHandlerRef = function (evt) {
  44167. _this._onPointerMove(evt);
  44168. };
  44169. this._onPointerOutHandlerRef = function (evt) {
  44170. _this._onPointerUp(evt);
  44171. };
  44172. this._onPointerUpHandlerRef = function (evt) {
  44173. _this._onPointerUp(evt);
  44174. };
  44175. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  44176. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  44177. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  44178. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  44179. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  44180. evt.preventDefault(); // Disables system menu
  44181. }, false);
  44182. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44183. }
  44184. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  44185. this._joystickSensibility = newJoystickSensibility;
  44186. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  44187. };
  44188. VirtualJoystick.prototype._onPointerDown = function (e) {
  44189. var positionOnScreenCondition;
  44190. e.preventDefault();
  44191. if (this._leftJoystick === true) {
  44192. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  44193. }
  44194. else {
  44195. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  44196. }
  44197. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  44198. // First contact will be dedicated to the virtual joystick
  44199. this._joystickPointerID = e.pointerId;
  44200. this._joystickPointerStartPos.x = e.clientX;
  44201. this._joystickPointerStartPos.y = e.clientY;
  44202. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  44203. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  44204. this._deltaJoystickVector.x = 0;
  44205. this._deltaJoystickVector.y = 0;
  44206. this.pressed = true;
  44207. this._touches.add(e.pointerId.toString(), e);
  44208. }
  44209. else {
  44210. // You can only trigger the action buttons with a joystick declared
  44211. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  44212. this._action();
  44213. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  44214. }
  44215. }
  44216. };
  44217. VirtualJoystick.prototype._onPointerMove = function (e) {
  44218. // If the current pointer is the one associated to the joystick (first touch contact)
  44219. if (this._joystickPointerID == e.pointerId) {
  44220. this._joystickPointerPos.x = e.clientX;
  44221. this._joystickPointerPos.y = e.clientY;
  44222. this._deltaJoystickVector = this._joystickPointerPos.clone();
  44223. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  44224. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  44225. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  44226. switch (this._axisTargetedByLeftAndRight) {
  44227. case JoystickAxis.X:
  44228. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  44229. break;
  44230. case JoystickAxis.Y:
  44231. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  44232. break;
  44233. case JoystickAxis.Z:
  44234. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  44235. break;
  44236. }
  44237. var directionUpDown = this.reverseUpDown ? 1 : -1;
  44238. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  44239. switch (this._axisTargetedByUpAndDown) {
  44240. case JoystickAxis.X:
  44241. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  44242. break;
  44243. case JoystickAxis.Y:
  44244. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  44245. break;
  44246. case JoystickAxis.Z:
  44247. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  44248. break;
  44249. }
  44250. }
  44251. else {
  44252. var data = this._touches.get(e.pointerId.toString());
  44253. if (data) {
  44254. data.x = e.clientX;
  44255. data.y = e.clientY;
  44256. }
  44257. }
  44258. };
  44259. VirtualJoystick.prototype._onPointerUp = function (e) {
  44260. if (this._joystickPointerID == e.pointerId) {
  44261. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 63, this._joystickPointerStartPos.y - 63, 126, 126);
  44262. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 41, this._joystickPreviousPointerPos.y - 41, 82, 82);
  44263. this._joystickPointerID = -1;
  44264. this.pressed = false;
  44265. }
  44266. else {
  44267. var touch = this._touches.get(e.pointerId.toString());
  44268. if (touch) {
  44269. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44270. }
  44271. }
  44272. this._deltaJoystickVector.x = 0;
  44273. this._deltaJoystickVector.y = 0;
  44274. this._touches.remove(e.pointerId.toString());
  44275. };
  44276. /**
  44277. * Change the color of the virtual joystick
  44278. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  44279. */
  44280. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  44281. this._joystickColor = newColor;
  44282. };
  44283. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  44284. this._action = action;
  44285. };
  44286. // Define which axis you'd like to control for left & right
  44287. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  44288. switch (axis) {
  44289. case JoystickAxis.X:
  44290. case JoystickAxis.Y:
  44291. case JoystickAxis.Z:
  44292. this._axisTargetedByLeftAndRight = axis;
  44293. break;
  44294. default:
  44295. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  44296. break;
  44297. }
  44298. };
  44299. // Define which axis you'd like to control for up & down
  44300. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  44301. switch (axis) {
  44302. case JoystickAxis.X:
  44303. case JoystickAxis.Y:
  44304. case JoystickAxis.Z:
  44305. this._axisTargetedByUpAndDown = axis;
  44306. break;
  44307. default:
  44308. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  44309. break;
  44310. }
  44311. };
  44312. VirtualJoystick.prototype._clearCanvas = function () {
  44313. if (this._leftJoystick) {
  44314. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  44315. }
  44316. else {
  44317. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  44318. }
  44319. };
  44320. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  44321. var _this = this;
  44322. if (this.pressed) {
  44323. this._touches.forEach(function (touch) {
  44324. if (touch.pointerId === _this._joystickPointerID) {
  44325. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 63, _this._joystickPointerStartPos.y - 63, 126, 126);
  44326. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 41, _this._joystickPreviousPointerPos.y - 41, 82, 82);
  44327. VirtualJoystick.vjCanvasContext.beginPath();
  44328. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44329. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44330. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  44331. VirtualJoystick.vjCanvasContext.stroke();
  44332. VirtualJoystick.vjCanvasContext.closePath();
  44333. VirtualJoystick.vjCanvasContext.beginPath();
  44334. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44335. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  44336. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  44337. VirtualJoystick.vjCanvasContext.stroke();
  44338. VirtualJoystick.vjCanvasContext.closePath();
  44339. VirtualJoystick.vjCanvasContext.beginPath();
  44340. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  44341. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  44342. VirtualJoystick.vjCanvasContext.stroke();
  44343. VirtualJoystick.vjCanvasContext.closePath();
  44344. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  44345. }
  44346. else {
  44347. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 43, touch.prevY - 43, 86, 86);
  44348. VirtualJoystick.vjCanvasContext.beginPath();
  44349. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  44350. VirtualJoystick.vjCanvasContext.beginPath();
  44351. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  44352. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  44353. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  44354. VirtualJoystick.vjCanvasContext.stroke();
  44355. VirtualJoystick.vjCanvasContext.closePath();
  44356. touch.prevX = touch.x;
  44357. touch.prevY = touch.y;
  44358. }
  44359. ;
  44360. });
  44361. }
  44362. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  44363. };
  44364. VirtualJoystick.prototype.releaseCanvas = function () {
  44365. if (VirtualJoystick.vjCanvas) {
  44366. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  44367. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  44368. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  44369. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  44370. window.removeEventListener("resize", this._onResize);
  44371. document.body.removeChild(VirtualJoystick.vjCanvas);
  44372. VirtualJoystick.vjCanvas = null;
  44373. }
  44374. };
  44375. return VirtualJoystick;
  44376. }());
  44377. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  44378. VirtualJoystick._globalJoystickIndex = 0;
  44379. BABYLON.VirtualJoystick = VirtualJoystick;
  44380. })(BABYLON || (BABYLON = {}));
  44381. //# sourceMappingURL=babylon.virtualJoystick.js.map
  44382. var BABYLON;
  44383. (function (BABYLON) {
  44384. // We're mainly based on the logic defined into the FreeCamera code
  44385. var VirtualJoysticksCamera = (function (_super) {
  44386. __extends(VirtualJoysticksCamera, _super);
  44387. function VirtualJoysticksCamera(name, position, scene) {
  44388. var _this = _super.call(this, name, position, scene) || this;
  44389. _this.inputs.addVirtualJoystick();
  44390. return _this;
  44391. }
  44392. VirtualJoysticksCamera.prototype.getClassName = function () {
  44393. return "VirtualJoysticksCamera";
  44394. };
  44395. return VirtualJoysticksCamera;
  44396. }(BABYLON.FreeCamera));
  44397. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  44398. })(BABYLON || (BABYLON = {}));
  44399. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  44400. var BABYLON;
  44401. (function (BABYLON) {
  44402. var FreeCameraVirtualJoystickInput = (function () {
  44403. function FreeCameraVirtualJoystickInput() {
  44404. }
  44405. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  44406. return this._leftjoystick;
  44407. };
  44408. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  44409. return this._rightjoystick;
  44410. };
  44411. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  44412. if (this._leftjoystick) {
  44413. var camera = this.camera;
  44414. var speed = camera._computeLocalCameraSpeed() * 50;
  44415. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  44416. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  44417. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  44418. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  44419. if (!this._leftjoystick.pressed) {
  44420. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  44421. }
  44422. if (!this._rightjoystick.pressed) {
  44423. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  44424. }
  44425. }
  44426. };
  44427. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  44428. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  44429. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  44430. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  44431. this._leftjoystick.setJoystickSensibility(0.15);
  44432. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  44433. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  44434. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  44435. this._rightjoystick.reverseUpDown = true;
  44436. this._rightjoystick.setJoystickSensibility(0.05);
  44437. this._rightjoystick.setJoystickColor("yellow");
  44438. };
  44439. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  44440. this._leftjoystick.releaseCanvas();
  44441. this._rightjoystick.releaseCanvas();
  44442. };
  44443. FreeCameraVirtualJoystickInput.prototype.getTypeName = function () {
  44444. return "FreeCameraVirtualJoystickInput";
  44445. };
  44446. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  44447. return "virtualJoystick";
  44448. };
  44449. return FreeCameraVirtualJoystickInput;
  44450. }());
  44451. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  44452. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  44453. })(BABYLON || (BABYLON = {}));
  44454. //# sourceMappingURL=babylon.freecamera.input.virtualjoystick.js.map
  44455. var BABYLON;
  44456. (function (BABYLON) {
  44457. var AnaglyphPostProcess = (function (_super) {
  44458. __extends(AnaglyphPostProcess, _super);
  44459. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  44460. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  44461. _this._passedProcess = rigCameras[0]._rigPostProcess;
  44462. _this.onApplyObservable.add(function (effect) {
  44463. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  44464. });
  44465. return _this;
  44466. }
  44467. return AnaglyphPostProcess;
  44468. }(BABYLON.PostProcess));
  44469. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  44470. })(BABYLON || (BABYLON = {}));
  44471. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  44472. var BABYLON;
  44473. (function (BABYLON) {
  44474. var OutlineRenderer = (function () {
  44475. function OutlineRenderer(scene) {
  44476. this._scene = scene;
  44477. }
  44478. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  44479. var _this = this;
  44480. if (useOverlay === void 0) { useOverlay = false; }
  44481. var scene = this._scene;
  44482. var engine = this._scene.getEngine();
  44483. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  44484. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  44485. return;
  44486. }
  44487. var mesh = subMesh.getRenderingMesh();
  44488. var material = subMesh.getMaterial();
  44489. engine.enableEffect(this._effect);
  44490. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  44491. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : 1.0);
  44492. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  44493. // Bones
  44494. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44495. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  44496. }
  44497. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  44498. // Alpha test
  44499. if (material && material.needAlphaTesting()) {
  44500. var alphaTexture = material.getAlphaTestTexture();
  44501. this._effect.setTexture("diffuseSampler", alphaTexture);
  44502. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  44503. }
  44504. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  44505. };
  44506. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  44507. var defines = [];
  44508. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  44509. var mesh = subMesh.getMesh();
  44510. var material = subMesh.getMaterial();
  44511. // Alpha test
  44512. if (material && material.needAlphaTesting()) {
  44513. defines.push("#define ALPHATEST");
  44514. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  44515. attribs.push(BABYLON.VertexBuffer.UVKind);
  44516. defines.push("#define UV1");
  44517. }
  44518. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  44519. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44520. defines.push("#define UV2");
  44521. }
  44522. }
  44523. // Bones
  44524. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  44525. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  44526. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  44527. if (mesh.numBoneInfluencers > 4) {
  44528. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  44529. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  44530. }
  44531. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  44532. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  44533. }
  44534. else {
  44535. defines.push("#define NUM_BONE_INFLUENCERS 0");
  44536. }
  44537. // Instances
  44538. if (useInstances) {
  44539. defines.push("#define INSTANCES");
  44540. attribs.push("world0");
  44541. attribs.push("world1");
  44542. attribs.push("world2");
  44543. attribs.push("world3");
  44544. }
  44545. // Get correct effect
  44546. var join = defines.join("\n");
  44547. if (this._cachedDefines !== join) {
  44548. this._cachedDefines = join;
  44549. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  44550. }
  44551. return this._effect.isReady();
  44552. };
  44553. return OutlineRenderer;
  44554. }());
  44555. BABYLON.OutlineRenderer = OutlineRenderer;
  44556. })(BABYLON || (BABYLON = {}));
  44557. //# sourceMappingURL=babylon.outlineRenderer.js.map
  44558. var BABYLON;
  44559. (function (BABYLON) {
  44560. var MeshAssetTask = (function () {
  44561. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  44562. this.name = name;
  44563. this.meshesNames = meshesNames;
  44564. this.rootUrl = rootUrl;
  44565. this.sceneFilename = sceneFilename;
  44566. this.isCompleted = false;
  44567. }
  44568. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44569. var _this = this;
  44570. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  44571. _this.loadedMeshes = meshes;
  44572. _this.loadedParticleSystems = particleSystems;
  44573. _this.loadedSkeletons = skeletons;
  44574. _this.isCompleted = true;
  44575. if (_this.onSuccess) {
  44576. _this.onSuccess(_this);
  44577. }
  44578. onSuccess();
  44579. }, null, function () {
  44580. if (_this.onError) {
  44581. _this.onError(_this);
  44582. }
  44583. onError();
  44584. });
  44585. };
  44586. return MeshAssetTask;
  44587. }());
  44588. BABYLON.MeshAssetTask = MeshAssetTask;
  44589. var TextFileAssetTask = (function () {
  44590. function TextFileAssetTask(name, url) {
  44591. this.name = name;
  44592. this.url = url;
  44593. this.isCompleted = false;
  44594. }
  44595. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44596. var _this = this;
  44597. BABYLON.Tools.LoadFile(this.url, function (data) {
  44598. _this.text = data;
  44599. _this.isCompleted = true;
  44600. if (_this.onSuccess) {
  44601. _this.onSuccess(_this);
  44602. }
  44603. onSuccess();
  44604. }, null, scene.database, false, function () {
  44605. if (_this.onError) {
  44606. _this.onError(_this);
  44607. }
  44608. onError();
  44609. });
  44610. };
  44611. return TextFileAssetTask;
  44612. }());
  44613. BABYLON.TextFileAssetTask = TextFileAssetTask;
  44614. var BinaryFileAssetTask = (function () {
  44615. function BinaryFileAssetTask(name, url) {
  44616. this.name = name;
  44617. this.url = url;
  44618. this.isCompleted = false;
  44619. }
  44620. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44621. var _this = this;
  44622. BABYLON.Tools.LoadFile(this.url, function (data) {
  44623. _this.data = data;
  44624. _this.isCompleted = true;
  44625. if (_this.onSuccess) {
  44626. _this.onSuccess(_this);
  44627. }
  44628. onSuccess();
  44629. }, null, scene.database, true, function () {
  44630. if (_this.onError) {
  44631. _this.onError(_this);
  44632. }
  44633. onError();
  44634. });
  44635. };
  44636. return BinaryFileAssetTask;
  44637. }());
  44638. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  44639. var ImageAssetTask = (function () {
  44640. function ImageAssetTask(name, url) {
  44641. this.name = name;
  44642. this.url = url;
  44643. this.isCompleted = false;
  44644. }
  44645. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44646. var _this = this;
  44647. var img = new Image();
  44648. BABYLON.Tools.SetCorsBehavior(this.url, img);
  44649. img.onload = function () {
  44650. _this.image = img;
  44651. _this.isCompleted = true;
  44652. if (_this.onSuccess) {
  44653. _this.onSuccess(_this);
  44654. }
  44655. onSuccess();
  44656. };
  44657. img.onerror = function () {
  44658. if (_this.onError) {
  44659. _this.onError(_this);
  44660. }
  44661. onError();
  44662. };
  44663. img.src = this.url;
  44664. };
  44665. return ImageAssetTask;
  44666. }());
  44667. BABYLON.ImageAssetTask = ImageAssetTask;
  44668. var TextureAssetTask = (function () {
  44669. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  44670. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44671. this.name = name;
  44672. this.url = url;
  44673. this.noMipmap = noMipmap;
  44674. this.invertY = invertY;
  44675. this.samplingMode = samplingMode;
  44676. this.isCompleted = false;
  44677. }
  44678. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44679. var _this = this;
  44680. var onload = function () {
  44681. _this.isCompleted = true;
  44682. if (_this.onSuccess) {
  44683. _this.onSuccess(_this);
  44684. }
  44685. onSuccess();
  44686. };
  44687. var onerror = function () {
  44688. if (_this.onError) {
  44689. _this.onError(_this);
  44690. }
  44691. onError();
  44692. };
  44693. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  44694. };
  44695. return TextureAssetTask;
  44696. }());
  44697. BABYLON.TextureAssetTask = TextureAssetTask;
  44698. var CubeTextureAssetTask = (function () {
  44699. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  44700. this.name = name;
  44701. this.url = url;
  44702. this.extensions = extensions;
  44703. this.noMipmap = noMipmap;
  44704. this.files = files;
  44705. this.isCompleted = false;
  44706. }
  44707. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  44708. var _this = this;
  44709. var onload = function () {
  44710. _this.isCompleted = true;
  44711. if (_this.onSuccess) {
  44712. _this.onSuccess(_this);
  44713. }
  44714. onSuccess();
  44715. };
  44716. var onerror = function () {
  44717. if (_this.onError) {
  44718. _this.onError(_this);
  44719. }
  44720. onError();
  44721. };
  44722. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  44723. };
  44724. return CubeTextureAssetTask;
  44725. }());
  44726. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  44727. var AssetsManager = (function () {
  44728. function AssetsManager(scene) {
  44729. this.tasks = new Array();
  44730. this.waitingTasksCount = 0;
  44731. this.useDefaultLoadingScreen = true;
  44732. this._scene = scene;
  44733. }
  44734. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  44735. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  44736. this.tasks.push(task);
  44737. return task;
  44738. };
  44739. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  44740. var task = new TextFileAssetTask(taskName, url);
  44741. this.tasks.push(task);
  44742. return task;
  44743. };
  44744. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  44745. var task = new BinaryFileAssetTask(taskName, url);
  44746. this.tasks.push(task);
  44747. return task;
  44748. };
  44749. AssetsManager.prototype.addImageTask = function (taskName, url) {
  44750. var task = new ImageAssetTask(taskName, url);
  44751. this.tasks.push(task);
  44752. return task;
  44753. };
  44754. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  44755. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  44756. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  44757. this.tasks.push(task);
  44758. return task;
  44759. };
  44760. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  44761. this.waitingTasksCount--;
  44762. if (this.waitingTasksCount === 0) {
  44763. if (this.onFinish) {
  44764. this.onFinish(this.tasks);
  44765. }
  44766. this._scene.getEngine().hideLoadingUI();
  44767. }
  44768. };
  44769. AssetsManager.prototype._runTask = function (task) {
  44770. var _this = this;
  44771. task.run(this._scene, function () {
  44772. if (_this.onTaskSuccess) {
  44773. _this.onTaskSuccess(task);
  44774. }
  44775. _this._decreaseWaitingTasksCount();
  44776. }, function () {
  44777. if (_this.onTaskError) {
  44778. _this.onTaskError(task);
  44779. }
  44780. _this._decreaseWaitingTasksCount();
  44781. });
  44782. };
  44783. AssetsManager.prototype.reset = function () {
  44784. this.tasks = new Array();
  44785. return this;
  44786. };
  44787. AssetsManager.prototype.load = function () {
  44788. this.waitingTasksCount = this.tasks.length;
  44789. if (this.waitingTasksCount === 0) {
  44790. if (this.onFinish) {
  44791. this.onFinish(this.tasks);
  44792. }
  44793. return this;
  44794. }
  44795. if (this.useDefaultLoadingScreen) {
  44796. this._scene.getEngine().displayLoadingUI();
  44797. }
  44798. for (var index = 0; index < this.tasks.length; index++) {
  44799. var task = this.tasks[index];
  44800. this._runTask(task);
  44801. }
  44802. return this;
  44803. };
  44804. return AssetsManager;
  44805. }());
  44806. BABYLON.AssetsManager = AssetsManager;
  44807. })(BABYLON || (BABYLON = {}));
  44808. //# sourceMappingURL=babylon.assetsManager.js.map
  44809. var BABYLON;
  44810. (function (BABYLON) {
  44811. var VRCameraMetrics = (function () {
  44812. function VRCameraMetrics() {
  44813. this.compensateDistortion = true;
  44814. }
  44815. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  44816. get: function () {
  44817. return this.hResolution / (2 * this.vResolution);
  44818. },
  44819. enumerable: true,
  44820. configurable: true
  44821. });
  44822. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  44823. get: function () {
  44824. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  44825. },
  44826. enumerable: true,
  44827. configurable: true
  44828. });
  44829. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  44830. get: function () {
  44831. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44832. var h = (4 * meters) / this.hScreenSize;
  44833. return BABYLON.Matrix.Translation(h, 0, 0);
  44834. },
  44835. enumerable: true,
  44836. configurable: true
  44837. });
  44838. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  44839. get: function () {
  44840. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  44841. var h = (4 * meters) / this.hScreenSize;
  44842. return BABYLON.Matrix.Translation(-h, 0, 0);
  44843. },
  44844. enumerable: true,
  44845. configurable: true
  44846. });
  44847. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  44848. get: function () {
  44849. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  44850. },
  44851. enumerable: true,
  44852. configurable: true
  44853. });
  44854. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  44855. get: function () {
  44856. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  44857. },
  44858. enumerable: true,
  44859. configurable: true
  44860. });
  44861. VRCameraMetrics.GetDefault = function () {
  44862. var result = new VRCameraMetrics();
  44863. result.hResolution = 1280;
  44864. result.vResolution = 800;
  44865. result.hScreenSize = 0.149759993;
  44866. result.vScreenSize = 0.0935999975;
  44867. result.vScreenCenter = 0.0467999987,
  44868. result.eyeToScreenDistance = 0.0410000011;
  44869. result.lensSeparationDistance = 0.0635000020;
  44870. result.interpupillaryDistance = 0.0640000030;
  44871. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  44872. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  44873. result.postProcessScaleFactor = 1.714605507808412;
  44874. result.lensCenterOffset = 0.151976421;
  44875. return result;
  44876. };
  44877. return VRCameraMetrics;
  44878. }());
  44879. BABYLON.VRCameraMetrics = VRCameraMetrics;
  44880. })(BABYLON || (BABYLON = {}));
  44881. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  44882. var BABYLON;
  44883. (function (BABYLON) {
  44884. var WebVRFreeCamera = (function (_super) {
  44885. __extends(WebVRFreeCamera, _super);
  44886. function WebVRFreeCamera(name, position, scene, compensateDistortion, webVROptions) {
  44887. if (compensateDistortion === void 0) { compensateDistortion = false; }
  44888. if (webVROptions === void 0) { webVROptions = {}; }
  44889. var _this = _super.call(this, name, position, scene) || this;
  44890. _this.webVROptions = webVROptions;
  44891. _this._vrDevice = null;
  44892. _this._cacheState = null;
  44893. _this._vrEnabled = false;
  44894. _this._attached = false;
  44895. //using the position provided as the current position offset
  44896. _this._positionOffset = position;
  44897. //enable VR
  44898. _this.getEngine().initWebVR();
  44899. if (!_this.getEngine().vrDisplaysPromise) {
  44900. BABYLON.Tools.Error("WebVR is not enabled on your browser");
  44901. }
  44902. else {
  44903. //TODO get the metrics updated using the device's eye parameters!
  44904. //TODO also check that the device has the right capabilities!
  44905. _this._frameData = new VRFrameData();
  44906. _this.getEngine().vrDisplaysPromise.then(function (devices) {
  44907. if (devices.length > 0) {
  44908. _this._vrEnabled = true;
  44909. if (_this.webVROptions.displayName) {
  44910. var found = devices.some(function (device) {
  44911. if (device.displayName === _this.webVROptions.displayName) {
  44912. _this._vrDevice = device;
  44913. return true;
  44914. }
  44915. else {
  44916. return false;
  44917. }
  44918. });
  44919. if (!found) {
  44920. _this._vrDevice = devices[0];
  44921. BABYLON.Tools.Warn("Display " + _this.webVROptions.displayName + " was not found. Using " + _this._vrDevice.displayName);
  44922. }
  44923. }
  44924. else {
  44925. //choose the first one
  44926. _this._vrDevice = devices[0];
  44927. }
  44928. //reset the rig parameters.
  44929. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { vrDisplay: _this._vrDevice, frameData: _this._frameData });
  44930. if (_this._attached) {
  44931. _this.getEngine().enableVR(_this._vrDevice);
  44932. }
  44933. }
  44934. else {
  44935. BABYLON.Tools.Error("No WebVR devices found!");
  44936. }
  44937. });
  44938. }
  44939. _this.rotationQuaternion = new BABYLON.Quaternion();
  44940. _this._quaternionCache = new BABYLON.Quaternion();
  44941. return _this;
  44942. }
  44943. WebVRFreeCamera.prototype._checkInputs = function () {
  44944. if (this._vrEnabled && this._vrDevice.getFrameData(this._frameData)) {
  44945. var currentPost = this._frameData.pose;
  44946. //make sure we have data
  44947. if (currentPost && currentPost.orientation) {
  44948. this._cacheState = currentPost;
  44949. this.rotationQuaternion.copyFromFloats(this._cacheState.orientation[0], this._cacheState.orientation[1], -this._cacheState.orientation[2], -this._cacheState.orientation[3]);
  44950. if (this.webVROptions.trackPosition && this._cacheState.position) {
  44951. this.position.copyFromFloats(this._cacheState.position[0], this._cacheState.position[1], -this._cacheState.position[2]);
  44952. //scale the position accordingly
  44953. this.webVROptions.positionScale && this.position.scaleInPlace(this.webVROptions.positionScale);
  44954. //add the position offset
  44955. this.position.addInPlace(this._positionOffset);
  44956. }
  44957. }
  44958. }
  44959. _super.prototype._checkInputs.call(this);
  44960. };
  44961. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  44962. _super.prototype.attachControl.call(this, element, noPreventDefault);
  44963. this._attached = true;
  44964. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  44965. if (this._vrEnabled) {
  44966. this.getEngine().enableVR(this._vrDevice);
  44967. }
  44968. };
  44969. WebVRFreeCamera.prototype.detachControl = function (element) {
  44970. _super.prototype.detachControl.call(this, element);
  44971. this._vrEnabled = false;
  44972. this._attached = false;
  44973. this.getEngine().disableVR();
  44974. };
  44975. WebVRFreeCamera.prototype.requestVRFullscreen = function (requestPointerlock) {
  44976. //Backwards comp.
  44977. BABYLON.Tools.Warn("requestVRFullscreen is deprecated. call attachControl() to start sending frames to the VR display.");
  44978. //this.getEngine().switchFullscreen(requestPointerlock);
  44979. };
  44980. WebVRFreeCamera.prototype.getClassName = function () {
  44981. return "WebVRFreeCamera";
  44982. };
  44983. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  44984. //uses the vrDisplay's "resetPose()".
  44985. //pitch and roll won't be affected.
  44986. this._vrDevice.resetPose();
  44987. };
  44988. /**
  44989. *
  44990. * Set the position offset of the VR camera
  44991. * The offset will be added to the WebVR pose, after scaling it (if set).
  44992. *
  44993. * @param {Vector3} [newPosition] an optional new position. if not provided, the current camera position will be used.
  44994. *
  44995. * @memberOf WebVRFreeCamera
  44996. */
  44997. WebVRFreeCamera.prototype.setPositionOffset = function (newPosition) {
  44998. if (newPosition) {
  44999. this._positionOffset = newPosition;
  45000. }
  45001. else {
  45002. this._positionOffset.copyFrom(this.position);
  45003. }
  45004. };
  45005. return WebVRFreeCamera;
  45006. }(BABYLON.FreeCamera));
  45007. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  45008. })(BABYLON || (BABYLON = {}));
  45009. //# sourceMappingURL=babylon.webVRCamera.js.map
  45010. var BABYLON;
  45011. (function (BABYLON) {
  45012. // Standard optimizations
  45013. var SceneOptimization = (function () {
  45014. function SceneOptimization(priority) {
  45015. if (priority === void 0) { priority = 0; }
  45016. this.priority = priority;
  45017. this.apply = function (scene) {
  45018. return true; // Return true if everything that can be done was applied
  45019. };
  45020. }
  45021. return SceneOptimization;
  45022. }());
  45023. BABYLON.SceneOptimization = SceneOptimization;
  45024. var TextureOptimization = (function (_super) {
  45025. __extends(TextureOptimization, _super);
  45026. function TextureOptimization(priority, maximumSize) {
  45027. if (priority === void 0) { priority = 0; }
  45028. if (maximumSize === void 0) { maximumSize = 1024; }
  45029. var _this = _super.call(this, priority) || this;
  45030. _this.priority = priority;
  45031. _this.maximumSize = maximumSize;
  45032. _this.apply = function (scene) {
  45033. var allDone = true;
  45034. for (var index = 0; index < scene.textures.length; index++) {
  45035. var texture = scene.textures[index];
  45036. if (!texture.canRescale) {
  45037. continue;
  45038. }
  45039. var currentSize = texture.getSize();
  45040. var maxDimension = Math.max(currentSize.width, currentSize.height);
  45041. if (maxDimension > _this.maximumSize) {
  45042. texture.scale(0.5);
  45043. allDone = false;
  45044. }
  45045. }
  45046. return allDone;
  45047. };
  45048. return _this;
  45049. }
  45050. return TextureOptimization;
  45051. }(SceneOptimization));
  45052. BABYLON.TextureOptimization = TextureOptimization;
  45053. var HardwareScalingOptimization = (function (_super) {
  45054. __extends(HardwareScalingOptimization, _super);
  45055. function HardwareScalingOptimization(priority, maximumScale) {
  45056. if (priority === void 0) { priority = 0; }
  45057. if (maximumScale === void 0) { maximumScale = 2; }
  45058. var _this = _super.call(this, priority) || this;
  45059. _this.priority = priority;
  45060. _this.maximumScale = maximumScale;
  45061. _this._currentScale = 1;
  45062. _this.apply = function (scene) {
  45063. _this._currentScale++;
  45064. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  45065. return _this._currentScale >= _this.maximumScale;
  45066. };
  45067. return _this;
  45068. }
  45069. return HardwareScalingOptimization;
  45070. }(SceneOptimization));
  45071. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  45072. var ShadowsOptimization = (function (_super) {
  45073. __extends(ShadowsOptimization, _super);
  45074. function ShadowsOptimization() {
  45075. var _this = _super.apply(this, arguments) || this;
  45076. _this.apply = function (scene) {
  45077. scene.shadowsEnabled = false;
  45078. return true;
  45079. };
  45080. return _this;
  45081. }
  45082. return ShadowsOptimization;
  45083. }(SceneOptimization));
  45084. BABYLON.ShadowsOptimization = ShadowsOptimization;
  45085. var PostProcessesOptimization = (function (_super) {
  45086. __extends(PostProcessesOptimization, _super);
  45087. function PostProcessesOptimization() {
  45088. var _this = _super.apply(this, arguments) || this;
  45089. _this.apply = function (scene) {
  45090. scene.postProcessesEnabled = false;
  45091. return true;
  45092. };
  45093. return _this;
  45094. }
  45095. return PostProcessesOptimization;
  45096. }(SceneOptimization));
  45097. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  45098. var LensFlaresOptimization = (function (_super) {
  45099. __extends(LensFlaresOptimization, _super);
  45100. function LensFlaresOptimization() {
  45101. var _this = _super.apply(this, arguments) || this;
  45102. _this.apply = function (scene) {
  45103. scene.lensFlaresEnabled = false;
  45104. return true;
  45105. };
  45106. return _this;
  45107. }
  45108. return LensFlaresOptimization;
  45109. }(SceneOptimization));
  45110. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  45111. var ParticlesOptimization = (function (_super) {
  45112. __extends(ParticlesOptimization, _super);
  45113. function ParticlesOptimization() {
  45114. var _this = _super.apply(this, arguments) || this;
  45115. _this.apply = function (scene) {
  45116. scene.particlesEnabled = false;
  45117. return true;
  45118. };
  45119. return _this;
  45120. }
  45121. return ParticlesOptimization;
  45122. }(SceneOptimization));
  45123. BABYLON.ParticlesOptimization = ParticlesOptimization;
  45124. var RenderTargetsOptimization = (function (_super) {
  45125. __extends(RenderTargetsOptimization, _super);
  45126. function RenderTargetsOptimization() {
  45127. var _this = _super.apply(this, arguments) || this;
  45128. _this.apply = function (scene) {
  45129. scene.renderTargetsEnabled = false;
  45130. return true;
  45131. };
  45132. return _this;
  45133. }
  45134. return RenderTargetsOptimization;
  45135. }(SceneOptimization));
  45136. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  45137. var MergeMeshesOptimization = (function (_super) {
  45138. __extends(MergeMeshesOptimization, _super);
  45139. function MergeMeshesOptimization() {
  45140. var _this = _super.apply(this, arguments) || this;
  45141. _this._canBeMerged = function (abstractMesh) {
  45142. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  45143. return false;
  45144. }
  45145. var mesh = abstractMesh;
  45146. if (!mesh.isVisible || !mesh.isEnabled()) {
  45147. return false;
  45148. }
  45149. if (mesh.instances.length > 0) {
  45150. return false;
  45151. }
  45152. if (mesh.skeleton || mesh.hasLODLevels) {
  45153. return false;
  45154. }
  45155. if (mesh.parent) {
  45156. return false;
  45157. }
  45158. return true;
  45159. };
  45160. _this.apply = function (scene, updateSelectionTree) {
  45161. var globalPool = scene.meshes.slice(0);
  45162. var globalLength = globalPool.length;
  45163. for (var index = 0; index < globalLength; index++) {
  45164. var currentPool = new Array();
  45165. var current = globalPool[index];
  45166. // Checks
  45167. if (!_this._canBeMerged(current)) {
  45168. continue;
  45169. }
  45170. currentPool.push(current);
  45171. // Find compatible meshes
  45172. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  45173. var otherMesh = globalPool[subIndex];
  45174. if (!_this._canBeMerged(otherMesh)) {
  45175. continue;
  45176. }
  45177. if (otherMesh.material !== current.material) {
  45178. continue;
  45179. }
  45180. if (otherMesh.checkCollisions !== current.checkCollisions) {
  45181. continue;
  45182. }
  45183. currentPool.push(otherMesh);
  45184. globalLength--;
  45185. globalPool.splice(subIndex, 1);
  45186. subIndex--;
  45187. }
  45188. if (currentPool.length < 2) {
  45189. continue;
  45190. }
  45191. // Merge meshes
  45192. BABYLON.Mesh.MergeMeshes(currentPool);
  45193. }
  45194. if (updateSelectionTree != undefined) {
  45195. if (updateSelectionTree) {
  45196. scene.createOrUpdateSelectionOctree();
  45197. }
  45198. }
  45199. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  45200. scene.createOrUpdateSelectionOctree();
  45201. }
  45202. return true;
  45203. };
  45204. return _this;
  45205. }
  45206. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  45207. get: function () {
  45208. return MergeMeshesOptimization._UpdateSelectionTree;
  45209. },
  45210. set: function (value) {
  45211. MergeMeshesOptimization._UpdateSelectionTree = value;
  45212. },
  45213. enumerable: true,
  45214. configurable: true
  45215. });
  45216. return MergeMeshesOptimization;
  45217. }(SceneOptimization));
  45218. MergeMeshesOptimization._UpdateSelectionTree = false;
  45219. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  45220. // Options
  45221. var SceneOptimizerOptions = (function () {
  45222. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  45223. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  45224. if (trackerDuration === void 0) { trackerDuration = 2000; }
  45225. this.targetFrameRate = targetFrameRate;
  45226. this.trackerDuration = trackerDuration;
  45227. this.optimizations = new Array();
  45228. }
  45229. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  45230. var result = new SceneOptimizerOptions(targetFrameRate);
  45231. var priority = 0;
  45232. result.optimizations.push(new MergeMeshesOptimization(priority));
  45233. result.optimizations.push(new ShadowsOptimization(priority));
  45234. result.optimizations.push(new LensFlaresOptimization(priority));
  45235. // Next priority
  45236. priority++;
  45237. result.optimizations.push(new PostProcessesOptimization(priority));
  45238. result.optimizations.push(new ParticlesOptimization(priority));
  45239. // Next priority
  45240. priority++;
  45241. result.optimizations.push(new TextureOptimization(priority, 1024));
  45242. return result;
  45243. };
  45244. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  45245. var result = new SceneOptimizerOptions(targetFrameRate);
  45246. var priority = 0;
  45247. result.optimizations.push(new MergeMeshesOptimization(priority));
  45248. result.optimizations.push(new ShadowsOptimization(priority));
  45249. result.optimizations.push(new LensFlaresOptimization(priority));
  45250. // Next priority
  45251. priority++;
  45252. result.optimizations.push(new PostProcessesOptimization(priority));
  45253. result.optimizations.push(new ParticlesOptimization(priority));
  45254. // Next priority
  45255. priority++;
  45256. result.optimizations.push(new TextureOptimization(priority, 512));
  45257. // Next priority
  45258. priority++;
  45259. result.optimizations.push(new RenderTargetsOptimization(priority));
  45260. // Next priority
  45261. priority++;
  45262. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  45263. return result;
  45264. };
  45265. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  45266. var result = new SceneOptimizerOptions(targetFrameRate);
  45267. var priority = 0;
  45268. result.optimizations.push(new MergeMeshesOptimization(priority));
  45269. result.optimizations.push(new ShadowsOptimization(priority));
  45270. result.optimizations.push(new LensFlaresOptimization(priority));
  45271. // Next priority
  45272. priority++;
  45273. result.optimizations.push(new PostProcessesOptimization(priority));
  45274. result.optimizations.push(new ParticlesOptimization(priority));
  45275. // Next priority
  45276. priority++;
  45277. result.optimizations.push(new TextureOptimization(priority, 256));
  45278. // Next priority
  45279. priority++;
  45280. result.optimizations.push(new RenderTargetsOptimization(priority));
  45281. // Next priority
  45282. priority++;
  45283. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  45284. return result;
  45285. };
  45286. return SceneOptimizerOptions;
  45287. }());
  45288. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  45289. // Scene optimizer tool
  45290. var SceneOptimizer = (function () {
  45291. function SceneOptimizer() {
  45292. }
  45293. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  45294. // TODO: add an epsilon
  45295. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  45296. if (onSuccess) {
  45297. onSuccess();
  45298. }
  45299. return;
  45300. }
  45301. // Apply current level of optimizations
  45302. var allDone = true;
  45303. var noOptimizationApplied = true;
  45304. for (var index = 0; index < options.optimizations.length; index++) {
  45305. var optimization = options.optimizations[index];
  45306. if (optimization.priority === currentPriorityLevel) {
  45307. noOptimizationApplied = false;
  45308. allDone = allDone && optimization.apply(scene);
  45309. }
  45310. }
  45311. // If no optimization was applied, this is a failure :(
  45312. if (noOptimizationApplied) {
  45313. if (onFailure) {
  45314. onFailure();
  45315. }
  45316. return;
  45317. }
  45318. // If all optimizations were done, move to next level
  45319. if (allDone) {
  45320. currentPriorityLevel++;
  45321. }
  45322. // Let's the system running for a specific amount of time before checking FPS
  45323. scene.executeWhenReady(function () {
  45324. setTimeout(function () {
  45325. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  45326. }, options.trackerDuration);
  45327. });
  45328. };
  45329. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  45330. if (!options) {
  45331. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  45332. }
  45333. // Let's the system running for a specific amount of time before checking FPS
  45334. scene.executeWhenReady(function () {
  45335. setTimeout(function () {
  45336. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  45337. }, options.trackerDuration);
  45338. });
  45339. };
  45340. return SceneOptimizer;
  45341. }());
  45342. BABYLON.SceneOptimizer = SceneOptimizer;
  45343. })(BABYLON || (BABYLON = {}));
  45344. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  45345. var BABYLON;
  45346. (function (BABYLON) {
  45347. var Internals;
  45348. (function (Internals) {
  45349. var MeshLODLevel = (function () {
  45350. function MeshLODLevel(distance, mesh) {
  45351. this.distance = distance;
  45352. this.mesh = mesh;
  45353. }
  45354. return MeshLODLevel;
  45355. }());
  45356. Internals.MeshLODLevel = MeshLODLevel;
  45357. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  45358. })(BABYLON || (BABYLON = {}));
  45359. //# sourceMappingURL=babylon.meshLODLevel.js.map
  45360. var BABYLON;
  45361. (function (BABYLON) {
  45362. var RawTexture = (function (_super) {
  45363. __extends(RawTexture, _super);
  45364. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  45365. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45366. if (invertY === void 0) { invertY = false; }
  45367. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45368. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  45369. _this.format = format;
  45370. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  45371. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45372. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45373. return _this;
  45374. }
  45375. RawTexture.prototype.update = function (data) {
  45376. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  45377. };
  45378. // Statics
  45379. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45380. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45381. if (invertY === void 0) { invertY = false; }
  45382. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45383. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  45384. };
  45385. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45386. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45387. if (invertY === void 0) { invertY = false; }
  45388. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45389. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45390. };
  45391. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45392. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45393. if (invertY === void 0) { invertY = false; }
  45394. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45395. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  45396. };
  45397. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45398. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45399. if (invertY === void 0) { invertY = false; }
  45400. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45401. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  45402. };
  45403. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  45404. if (generateMipMaps === void 0) { generateMipMaps = true; }
  45405. if (invertY === void 0) { invertY = false; }
  45406. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45407. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  45408. };
  45409. return RawTexture;
  45410. }(BABYLON.Texture));
  45411. BABYLON.RawTexture = RawTexture;
  45412. })(BABYLON || (BABYLON = {}));
  45413. //# sourceMappingURL=babylon.rawTexture.js.map
  45414. var BABYLON;
  45415. (function (BABYLON) {
  45416. var IndexedVector2 = (function (_super) {
  45417. __extends(IndexedVector2, _super);
  45418. function IndexedVector2(original, index) {
  45419. var _this = _super.call(this, original.x, original.y) || this;
  45420. _this.index = index;
  45421. return _this;
  45422. }
  45423. return IndexedVector2;
  45424. }(BABYLON.Vector2));
  45425. var PolygonPoints = (function () {
  45426. function PolygonPoints() {
  45427. this.elements = new Array();
  45428. }
  45429. PolygonPoints.prototype.add = function (originalPoints) {
  45430. var _this = this;
  45431. var result = new Array();
  45432. originalPoints.forEach(function (point) {
  45433. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  45434. var newPoint = new IndexedVector2(point, _this.elements.length);
  45435. result.push(newPoint);
  45436. _this.elements.push(newPoint);
  45437. }
  45438. });
  45439. return result;
  45440. };
  45441. PolygonPoints.prototype.computeBounds = function () {
  45442. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45443. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  45444. this.elements.forEach(function (point) {
  45445. // x
  45446. if (point.x < lmin.x) {
  45447. lmin.x = point.x;
  45448. }
  45449. else if (point.x > lmax.x) {
  45450. lmax.x = point.x;
  45451. }
  45452. // y
  45453. if (point.y < lmin.y) {
  45454. lmin.y = point.y;
  45455. }
  45456. else if (point.y > lmax.y) {
  45457. lmax.y = point.y;
  45458. }
  45459. });
  45460. return {
  45461. min: lmin,
  45462. max: lmax,
  45463. width: lmax.x - lmin.x,
  45464. height: lmax.y - lmin.y
  45465. };
  45466. };
  45467. return PolygonPoints;
  45468. }());
  45469. var Polygon = (function () {
  45470. function Polygon() {
  45471. }
  45472. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  45473. return [
  45474. new BABYLON.Vector2(xmin, ymin),
  45475. new BABYLON.Vector2(xmax, ymin),
  45476. new BABYLON.Vector2(xmax, ymax),
  45477. new BABYLON.Vector2(xmin, ymax)
  45478. ];
  45479. };
  45480. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  45481. if (cx === void 0) { cx = 0; }
  45482. if (cy === void 0) { cy = 0; }
  45483. if (numberOfSides === void 0) { numberOfSides = 32; }
  45484. var result = new Array();
  45485. var angle = 0;
  45486. var increment = (Math.PI * 2) / numberOfSides;
  45487. for (var i = 0; i < numberOfSides; i++) {
  45488. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  45489. angle -= increment;
  45490. }
  45491. return result;
  45492. };
  45493. Polygon.Parse = function (input) {
  45494. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  45495. var i, result = [];
  45496. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  45497. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  45498. }
  45499. return result;
  45500. };
  45501. Polygon.StartingAt = function (x, y) {
  45502. return BABYLON.Path2.StartingAt(x, y);
  45503. };
  45504. return Polygon;
  45505. }());
  45506. BABYLON.Polygon = Polygon;
  45507. var PolygonMeshBuilder = (function () {
  45508. function PolygonMeshBuilder(name, contours, scene) {
  45509. this._points = new PolygonPoints();
  45510. this._outlinepoints = new PolygonPoints();
  45511. this._holes = [];
  45512. this._epoints = new Array();
  45513. this._eholes = new Array();
  45514. this._name = name;
  45515. this._scene = scene;
  45516. var points;
  45517. if (contours instanceof BABYLON.Path2) {
  45518. points = contours.getPoints();
  45519. }
  45520. else {
  45521. points = contours;
  45522. }
  45523. this._addToepoint(points);
  45524. this._points.add(points);
  45525. this._outlinepoints.add(points);
  45526. }
  45527. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  45528. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  45529. var p = points_1[_i];
  45530. this._epoints.push(p.x, p.y);
  45531. }
  45532. };
  45533. PolygonMeshBuilder.prototype.addHole = function (hole) {
  45534. this._points.add(hole);
  45535. var holepoints = new PolygonPoints();
  45536. holepoints.add(hole);
  45537. this._holes.push(holepoints);
  45538. this._eholes.push(this._epoints.length / 2);
  45539. this._addToepoint(hole);
  45540. return this;
  45541. };
  45542. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  45543. var _this = this;
  45544. if (updatable === void 0) { updatable = false; }
  45545. var result = new BABYLON.Mesh(this._name, this._scene);
  45546. var normals = [];
  45547. var positions = [];
  45548. var uvs = [];
  45549. var bounds = this._points.computeBounds();
  45550. this._points.elements.forEach(function (p) {
  45551. normals.push(0, 1.0, 0);
  45552. positions.push(p.x, 0, p.y);
  45553. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  45554. });
  45555. var indices = [];
  45556. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  45557. for (var i = 0; i < res.length; i++) {
  45558. indices.push(res[i]);
  45559. }
  45560. if (depth > 0) {
  45561. var positionscount = (positions.length / 3); //get the current pointcount
  45562. this._points.elements.forEach(function (p) {
  45563. normals.push(0, -1.0, 0);
  45564. positions.push(p.x, -depth, p.y);
  45565. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  45566. });
  45567. var totalCount = indices.length;
  45568. for (var i = 0; i < totalCount; i += 3) {
  45569. var i0 = indices[i + 0];
  45570. var i1 = indices[i + 1];
  45571. var i2 = indices[i + 2];
  45572. indices.push(i2 + positionscount);
  45573. indices.push(i1 + positionscount);
  45574. indices.push(i0 + positionscount);
  45575. }
  45576. //Add the sides
  45577. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  45578. this._holes.forEach(function (hole) {
  45579. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  45580. });
  45581. }
  45582. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  45583. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  45584. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  45585. result.setIndices(indices);
  45586. return result;
  45587. };
  45588. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  45589. var StartIndex = positions.length / 3;
  45590. var ulength = 0;
  45591. for (var i = 0; i < points.elements.length; i++) {
  45592. var p = points.elements[i];
  45593. var p1;
  45594. if ((i + 1) > points.elements.length - 1) {
  45595. p1 = points.elements[0];
  45596. }
  45597. else {
  45598. p1 = points.elements[i + 1];
  45599. }
  45600. positions.push(p.x, 0, p.y);
  45601. positions.push(p.x, -depth, p.y);
  45602. positions.push(p1.x, 0, p1.y);
  45603. positions.push(p1.x, -depth, p1.y);
  45604. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  45605. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  45606. var v3 = v2.subtract(v1);
  45607. var v4 = new BABYLON.Vector3(0, 1, 0);
  45608. var vn = BABYLON.Vector3.Cross(v3, v4);
  45609. vn = vn.normalize();
  45610. uvs.push(ulength / bounds.width, 0);
  45611. uvs.push(ulength / bounds.width, 1);
  45612. ulength += v3.length();
  45613. uvs.push((ulength / bounds.width), 0);
  45614. uvs.push((ulength / bounds.width), 1);
  45615. if (!flip) {
  45616. normals.push(-vn.x, -vn.y, -vn.z);
  45617. normals.push(-vn.x, -vn.y, -vn.z);
  45618. normals.push(-vn.x, -vn.y, -vn.z);
  45619. normals.push(-vn.x, -vn.y, -vn.z);
  45620. indices.push(StartIndex);
  45621. indices.push(StartIndex + 1);
  45622. indices.push(StartIndex + 2);
  45623. indices.push(StartIndex + 1);
  45624. indices.push(StartIndex + 3);
  45625. indices.push(StartIndex + 2);
  45626. }
  45627. else {
  45628. normals.push(vn.x, vn.y, vn.z);
  45629. normals.push(vn.x, vn.y, vn.z);
  45630. normals.push(vn.x, vn.y, vn.z);
  45631. normals.push(vn.x, vn.y, vn.z);
  45632. indices.push(StartIndex);
  45633. indices.push(StartIndex + 2);
  45634. indices.push(StartIndex + 1);
  45635. indices.push(StartIndex + 1);
  45636. indices.push(StartIndex + 2);
  45637. indices.push(StartIndex + 3);
  45638. }
  45639. StartIndex += 4;
  45640. }
  45641. ;
  45642. };
  45643. return PolygonMeshBuilder;
  45644. }());
  45645. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  45646. })(BABYLON || (BABYLON = {}));
  45647. //# sourceMappingURL=babylon.polygonMesh.js.map
  45648. var BABYLON;
  45649. (function (BABYLON) {
  45650. var Octree = (function () {
  45651. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  45652. if (maxDepth === void 0) { maxDepth = 2; }
  45653. this.maxDepth = maxDepth;
  45654. this.dynamicContent = new Array();
  45655. this._maxBlockCapacity = maxBlockCapacity || 64;
  45656. this._selectionContent = new BABYLON.SmartArray(1024);
  45657. this._creationFunc = creationFunc;
  45658. }
  45659. // Methods
  45660. Octree.prototype.update = function (worldMin, worldMax, entries) {
  45661. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  45662. };
  45663. Octree.prototype.addMesh = function (entry) {
  45664. for (var index = 0; index < this.blocks.length; index++) {
  45665. var block = this.blocks[index];
  45666. block.addEntry(entry);
  45667. }
  45668. };
  45669. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  45670. this._selectionContent.reset();
  45671. for (var index = 0; index < this.blocks.length; index++) {
  45672. var block = this.blocks[index];
  45673. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  45674. }
  45675. if (allowDuplicate) {
  45676. this._selectionContent.concat(this.dynamicContent);
  45677. }
  45678. else {
  45679. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45680. }
  45681. return this._selectionContent;
  45682. };
  45683. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  45684. this._selectionContent.reset();
  45685. for (var index = 0; index < this.blocks.length; index++) {
  45686. var block = this.blocks[index];
  45687. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  45688. }
  45689. if (allowDuplicate) {
  45690. this._selectionContent.concat(this.dynamicContent);
  45691. }
  45692. else {
  45693. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45694. }
  45695. return this._selectionContent;
  45696. };
  45697. Octree.prototype.intersectsRay = function (ray) {
  45698. this._selectionContent.reset();
  45699. for (var index = 0; index < this.blocks.length; index++) {
  45700. var block = this.blocks[index];
  45701. block.intersectsRay(ray, this._selectionContent);
  45702. }
  45703. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  45704. return this._selectionContent;
  45705. };
  45706. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  45707. target.blocks = new Array();
  45708. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  45709. // Segmenting space
  45710. for (var x = 0; x < 2; x++) {
  45711. for (var y = 0; y < 2; y++) {
  45712. for (var z = 0; z < 2; z++) {
  45713. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  45714. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  45715. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  45716. block.addEntries(entries);
  45717. target.blocks.push(block);
  45718. }
  45719. }
  45720. }
  45721. };
  45722. return Octree;
  45723. }());
  45724. Octree.CreationFuncForMeshes = function (entry, block) {
  45725. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45726. block.entries.push(entry);
  45727. }
  45728. };
  45729. Octree.CreationFuncForSubMeshes = function (entry, block) {
  45730. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  45731. block.entries.push(entry);
  45732. }
  45733. };
  45734. BABYLON.Octree = Octree;
  45735. })(BABYLON || (BABYLON = {}));
  45736. //# sourceMappingURL=babylon.octree.js.map
  45737. var BABYLON;
  45738. (function (BABYLON) {
  45739. var OctreeBlock = (function () {
  45740. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  45741. this.entries = new Array();
  45742. this._boundingVectors = new Array();
  45743. this._capacity = capacity;
  45744. this._depth = depth;
  45745. this._maxDepth = maxDepth;
  45746. this._creationFunc = creationFunc;
  45747. this._minPoint = minPoint;
  45748. this._maxPoint = maxPoint;
  45749. this._boundingVectors.push(minPoint.clone());
  45750. this._boundingVectors.push(maxPoint.clone());
  45751. this._boundingVectors.push(minPoint.clone());
  45752. this._boundingVectors[2].x = maxPoint.x;
  45753. this._boundingVectors.push(minPoint.clone());
  45754. this._boundingVectors[3].y = maxPoint.y;
  45755. this._boundingVectors.push(minPoint.clone());
  45756. this._boundingVectors[4].z = maxPoint.z;
  45757. this._boundingVectors.push(maxPoint.clone());
  45758. this._boundingVectors[5].z = minPoint.z;
  45759. this._boundingVectors.push(maxPoint.clone());
  45760. this._boundingVectors[6].x = minPoint.x;
  45761. this._boundingVectors.push(maxPoint.clone());
  45762. this._boundingVectors[7].y = minPoint.y;
  45763. }
  45764. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  45765. // Property
  45766. get: function () {
  45767. return this._capacity;
  45768. },
  45769. enumerable: true,
  45770. configurable: true
  45771. });
  45772. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  45773. get: function () {
  45774. return this._minPoint;
  45775. },
  45776. enumerable: true,
  45777. configurable: true
  45778. });
  45779. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  45780. get: function () {
  45781. return this._maxPoint;
  45782. },
  45783. enumerable: true,
  45784. configurable: true
  45785. });
  45786. // Methods
  45787. OctreeBlock.prototype.addEntry = function (entry) {
  45788. if (this.blocks) {
  45789. for (var index = 0; index < this.blocks.length; index++) {
  45790. var block = this.blocks[index];
  45791. block.addEntry(entry);
  45792. }
  45793. return;
  45794. }
  45795. this._creationFunc(entry, this);
  45796. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  45797. this.createInnerBlocks();
  45798. }
  45799. };
  45800. OctreeBlock.prototype.addEntries = function (entries) {
  45801. for (var index = 0; index < entries.length; index++) {
  45802. var mesh = entries[index];
  45803. this.addEntry(mesh);
  45804. }
  45805. };
  45806. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  45807. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  45808. if (this.blocks) {
  45809. for (var index = 0; index < this.blocks.length; index++) {
  45810. var block = this.blocks[index];
  45811. block.select(frustumPlanes, selection, allowDuplicate);
  45812. }
  45813. return;
  45814. }
  45815. if (allowDuplicate) {
  45816. selection.concat(this.entries);
  45817. }
  45818. else {
  45819. selection.concatWithNoDuplicate(this.entries);
  45820. }
  45821. }
  45822. };
  45823. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  45824. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  45825. if (this.blocks) {
  45826. for (var index = 0; index < this.blocks.length; index++) {
  45827. var block = this.blocks[index];
  45828. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  45829. }
  45830. return;
  45831. }
  45832. if (allowDuplicate) {
  45833. selection.concat(this.entries);
  45834. }
  45835. else {
  45836. selection.concatWithNoDuplicate(this.entries);
  45837. }
  45838. }
  45839. };
  45840. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  45841. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  45842. if (this.blocks) {
  45843. for (var index = 0; index < this.blocks.length; index++) {
  45844. var block = this.blocks[index];
  45845. block.intersectsRay(ray, selection);
  45846. }
  45847. return;
  45848. }
  45849. selection.concatWithNoDuplicate(this.entries);
  45850. }
  45851. };
  45852. OctreeBlock.prototype.createInnerBlocks = function () {
  45853. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  45854. };
  45855. return OctreeBlock;
  45856. }());
  45857. BABYLON.OctreeBlock = OctreeBlock;
  45858. })(BABYLON || (BABYLON = {}));
  45859. //# sourceMappingURL=babylon.octreeBlock.js.map
  45860. var BABYLON;
  45861. (function (BABYLON) {
  45862. var BlurPostProcess = (function (_super) {
  45863. __extends(BlurPostProcess, _super);
  45864. function BlurPostProcess(name, direction, blurWidth, options, camera, samplingMode, engine, reusable) {
  45865. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45866. var _this = _super.call(this, name, "blur", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  45867. _this.direction = direction;
  45868. _this.blurWidth = blurWidth;
  45869. _this.onApplyObservable.add(function (effect) {
  45870. effect.setFloat2("screenSize", _this.width, _this.height);
  45871. effect.setVector2("direction", _this.direction);
  45872. effect.setFloat("blurWidth", _this.blurWidth);
  45873. });
  45874. return _this;
  45875. }
  45876. return BlurPostProcess;
  45877. }(BABYLON.PostProcess));
  45878. BABYLON.BlurPostProcess = BlurPostProcess;
  45879. })(BABYLON || (BABYLON = {}));
  45880. //# sourceMappingURL=babylon.blurPostProcess.js.map
  45881. var BABYLON;
  45882. (function (BABYLON) {
  45883. var RefractionPostProcess = (function (_super) {
  45884. __extends(RefractionPostProcess, _super);
  45885. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  45886. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  45887. _this.color = color;
  45888. _this.depth = depth;
  45889. _this.colorLevel = colorLevel;
  45890. _this.onActivateObservable.add(function (cam) {
  45891. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  45892. });
  45893. _this.onApplyObservable.add(function (effect) {
  45894. effect.setColor3("baseColor", _this.color);
  45895. effect.setFloat("depth", _this.depth);
  45896. effect.setFloat("colorLevel", _this.colorLevel);
  45897. effect.setTexture("refractionSampler", _this._refRexture);
  45898. });
  45899. return _this;
  45900. }
  45901. // Methods
  45902. RefractionPostProcess.prototype.dispose = function (camera) {
  45903. if (this._refRexture) {
  45904. this._refRexture.dispose();
  45905. }
  45906. _super.prototype.dispose.call(this, camera);
  45907. };
  45908. return RefractionPostProcess;
  45909. }(BABYLON.PostProcess));
  45910. BABYLON.RefractionPostProcess = RefractionPostProcess;
  45911. })(BABYLON || (BABYLON = {}));
  45912. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  45913. var BABYLON;
  45914. (function (BABYLON) {
  45915. var BlackAndWhitePostProcess = (function (_super) {
  45916. __extends(BlackAndWhitePostProcess, _super);
  45917. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  45918. return _super.call(this, name, "blackAndWhite", null, null, options, camera, samplingMode, engine, reusable) || this;
  45919. }
  45920. return BlackAndWhitePostProcess;
  45921. }(BABYLON.PostProcess));
  45922. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  45923. })(BABYLON || (BABYLON = {}));
  45924. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  45925. var BABYLON;
  45926. (function (BABYLON) {
  45927. var ConvolutionPostProcess = (function (_super) {
  45928. __extends(ConvolutionPostProcess, _super);
  45929. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  45930. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45931. _this.kernel = kernel;
  45932. _this.onApply = function (effect) {
  45933. effect.setFloat2("screenSize", _this.width, _this.height);
  45934. effect.setArray("kernel", _this.kernel);
  45935. };
  45936. return _this;
  45937. }
  45938. return ConvolutionPostProcess;
  45939. }(BABYLON.PostProcess));
  45940. // Statics
  45941. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  45942. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  45943. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  45944. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  45945. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  45946. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  45947. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  45948. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  45949. })(BABYLON || (BABYLON = {}));
  45950. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  45951. var BABYLON;
  45952. (function (BABYLON) {
  45953. var FilterPostProcess = (function (_super) {
  45954. __extends(FilterPostProcess, _super);
  45955. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  45956. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  45957. _this.kernelMatrix = kernelMatrix;
  45958. _this.onApply = function (effect) {
  45959. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  45960. };
  45961. return _this;
  45962. }
  45963. return FilterPostProcess;
  45964. }(BABYLON.PostProcess));
  45965. BABYLON.FilterPostProcess = FilterPostProcess;
  45966. })(BABYLON || (BABYLON = {}));
  45967. //# sourceMappingURL=babylon.filterPostProcess.js.map
  45968. var BABYLON;
  45969. (function (BABYLON) {
  45970. var FxaaPostProcess = (function (_super) {
  45971. __extends(FxaaPostProcess, _super);
  45972. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable) {
  45973. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode, engine, reusable) || this;
  45974. _this.onSizeChangedObservable.add(function () {
  45975. _this.texelWidth = 1.0 / _this.width;
  45976. _this.texelHeight = 1.0 / _this.height;
  45977. });
  45978. _this.onApplyObservable.add(function (effect) {
  45979. effect.setFloat2("texelSize", _this.texelWidth, _this.texelHeight);
  45980. });
  45981. return _this;
  45982. }
  45983. return FxaaPostProcess;
  45984. }(BABYLON.PostProcess));
  45985. BABYLON.FxaaPostProcess = FxaaPostProcess;
  45986. })(BABYLON || (BABYLON = {}));
  45987. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  45988. var BABYLON;
  45989. (function (BABYLON) {
  45990. var StereoscopicInterlacePostProcess = (function (_super) {
  45991. __extends(StereoscopicInterlacePostProcess, _super);
  45992. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  45993. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  45994. _this._passedProcess = rigCameras[0]._rigPostProcess;
  45995. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45996. _this.onSizeChangedObservable.add(function () {
  45997. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  45998. });
  45999. _this.onApplyObservable.add(function (effect) {
  46000. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  46001. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  46002. });
  46003. return _this;
  46004. }
  46005. return StereoscopicInterlacePostProcess;
  46006. }(BABYLON.PostProcess));
  46007. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  46008. })(BABYLON || (BABYLON = {}));
  46009. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  46010. var BABYLON;
  46011. (function (BABYLON) {
  46012. var LensFlare = (function () {
  46013. function LensFlare(size, position, color, imgUrl, system) {
  46014. this.size = size;
  46015. this.position = position;
  46016. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  46017. this.dispose = function () {
  46018. if (this.texture) {
  46019. this.texture.dispose();
  46020. }
  46021. // Remove from scene
  46022. var index = this._system.lensFlares.indexOf(this);
  46023. this._system.lensFlares.splice(index, 1);
  46024. };
  46025. this.color = color || new BABYLON.Color3(1, 1, 1);
  46026. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  46027. this._system = system;
  46028. system.lensFlares.push(this);
  46029. }
  46030. return LensFlare;
  46031. }());
  46032. BABYLON.LensFlare = LensFlare;
  46033. })(BABYLON || (BABYLON = {}));
  46034. //# sourceMappingURL=babylon.lensFlare.js.map
  46035. var BABYLON;
  46036. (function (BABYLON) {
  46037. var LensFlareSystem = (function () {
  46038. function LensFlareSystem(name, emitter, scene) {
  46039. this.name = name;
  46040. this.lensFlares = new Array();
  46041. this.borderLimit = 300;
  46042. this.viewportBorder = 0;
  46043. this.layerMask = 0x0FFFFFFF;
  46044. this._vertexBuffers = {};
  46045. this._isEnabled = true;
  46046. this._scene = scene;
  46047. this._emitter = emitter;
  46048. this.id = name;
  46049. scene.lensFlareSystems.push(this);
  46050. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  46051. var engine = scene.getEngine();
  46052. // VBO
  46053. var vertices = [];
  46054. vertices.push(1, 1);
  46055. vertices.push(-1, 1);
  46056. vertices.push(-1, -1);
  46057. vertices.push(1, -1);
  46058. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  46059. // Indices
  46060. var indices = [];
  46061. indices.push(0);
  46062. indices.push(1);
  46063. indices.push(2);
  46064. indices.push(0);
  46065. indices.push(2);
  46066. indices.push(3);
  46067. this._indexBuffer = engine.createIndexBuffer(indices);
  46068. // Effects
  46069. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  46070. }
  46071. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  46072. get: function () {
  46073. return this._isEnabled;
  46074. },
  46075. set: function (value) {
  46076. this._isEnabled = value;
  46077. },
  46078. enumerable: true,
  46079. configurable: true
  46080. });
  46081. LensFlareSystem.prototype.getScene = function () {
  46082. return this._scene;
  46083. };
  46084. LensFlareSystem.prototype.getEmitter = function () {
  46085. return this._emitter;
  46086. };
  46087. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  46088. this._emitter = newEmitter;
  46089. };
  46090. LensFlareSystem.prototype.getEmitterPosition = function () {
  46091. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  46092. };
  46093. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  46094. var position = this.getEmitterPosition();
  46095. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  46096. this._positionX = position.x;
  46097. this._positionY = position.y;
  46098. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  46099. if (this.viewportBorder > 0) {
  46100. globalViewport.x -= this.viewportBorder;
  46101. globalViewport.y -= this.viewportBorder;
  46102. globalViewport.width += this.viewportBorder * 2;
  46103. globalViewport.height += this.viewportBorder * 2;
  46104. position.x += this.viewportBorder;
  46105. position.y += this.viewportBorder;
  46106. this._positionX += this.viewportBorder;
  46107. this._positionY += this.viewportBorder;
  46108. }
  46109. if (position.z > 0) {
  46110. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  46111. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  46112. return true;
  46113. }
  46114. return true;
  46115. }
  46116. return false;
  46117. };
  46118. LensFlareSystem.prototype._isVisible = function () {
  46119. if (!this._isEnabled) {
  46120. return false;
  46121. }
  46122. var emitterPosition = this.getEmitterPosition();
  46123. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  46124. var distance = direction.length();
  46125. direction.normalize();
  46126. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  46127. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  46128. return !pickInfo.hit || pickInfo.distance > distance;
  46129. };
  46130. LensFlareSystem.prototype.render = function () {
  46131. if (!this._effect.isReady())
  46132. return false;
  46133. var engine = this._scene.getEngine();
  46134. var viewport = this._scene.activeCamera.viewport;
  46135. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  46136. // Position
  46137. if (!this.computeEffectivePosition(globalViewport)) {
  46138. return false;
  46139. }
  46140. // Visibility
  46141. if (!this._isVisible()) {
  46142. return false;
  46143. }
  46144. // Intensity
  46145. var awayX;
  46146. var awayY;
  46147. if (this._positionX < this.borderLimit + globalViewport.x) {
  46148. awayX = this.borderLimit + globalViewport.x - this._positionX;
  46149. }
  46150. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  46151. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  46152. }
  46153. else {
  46154. awayX = 0;
  46155. }
  46156. if (this._positionY < this.borderLimit + globalViewport.y) {
  46157. awayY = this.borderLimit + globalViewport.y - this._positionY;
  46158. }
  46159. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  46160. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  46161. }
  46162. else {
  46163. awayY = 0;
  46164. }
  46165. var away = (awayX > awayY) ? awayX : awayY;
  46166. away -= this.viewportBorder;
  46167. if (away > this.borderLimit) {
  46168. away = this.borderLimit;
  46169. }
  46170. var intensity = 1.0 - (away / this.borderLimit);
  46171. if (intensity < 0) {
  46172. return false;
  46173. }
  46174. if (intensity > 1.0) {
  46175. intensity = 1.0;
  46176. }
  46177. if (this.viewportBorder > 0) {
  46178. globalViewport.x += this.viewportBorder;
  46179. globalViewport.y += this.viewportBorder;
  46180. globalViewport.width -= this.viewportBorder * 2;
  46181. globalViewport.height -= this.viewportBorder * 2;
  46182. this._positionX -= this.viewportBorder;
  46183. this._positionY -= this.viewportBorder;
  46184. }
  46185. // Position
  46186. var centerX = globalViewport.x + globalViewport.width / 2;
  46187. var centerY = globalViewport.y + globalViewport.height / 2;
  46188. var distX = centerX - this._positionX;
  46189. var distY = centerY - this._positionY;
  46190. // Effects
  46191. engine.enableEffect(this._effect);
  46192. engine.setState(false);
  46193. engine.setDepthBuffer(false);
  46194. // VBOs
  46195. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  46196. // Flares
  46197. for (var index = 0; index < this.lensFlares.length; index++) {
  46198. var flare = this.lensFlares[index];
  46199. engine.setAlphaMode(flare.alphaMode);
  46200. var x = centerX - (distX * flare.position);
  46201. var y = centerY - (distY * flare.position);
  46202. var cw = flare.size;
  46203. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  46204. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  46205. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  46206. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  46207. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  46208. // Texture
  46209. this._effect.setTexture("textureSampler", flare.texture);
  46210. // Color
  46211. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  46212. // Draw order
  46213. engine.draw(true, 0, 6);
  46214. }
  46215. engine.setDepthBuffer(true);
  46216. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  46217. return true;
  46218. };
  46219. LensFlareSystem.prototype.dispose = function () {
  46220. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  46221. if (vertexBuffer) {
  46222. vertexBuffer.dispose();
  46223. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  46224. }
  46225. if (this._indexBuffer) {
  46226. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  46227. this._indexBuffer = null;
  46228. }
  46229. while (this.lensFlares.length) {
  46230. this.lensFlares[0].dispose();
  46231. }
  46232. // Remove from scene
  46233. var index = this._scene.lensFlareSystems.indexOf(this);
  46234. this._scene.lensFlareSystems.splice(index, 1);
  46235. };
  46236. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  46237. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  46238. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  46239. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  46240. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  46241. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  46242. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  46243. var parsedFlare = parsedLensFlareSystem.flares[index];
  46244. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), rootUrl + parsedFlare.textureName, lensFlareSystem);
  46245. }
  46246. return lensFlareSystem;
  46247. };
  46248. LensFlareSystem.prototype.serialize = function () {
  46249. var serializationObject = {};
  46250. serializationObject.id = this.id;
  46251. serializationObject.name = this.name;
  46252. serializationObject.emitterId = this.getEmitter().id;
  46253. serializationObject.borderLimit = this.borderLimit;
  46254. serializationObject.flares = [];
  46255. for (var index = 0; index < this.lensFlares.length; index++) {
  46256. var flare = this.lensFlares[index];
  46257. serializationObject.flares.push({
  46258. size: flare.size,
  46259. position: flare.position,
  46260. color: flare.color.asArray(),
  46261. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  46262. });
  46263. }
  46264. return serializationObject;
  46265. };
  46266. return LensFlareSystem;
  46267. }());
  46268. BABYLON.LensFlareSystem = LensFlareSystem;
  46269. })(BABYLON || (BABYLON = {}));
  46270. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  46271. var BABYLON;
  46272. (function (BABYLON) {
  46273. // We're mainly based on the logic defined into the FreeCamera code
  46274. var DeviceOrientationCamera = (function (_super) {
  46275. __extends(DeviceOrientationCamera, _super);
  46276. function DeviceOrientationCamera(name, position, scene) {
  46277. var _this = _super.call(this, name, position, scene) || this;
  46278. _this._quaternionCache = new BABYLON.Quaternion();
  46279. _this.inputs.addDeviceOrientation();
  46280. return _this;
  46281. }
  46282. DeviceOrientationCamera.prototype.getClassName = function () {
  46283. return "DeviceOrientationCamera";
  46284. };
  46285. DeviceOrientationCamera.prototype._checkInputs = function () {
  46286. _super.prototype._checkInputs.call(this);
  46287. this._quaternionCache.copyFrom(this.rotationQuaternion);
  46288. if (this._initialQuaternion) {
  46289. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46290. }
  46291. };
  46292. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  46293. var _this = this;
  46294. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  46295. //can only work if this camera has a rotation quaternion already.
  46296. if (!this.rotationQuaternion)
  46297. return;
  46298. if (!this._initialQuaternion) {
  46299. this._initialQuaternion = new BABYLON.Quaternion();
  46300. }
  46301. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  46302. ['x', 'y', 'z'].forEach(function (axisName) {
  46303. if (!axis[axisName]) {
  46304. _this._initialQuaternion[axisName] = 0;
  46305. }
  46306. else {
  46307. _this._initialQuaternion[axisName] *= -1;
  46308. }
  46309. });
  46310. this._initialQuaternion.normalize();
  46311. //force rotation update
  46312. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  46313. };
  46314. return DeviceOrientationCamera;
  46315. }(BABYLON.FreeCamera));
  46316. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  46317. })(BABYLON || (BABYLON = {}));
  46318. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  46319. var BABYLON;
  46320. (function (BABYLON) {
  46321. var VRDeviceOrientationFreeCamera = (function (_super) {
  46322. __extends(VRDeviceOrientationFreeCamera, _super);
  46323. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  46324. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46325. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46326. var _this = _super.call(this, name, position, scene) || this;
  46327. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46328. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46329. return _this;
  46330. }
  46331. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  46332. return "VRDeviceOrientationFreeCamera";
  46333. };
  46334. return VRDeviceOrientationFreeCamera;
  46335. }(BABYLON.DeviceOrientationCamera));
  46336. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  46337. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  46338. __extends(VRDeviceOrientationArcRotateCamera, _super);
  46339. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  46340. if (compensateDistortion === void 0) { compensateDistortion = true; }
  46341. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  46342. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  46343. vrCameraMetrics.compensateDistortion = compensateDistortion;
  46344. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  46345. _this.inputs.addVRDeviceOrientation();
  46346. return _this;
  46347. }
  46348. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  46349. return "VRDeviceOrientationArcRotateCamera";
  46350. };
  46351. return VRDeviceOrientationArcRotateCamera;
  46352. }(BABYLON.ArcRotateCamera));
  46353. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  46354. })(BABYLON || (BABYLON = {}));
  46355. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  46356. var BABYLON;
  46357. (function (BABYLON) {
  46358. // We're mainly based on the logic defined into the FreeCamera code
  46359. var UniversalCamera = (function (_super) {
  46360. __extends(UniversalCamera, _super);
  46361. //-- end properties for backward compatibility for inputs
  46362. function UniversalCamera(name, position, scene) {
  46363. var _this = _super.call(this, name, position, scene) || this;
  46364. _this.inputs.addGamepad();
  46365. return _this;
  46366. }
  46367. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  46368. //-- Begin properties for backward compatibility for inputs
  46369. get: function () {
  46370. var gamepad = this.inputs.attached["gamepad"];
  46371. if (gamepad)
  46372. return gamepad.gamepadAngularSensibility;
  46373. },
  46374. set: function (value) {
  46375. var gamepad = this.inputs.attached["gamepad"];
  46376. if (gamepad)
  46377. gamepad.gamepadAngularSensibility = value;
  46378. },
  46379. enumerable: true,
  46380. configurable: true
  46381. });
  46382. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  46383. get: function () {
  46384. var gamepad = this.inputs.attached["gamepad"];
  46385. if (gamepad)
  46386. return gamepad.gamepadMoveSensibility;
  46387. },
  46388. set: function (value) {
  46389. var gamepad = this.inputs.attached["gamepad"];
  46390. if (gamepad)
  46391. gamepad.gamepadMoveSensibility = value;
  46392. },
  46393. enumerable: true,
  46394. configurable: true
  46395. });
  46396. UniversalCamera.prototype.getClassName = function () {
  46397. return "UniversalCamera";
  46398. };
  46399. return UniversalCamera;
  46400. }(BABYLON.TouchCamera));
  46401. BABYLON.UniversalCamera = UniversalCamera;
  46402. })(BABYLON || (BABYLON = {}));
  46403. //# sourceMappingURL=babylon.universalCamera.js.map
  46404. var BABYLON;
  46405. (function (BABYLON) {
  46406. var Gamepads = (function () {
  46407. function Gamepads(ongamedpadconnected) {
  46408. var _this = this;
  46409. this.babylonGamepads = [];
  46410. this.oneGamepadConnected = false;
  46411. this.isMonitoring = false;
  46412. this.gamepadEventSupported = 'GamepadEvent' in window;
  46413. this.gamepadSupportAvailable = (navigator.getGamepads ||
  46414. !!navigator.webkitGetGamepads || !!navigator.msGetGamepads || !!navigator.webkitGamepads);
  46415. this._callbackGamepadConnected = ongamedpadconnected;
  46416. if (this.gamepadSupportAvailable) {
  46417. // Checking if the gamepad connected event is supported (like in Firefox)
  46418. if (this.gamepadEventSupported) {
  46419. this._onGamepadConnectedEvent = function (evt) {
  46420. _this._onGamepadConnected(evt);
  46421. };
  46422. this._onGamepadDisonnectedEvent = function (evt) {
  46423. _this._onGamepadDisconnected(evt);
  46424. };
  46425. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46426. window.addEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46427. }
  46428. else {
  46429. this._startMonitoringGamepads();
  46430. }
  46431. }
  46432. }
  46433. Gamepads.prototype.dispose = function () {
  46434. if (Gamepads.gamepadDOMInfo) {
  46435. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46436. }
  46437. if (this._onGamepadConnectedEvent) {
  46438. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  46439. window.removeEventListener('gamepaddisconnected', this._onGamepadDisonnectedEvent, false);
  46440. this._onGamepadConnectedEvent = null;
  46441. this._onGamepadDisonnectedEvent = null;
  46442. }
  46443. };
  46444. Gamepads.prototype._onGamepadConnected = function (evt) {
  46445. var newGamepad = this._addNewGamepad(evt.gamepad);
  46446. if (this._callbackGamepadConnected)
  46447. this._callbackGamepadConnected(newGamepad);
  46448. this._startMonitoringGamepads();
  46449. };
  46450. Gamepads.prototype._addNewGamepad = function (gamepad) {
  46451. if (!this.oneGamepadConnected) {
  46452. this.oneGamepadConnected = true;
  46453. if (Gamepads.gamepadDOMInfo) {
  46454. document.body.removeChild(Gamepads.gamepadDOMInfo);
  46455. Gamepads.gamepadDOMInfo = null;
  46456. }
  46457. }
  46458. var newGamepad;
  46459. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  46460. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  46461. newGamepad = new Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  46462. }
  46463. else {
  46464. newGamepad = new GenericPad(gamepad.id, gamepad.index, gamepad);
  46465. }
  46466. this.babylonGamepads.push(newGamepad);
  46467. return newGamepad;
  46468. };
  46469. Gamepads.prototype._onGamepadDisconnected = function (evt) {
  46470. // Remove the gamepad from the list of gamepads to monitor.
  46471. for (var i in this.babylonGamepads) {
  46472. if (this.babylonGamepads[i].index == evt.gamepad.index) {
  46473. this.babylonGamepads.splice(+i, 1);
  46474. break;
  46475. }
  46476. }
  46477. // If no gamepads are left, stop the polling loop.
  46478. if (this.babylonGamepads.length == 0) {
  46479. this._stopMonitoringGamepads();
  46480. }
  46481. };
  46482. Gamepads.prototype._startMonitoringGamepads = function () {
  46483. if (!this.isMonitoring) {
  46484. this.isMonitoring = true;
  46485. this._checkGamepadsStatus();
  46486. }
  46487. };
  46488. Gamepads.prototype._stopMonitoringGamepads = function () {
  46489. this.isMonitoring = false;
  46490. };
  46491. Gamepads.prototype._checkGamepadsStatus = function () {
  46492. var _this = this;
  46493. // updating gamepad objects
  46494. this._updateGamepadObjects();
  46495. for (var i in this.babylonGamepads) {
  46496. this.babylonGamepads[i].update();
  46497. }
  46498. if (this.isMonitoring) {
  46499. if (window.requestAnimationFrame) {
  46500. window.requestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46501. }
  46502. else if (window.mozRequestAnimationFrame) {
  46503. window.mozRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46504. }
  46505. else if (window.webkitRequestAnimationFrame) {
  46506. window.webkitRequestAnimationFrame(function () { _this._checkGamepadsStatus(); });
  46507. }
  46508. }
  46509. };
  46510. // This function is called only on Chrome, which does not yet support
  46511. // connection/disconnection events, but requires you to monitor
  46512. // an array for changes.
  46513. Gamepads.prototype._updateGamepadObjects = function () {
  46514. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  46515. for (var i = 0; i < gamepads.length; i++) {
  46516. if (gamepads[i]) {
  46517. if (!(gamepads[i].index in this.babylonGamepads)) {
  46518. var newGamepad = this._addNewGamepad(gamepads[i]);
  46519. if (this._callbackGamepadConnected) {
  46520. this._callbackGamepadConnected(newGamepad);
  46521. }
  46522. }
  46523. else {
  46524. this.babylonGamepads[i].browserGamepad = gamepads[i];
  46525. }
  46526. }
  46527. }
  46528. };
  46529. return Gamepads;
  46530. }());
  46531. BABYLON.Gamepads = Gamepads;
  46532. var StickValues = (function () {
  46533. function StickValues(x, y) {
  46534. this.x = x;
  46535. this.y = y;
  46536. }
  46537. return StickValues;
  46538. }());
  46539. BABYLON.StickValues = StickValues;
  46540. var Gamepad = (function () {
  46541. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  46542. if (leftStickX === void 0) { leftStickX = 0; }
  46543. if (leftStickY === void 0) { leftStickY = 1; }
  46544. if (rightStickX === void 0) { rightStickX = 2; }
  46545. if (rightStickY === void 0) { rightStickY = 3; }
  46546. this.id = id;
  46547. this.index = index;
  46548. this.browserGamepad = browserGamepad;
  46549. this._leftStickAxisX = leftStickX;
  46550. this._leftStickAxisY = leftStickY;
  46551. this._rightStickAxisX = rightStickX;
  46552. this._rightStickAxisY = rightStickY;
  46553. if (this.browserGamepad.axes.length >= 2) {
  46554. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46555. }
  46556. if (this.browserGamepad.axes.length >= 4) {
  46557. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46558. }
  46559. }
  46560. Gamepad.prototype.onleftstickchanged = function (callback) {
  46561. this._onleftstickchanged = callback;
  46562. };
  46563. Gamepad.prototype.onrightstickchanged = function (callback) {
  46564. this._onrightstickchanged = callback;
  46565. };
  46566. Object.defineProperty(Gamepad.prototype, "leftStick", {
  46567. get: function () {
  46568. return this._leftStick;
  46569. },
  46570. set: function (newValues) {
  46571. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  46572. this._onleftstickchanged(newValues);
  46573. }
  46574. this._leftStick = newValues;
  46575. },
  46576. enumerable: true,
  46577. configurable: true
  46578. });
  46579. Object.defineProperty(Gamepad.prototype, "rightStick", {
  46580. get: function () {
  46581. return this._rightStick;
  46582. },
  46583. set: function (newValues) {
  46584. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  46585. this._onrightstickchanged(newValues);
  46586. }
  46587. this._rightStick = newValues;
  46588. },
  46589. enumerable: true,
  46590. configurable: true
  46591. });
  46592. Gamepad.prototype.update = function () {
  46593. if (this._leftStick) {
  46594. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  46595. }
  46596. if (this._rightStick) {
  46597. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  46598. }
  46599. };
  46600. return Gamepad;
  46601. }());
  46602. BABYLON.Gamepad = Gamepad;
  46603. var GenericPad = (function (_super) {
  46604. __extends(GenericPad, _super);
  46605. function GenericPad(id, index, gamepad) {
  46606. var _this = _super.call(this, id, index, gamepad) || this;
  46607. _this.id = id;
  46608. _this.index = index;
  46609. _this.gamepad = gamepad;
  46610. _this._buttons = new Array(gamepad.buttons.length);
  46611. return _this;
  46612. }
  46613. GenericPad.prototype.onbuttondown = function (callback) {
  46614. this._onbuttondown = callback;
  46615. };
  46616. GenericPad.prototype.onbuttonup = function (callback) {
  46617. this._onbuttonup = callback;
  46618. };
  46619. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  46620. if (newValue !== currentValue) {
  46621. if (this._onbuttondown && newValue === 1) {
  46622. this._onbuttondown(buttonIndex);
  46623. }
  46624. if (this._onbuttonup && newValue === 0) {
  46625. this._onbuttonup(buttonIndex);
  46626. }
  46627. }
  46628. return newValue;
  46629. };
  46630. GenericPad.prototype.update = function () {
  46631. _super.prototype.update.call(this);
  46632. for (var index = 0; index < this._buttons.length; index++) {
  46633. this._buttons[index] = this._setButtonValue(this.gamepad.buttons[index].value, this._buttons[index], index);
  46634. }
  46635. };
  46636. return GenericPad;
  46637. }(Gamepad));
  46638. BABYLON.GenericPad = GenericPad;
  46639. var Xbox360Button;
  46640. (function (Xbox360Button) {
  46641. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  46642. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  46643. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  46644. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  46645. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  46646. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  46647. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  46648. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  46649. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  46650. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  46651. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  46652. var Xbox360Dpad;
  46653. (function (Xbox360Dpad) {
  46654. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  46655. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  46656. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  46657. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  46658. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  46659. var Xbox360Pad = (function (_super) {
  46660. __extends(Xbox360Pad, _super);
  46661. function Xbox360Pad(id, index, gamepad, xboxOne) {
  46662. if (xboxOne === void 0) { xboxOne = false; }
  46663. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  46664. _this._leftTrigger = 0;
  46665. _this._rightTrigger = 0;
  46666. _this._buttonA = 0;
  46667. _this._buttonB = 0;
  46668. _this._buttonX = 0;
  46669. _this._buttonY = 0;
  46670. _this._buttonBack = 0;
  46671. _this._buttonStart = 0;
  46672. _this._buttonLB = 0;
  46673. _this._buttonRB = 0;
  46674. _this._buttonLeftStick = 0;
  46675. _this._buttonRightStick = 0;
  46676. _this._dPadUp = 0;
  46677. _this._dPadDown = 0;
  46678. _this._dPadLeft = 0;
  46679. _this._dPadRight = 0;
  46680. _this._isXboxOnePad = false;
  46681. _this._isXboxOnePad = xboxOne;
  46682. return _this;
  46683. }
  46684. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  46685. this._onlefttriggerchanged = callback;
  46686. };
  46687. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  46688. this._onrighttriggerchanged = callback;
  46689. };
  46690. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  46691. get: function () {
  46692. return this._leftTrigger;
  46693. },
  46694. set: function (newValue) {
  46695. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  46696. this._onlefttriggerchanged(newValue);
  46697. }
  46698. this._leftTrigger = newValue;
  46699. },
  46700. enumerable: true,
  46701. configurable: true
  46702. });
  46703. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  46704. get: function () {
  46705. return this._rightTrigger;
  46706. },
  46707. set: function (newValue) {
  46708. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  46709. this._onrighttriggerchanged(newValue);
  46710. }
  46711. this._rightTrigger = newValue;
  46712. },
  46713. enumerable: true,
  46714. configurable: true
  46715. });
  46716. Xbox360Pad.prototype.onbuttondown = function (callback) {
  46717. this._onbuttondown = callback;
  46718. };
  46719. Xbox360Pad.prototype.onbuttonup = function (callback) {
  46720. this._onbuttonup = callback;
  46721. };
  46722. Xbox360Pad.prototype.ondpaddown = function (callback) {
  46723. this._ondpaddown = callback;
  46724. };
  46725. Xbox360Pad.prototype.ondpadup = function (callback) {
  46726. this._ondpadup = callback;
  46727. };
  46728. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  46729. if (newValue !== currentValue) {
  46730. if (this._onbuttondown && newValue === 1) {
  46731. this._onbuttondown(buttonType);
  46732. }
  46733. if (this._onbuttonup && newValue === 0) {
  46734. this._onbuttonup(buttonType);
  46735. }
  46736. }
  46737. return newValue;
  46738. };
  46739. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  46740. if (newValue !== currentValue) {
  46741. if (this._ondpaddown && newValue === 1) {
  46742. this._ondpaddown(buttonType);
  46743. }
  46744. if (this._ondpadup && newValue === 0) {
  46745. this._ondpadup(buttonType);
  46746. }
  46747. }
  46748. return newValue;
  46749. };
  46750. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  46751. get: function () {
  46752. return this._buttonA;
  46753. },
  46754. set: function (value) {
  46755. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  46756. },
  46757. enumerable: true,
  46758. configurable: true
  46759. });
  46760. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  46761. get: function () {
  46762. return this._buttonB;
  46763. },
  46764. set: function (value) {
  46765. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  46766. },
  46767. enumerable: true,
  46768. configurable: true
  46769. });
  46770. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  46771. get: function () {
  46772. return this._buttonX;
  46773. },
  46774. set: function (value) {
  46775. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  46776. },
  46777. enumerable: true,
  46778. configurable: true
  46779. });
  46780. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  46781. get: function () {
  46782. return this._buttonY;
  46783. },
  46784. set: function (value) {
  46785. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  46786. },
  46787. enumerable: true,
  46788. configurable: true
  46789. });
  46790. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  46791. get: function () {
  46792. return this._buttonStart;
  46793. },
  46794. set: function (value) {
  46795. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  46796. },
  46797. enumerable: true,
  46798. configurable: true
  46799. });
  46800. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  46801. get: function () {
  46802. return this._buttonBack;
  46803. },
  46804. set: function (value) {
  46805. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  46806. },
  46807. enumerable: true,
  46808. configurable: true
  46809. });
  46810. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  46811. get: function () {
  46812. return this._buttonLB;
  46813. },
  46814. set: function (value) {
  46815. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  46816. },
  46817. enumerable: true,
  46818. configurable: true
  46819. });
  46820. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  46821. get: function () {
  46822. return this._buttonRB;
  46823. },
  46824. set: function (value) {
  46825. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  46826. },
  46827. enumerable: true,
  46828. configurable: true
  46829. });
  46830. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  46831. get: function () {
  46832. return this._buttonLeftStick;
  46833. },
  46834. set: function (value) {
  46835. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  46836. },
  46837. enumerable: true,
  46838. configurable: true
  46839. });
  46840. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  46841. get: function () {
  46842. return this._buttonRightStick;
  46843. },
  46844. set: function (value) {
  46845. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  46846. },
  46847. enumerable: true,
  46848. configurable: true
  46849. });
  46850. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  46851. get: function () {
  46852. return this._dPadUp;
  46853. },
  46854. set: function (value) {
  46855. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  46856. },
  46857. enumerable: true,
  46858. configurable: true
  46859. });
  46860. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  46861. get: function () {
  46862. return this._dPadDown;
  46863. },
  46864. set: function (value) {
  46865. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  46866. },
  46867. enumerable: true,
  46868. configurable: true
  46869. });
  46870. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  46871. get: function () {
  46872. return this._dPadLeft;
  46873. },
  46874. set: function (value) {
  46875. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  46876. },
  46877. enumerable: true,
  46878. configurable: true
  46879. });
  46880. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  46881. get: function () {
  46882. return this._dPadRight;
  46883. },
  46884. set: function (value) {
  46885. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  46886. },
  46887. enumerable: true,
  46888. configurable: true
  46889. });
  46890. Xbox360Pad.prototype.update = function () {
  46891. _super.prototype.update.call(this);
  46892. if (this._isXboxOnePad) {
  46893. this.buttonA = this.browserGamepad.buttons[0].value;
  46894. this.buttonB = this.browserGamepad.buttons[1].value;
  46895. this.buttonX = this.browserGamepad.buttons[2].value;
  46896. this.buttonY = this.browserGamepad.buttons[3].value;
  46897. this.buttonLB = this.browserGamepad.buttons[4].value;
  46898. this.buttonRB = this.browserGamepad.buttons[5].value;
  46899. this.leftTrigger = this.browserGamepad.axes[2];
  46900. this.rightTrigger = this.browserGamepad.axes[5];
  46901. this.buttonBack = this.browserGamepad.buttons[9].value;
  46902. this.buttonStart = this.browserGamepad.buttons[8].value;
  46903. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  46904. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  46905. this.dPadUp = this.browserGamepad.buttons[11].value;
  46906. this.dPadDown = this.browserGamepad.buttons[12].value;
  46907. this.dPadLeft = this.browserGamepad.buttons[13].value;
  46908. this.dPadRight = this.browserGamepad.buttons[14].value;
  46909. }
  46910. else {
  46911. this.buttonA = this.browserGamepad.buttons[0].value;
  46912. this.buttonB = this.browserGamepad.buttons[1].value;
  46913. this.buttonX = this.browserGamepad.buttons[2].value;
  46914. this.buttonY = this.browserGamepad.buttons[3].value;
  46915. this.buttonLB = this.browserGamepad.buttons[4].value;
  46916. this.buttonRB = this.browserGamepad.buttons[5].value;
  46917. this.leftTrigger = this.browserGamepad.buttons[6].value;
  46918. this.rightTrigger = this.browserGamepad.buttons[7].value;
  46919. this.buttonBack = this.browserGamepad.buttons[8].value;
  46920. this.buttonStart = this.browserGamepad.buttons[9].value;
  46921. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  46922. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  46923. this.dPadUp = this.browserGamepad.buttons[12].value;
  46924. this.dPadDown = this.browserGamepad.buttons[13].value;
  46925. this.dPadLeft = this.browserGamepad.buttons[14].value;
  46926. this.dPadRight = this.browserGamepad.buttons[15].value;
  46927. }
  46928. };
  46929. return Xbox360Pad;
  46930. }(Gamepad));
  46931. BABYLON.Xbox360Pad = Xbox360Pad;
  46932. })(BABYLON || (BABYLON = {}));
  46933. //# sourceMappingURL=babylon.gamepads.js.map
  46934. var BABYLON;
  46935. (function (BABYLON) {
  46936. // We're mainly based on the logic defined into the FreeCamera code
  46937. var GamepadCamera = (function (_super) {
  46938. __extends(GamepadCamera, _super);
  46939. //-- end properties for backward compatibility for inputs
  46940. function GamepadCamera(name, position, scene) {
  46941. var _this;
  46942. BABYLON.Tools.Warn("Deprecated. Please use Universal Camera instead.");
  46943. _this = _super.call(this, name, position, scene) || this;
  46944. return _this;
  46945. }
  46946. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  46947. //-- Begin properties for backward compatibility for inputs
  46948. get: function () {
  46949. var gamepad = this.inputs.attached["gamepad"];
  46950. if (gamepad)
  46951. return gamepad.gamepadAngularSensibility;
  46952. },
  46953. set: function (value) {
  46954. var gamepad = this.inputs.attached["gamepad"];
  46955. if (gamepad)
  46956. gamepad.gamepadAngularSensibility = value;
  46957. },
  46958. enumerable: true,
  46959. configurable: true
  46960. });
  46961. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  46962. get: function () {
  46963. var gamepad = this.inputs.attached["gamepad"];
  46964. if (gamepad)
  46965. return gamepad.gamepadMoveSensibility;
  46966. },
  46967. set: function (value) {
  46968. var gamepad = this.inputs.attached["gamepad"];
  46969. if (gamepad)
  46970. gamepad.gamepadMoveSensibility = value;
  46971. },
  46972. enumerable: true,
  46973. configurable: true
  46974. });
  46975. GamepadCamera.prototype.getClassName = function () {
  46976. return "GamepadCamera";
  46977. };
  46978. return GamepadCamera;
  46979. }(BABYLON.UniversalCamera));
  46980. BABYLON.GamepadCamera = GamepadCamera;
  46981. })(BABYLON || (BABYLON = {}));
  46982. //# sourceMappingURL=babylon.gamepadCamera.js.map
  46983. var BABYLON;
  46984. (function (BABYLON) {
  46985. var Analyser = (function () {
  46986. function Analyser(scene) {
  46987. this.SMOOTHING = 0.75;
  46988. this.FFT_SIZE = 512;
  46989. this.BARGRAPHAMPLITUDE = 256;
  46990. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  46991. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  46992. this._scene = scene;
  46993. this._audioEngine = BABYLON.Engine.audioEngine;
  46994. if (this._audioEngine.canUseWebAudio) {
  46995. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  46996. this._webAudioAnalyser.minDecibels = -140;
  46997. this._webAudioAnalyser.maxDecibels = 0;
  46998. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  46999. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  47000. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  47001. }
  47002. }
  47003. Analyser.prototype.getFrequencyBinCount = function () {
  47004. if (this._audioEngine.canUseWebAudio) {
  47005. return this._webAudioAnalyser.frequencyBinCount;
  47006. }
  47007. else {
  47008. return 0;
  47009. }
  47010. };
  47011. Analyser.prototype.getByteFrequencyData = function () {
  47012. if (this._audioEngine.canUseWebAudio) {
  47013. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47014. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47015. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  47016. }
  47017. return this._byteFreqs;
  47018. };
  47019. Analyser.prototype.getByteTimeDomainData = function () {
  47020. if (this._audioEngine.canUseWebAudio) {
  47021. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47022. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47023. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  47024. }
  47025. return this._byteTime;
  47026. };
  47027. Analyser.prototype.getFloatFrequencyData = function () {
  47028. if (this._audioEngine.canUseWebAudio) {
  47029. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  47030. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  47031. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  47032. }
  47033. return this._floatFreqs;
  47034. };
  47035. Analyser.prototype.drawDebugCanvas = function () {
  47036. var _this = this;
  47037. if (this._audioEngine.canUseWebAudio) {
  47038. if (!this._debugCanvas) {
  47039. this._debugCanvas = document.createElement("canvas");
  47040. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  47041. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  47042. this._debugCanvas.style.position = "absolute";
  47043. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  47044. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  47045. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  47046. document.body.appendChild(this._debugCanvas);
  47047. this._registerFunc = function () {
  47048. _this.drawDebugCanvas();
  47049. };
  47050. this._scene.registerBeforeRender(this._registerFunc);
  47051. }
  47052. if (this._registerFunc) {
  47053. var workingArray = this.getByteFrequencyData();
  47054. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  47055. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  47056. // Draw the frequency domain chart.
  47057. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  47058. var value = workingArray[i];
  47059. var percent = value / this.BARGRAPHAMPLITUDE;
  47060. var height = this.DEBUGCANVASSIZE.height * percent;
  47061. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  47062. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  47063. var hue = i / this.getFrequencyBinCount() * 360;
  47064. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  47065. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  47066. }
  47067. }
  47068. }
  47069. };
  47070. Analyser.prototype.stopDebugCanvas = function () {
  47071. if (this._debugCanvas) {
  47072. this._scene.unregisterBeforeRender(this._registerFunc);
  47073. this._registerFunc = null;
  47074. document.body.removeChild(this._debugCanvas);
  47075. this._debugCanvas = null;
  47076. this._debugCanvasContext = null;
  47077. }
  47078. };
  47079. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  47080. if (this._audioEngine.canUseWebAudio) {
  47081. inputAudioNode.connect(this._webAudioAnalyser);
  47082. this._webAudioAnalyser.connect(outputAudioNode);
  47083. }
  47084. };
  47085. Analyser.prototype.dispose = function () {
  47086. if (this._audioEngine.canUseWebAudio) {
  47087. this._webAudioAnalyser.disconnect();
  47088. }
  47089. };
  47090. return Analyser;
  47091. }());
  47092. BABYLON.Analyser = Analyser;
  47093. })(BABYLON || (BABYLON = {}));
  47094. //# sourceMappingURL=babylon.analyser.js.map
  47095. var BABYLON;
  47096. (function (BABYLON) {
  47097. var DepthRenderer = (function () {
  47098. function DepthRenderer(scene, type) {
  47099. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  47100. var _this = this;
  47101. this._viewMatrix = BABYLON.Matrix.Zero();
  47102. this._projectionMatrix = BABYLON.Matrix.Zero();
  47103. this._transformMatrix = BABYLON.Matrix.Zero();
  47104. this._worldViewProjection = BABYLON.Matrix.Zero();
  47105. this._scene = scene;
  47106. var engine = scene.getEngine();
  47107. // Render target
  47108. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  47109. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47110. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47111. this._depthMap.refreshRate = 1;
  47112. this._depthMap.renderParticles = false;
  47113. this._depthMap.renderList = null;
  47114. // set default depth value to 1.0 (far away)
  47115. this._depthMap.onClearObservable.add(function (engine) {
  47116. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  47117. });
  47118. // Custom render function
  47119. var renderSubMesh = function (subMesh) {
  47120. var mesh = subMesh.getRenderingMesh();
  47121. var scene = _this._scene;
  47122. var engine = scene.getEngine();
  47123. // Culling
  47124. engine.setState(subMesh.getMaterial().backFaceCulling);
  47125. // Managing instances
  47126. var batch = mesh._getInstancesRenderList(subMesh._id);
  47127. if (batch.mustReturn) {
  47128. return;
  47129. }
  47130. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47131. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47132. engine.enableEffect(_this._effect);
  47133. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  47134. var material = subMesh.getMaterial();
  47135. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  47136. _this._effect.setFloat("far", scene.activeCamera.maxZ);
  47137. // Alpha test
  47138. if (material && material.needAlphaTesting()) {
  47139. var alphaTexture = material.getAlphaTestTexture();
  47140. _this._effect.setTexture("diffuseSampler", alphaTexture);
  47141. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47142. }
  47143. // Bones
  47144. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47145. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47146. }
  47147. // Draw
  47148. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47149. }
  47150. };
  47151. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  47152. var index;
  47153. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47154. renderSubMesh(opaqueSubMeshes.data[index]);
  47155. }
  47156. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47157. renderSubMesh(alphaTestSubMeshes.data[index]);
  47158. }
  47159. };
  47160. }
  47161. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  47162. var material = subMesh.getMaterial();
  47163. if (material.disableDepthWrite) {
  47164. return false;
  47165. }
  47166. var defines = [];
  47167. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47168. var mesh = subMesh.getMesh();
  47169. var scene = mesh.getScene();
  47170. // Alpha test
  47171. if (material && material.needAlphaTesting()) {
  47172. defines.push("#define ALPHATEST");
  47173. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47174. attribs.push(BABYLON.VertexBuffer.UVKind);
  47175. defines.push("#define UV1");
  47176. }
  47177. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47178. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47179. defines.push("#define UV2");
  47180. }
  47181. }
  47182. // Bones
  47183. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47184. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47185. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47186. if (mesh.numBoneInfluencers > 4) {
  47187. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47188. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47189. }
  47190. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47191. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47192. }
  47193. else {
  47194. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47195. }
  47196. // Instances
  47197. if (useInstances) {
  47198. defines.push("#define INSTANCES");
  47199. attribs.push("world0");
  47200. attribs.push("world1");
  47201. attribs.push("world2");
  47202. attribs.push("world3");
  47203. }
  47204. // Get correct effect
  47205. var join = defines.join("\n");
  47206. if (this._cachedDefines !== join) {
  47207. this._cachedDefines = join;
  47208. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "far"], ["diffuseSampler"], join);
  47209. }
  47210. return this._effect.isReady();
  47211. };
  47212. DepthRenderer.prototype.getDepthMap = function () {
  47213. return this._depthMap;
  47214. };
  47215. // Methods
  47216. DepthRenderer.prototype.dispose = function () {
  47217. this._depthMap.dispose();
  47218. };
  47219. return DepthRenderer;
  47220. }());
  47221. BABYLON.DepthRenderer = DepthRenderer;
  47222. })(BABYLON || (BABYLON = {}));
  47223. //# sourceMappingURL=babylon.depthRenderer.js.map
  47224. var BABYLON;
  47225. (function (BABYLON) {
  47226. var SSAORenderingPipeline = (function (_super) {
  47227. __extends(SSAORenderingPipeline, _super);
  47228. /**
  47229. * @constructor
  47230. * @param {string} name - The rendering pipeline name
  47231. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47232. * @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 }
  47233. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47234. */
  47235. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  47236. var _this = _super.call(this, scene.getEngine(), name) || this;
  47237. // Members
  47238. /**
  47239. * The PassPostProcess id in the pipeline that contains the original scene color
  47240. * @type {string}
  47241. */
  47242. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  47243. /**
  47244. * The SSAO PostProcess id in the pipeline
  47245. * @type {string}
  47246. */
  47247. _this.SSAORenderEffect = "SSAORenderEffect";
  47248. /**
  47249. * The horizontal blur PostProcess id in the pipeline
  47250. * @type {string}
  47251. */
  47252. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  47253. /**
  47254. * The vertical blur PostProcess id in the pipeline
  47255. * @type {string}
  47256. */
  47257. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  47258. /**
  47259. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  47260. * @type {string}
  47261. */
  47262. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  47263. /**
  47264. * The output strength of the SSAO post-process. Default value is 1.0.
  47265. * @type {number}
  47266. */
  47267. _this.totalStrength = 1.0;
  47268. /**
  47269. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  47270. * @type {number}
  47271. */
  47272. _this.radius = 0.0001;
  47273. /**
  47274. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  47275. * Must not be equal to fallOff and superior to fallOff.
  47276. * Default value is 0.975
  47277. * @type {number}
  47278. */
  47279. _this.area = 0.0075;
  47280. /**
  47281. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  47282. * Must not be equal to area and inferior to area.
  47283. * Default value is 0.0
  47284. * @type {number}
  47285. */
  47286. _this.fallOff = 0.000001;
  47287. /**
  47288. * The base color of the SSAO post-process
  47289. * The final result is "base + ssao" between [0, 1]
  47290. * @type {number}
  47291. */
  47292. _this.base = 0.5;
  47293. _this._firstUpdate = true;
  47294. _this._scene = scene;
  47295. // Set up assets
  47296. _this._createRandomTexture();
  47297. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47298. var ssaoRatio = ratio.ssaoRatio || ratio;
  47299. var combineRatio = ratio.combineRatio || ratio;
  47300. _this._ratio = {
  47301. ssaoRatio: ssaoRatio,
  47302. combineRatio: combineRatio
  47303. };
  47304. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  47305. _this._createSSAOPostProcess(ssaoRatio);
  47306. _this._createBlurPostProcess(ssaoRatio);
  47307. _this._createSSAOCombinePostProcess(combineRatio);
  47308. // Set up pipeline
  47309. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  47310. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  47311. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  47312. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  47313. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  47314. // Finish
  47315. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47316. if (cameras)
  47317. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47318. return _this;
  47319. }
  47320. // Public Methods
  47321. /**
  47322. * Returns the horizontal blur PostProcess
  47323. * @return {BABYLON.BlurPostProcess} The horizontal blur post-process
  47324. */
  47325. SSAORenderingPipeline.prototype.getBlurHPostProcess = function () {
  47326. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurHPostProcess() is deprecated, no more blur post-process exists");
  47327. return null;
  47328. };
  47329. /**
  47330. * Returns the vertical blur PostProcess
  47331. * @return {BABYLON.BlurPostProcess} The vertical blur post-process
  47332. */
  47333. SSAORenderingPipeline.prototype.getBlurVPostProcess = function () {
  47334. BABYLON.Tools.Error("SSAORenderinPipeline.getBlurVPostProcess() is deprecated, no more blur post-process exists");
  47335. return null;
  47336. };
  47337. /**
  47338. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  47339. */
  47340. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47341. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47342. for (var i = 0; i < this._scene.cameras.length; i++) {
  47343. var camera = this._scene.cameras[i];
  47344. this._originalColorPostProcess.dispose(camera);
  47345. this._ssaoPostProcess.dispose(camera);
  47346. this._blurHPostProcess.dispose(camera);
  47347. this._blurVPostProcess.dispose(camera);
  47348. this._ssaoCombinePostProcess.dispose(camera);
  47349. }
  47350. this._randomTexture.dispose();
  47351. if (disableDepthRender)
  47352. this._scene.disableDepthRenderer();
  47353. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47354. };
  47355. // Private Methods
  47356. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  47357. var _this = this;
  47358. /*
  47359. var samplerOffsets = [
  47360. -8.0, -6.0, -4.0, -2.0,
  47361. 0.0,
  47362. 2.0, 4.0, 6.0, 8.0
  47363. ];
  47364. */
  47365. var samples = 16;
  47366. var samplerOffsets = [];
  47367. for (var i = -8; i < 8; i++) {
  47368. samplerOffsets.push(i * 2);
  47369. }
  47370. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16");
  47371. this._blurHPostProcess.onApply = function (effect) {
  47372. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  47373. effect.setTexture("depthSampler", _this._depthTexture);
  47374. if (_this._firstUpdate) {
  47375. effect.setArray("samplerOffsets", samplerOffsets);
  47376. }
  47377. };
  47378. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao", ["outSize", "samplerOffsets"], ["depthSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define SAMPLES 16");
  47379. this._blurVPostProcess.onApply = function (effect) {
  47380. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  47381. effect.setTexture("depthSampler", _this._depthTexture);
  47382. if (_this._firstUpdate) {
  47383. effect.setArray("samplerOffsets", samplerOffsets);
  47384. _this._firstUpdate = false;
  47385. }
  47386. };
  47387. };
  47388. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  47389. var _this = this;
  47390. var numSamples = 16;
  47391. var sampleSphere = [
  47392. 0.5381, 0.1856, -0.4319,
  47393. 0.1379, 0.2486, 0.4430,
  47394. 0.3371, 0.5679, -0.0057,
  47395. -0.6999, -0.0451, -0.0019,
  47396. 0.0689, -0.1598, -0.8547,
  47397. 0.0560, 0.0069, -0.1843,
  47398. -0.0146, 0.1402, 0.0762,
  47399. 0.0100, -0.1924, -0.0344,
  47400. -0.3577, -0.5301, -0.4358,
  47401. -0.3169, 0.1063, 0.0158,
  47402. 0.0103, -0.5869, 0.0046,
  47403. -0.0897, -0.4940, 0.3287,
  47404. 0.7119, -0.0154, -0.0918,
  47405. -0.0533, 0.0596, -0.5411,
  47406. 0.0352, -0.0631, 0.5460,
  47407. -0.4776, 0.2847, -0.0271
  47408. ];
  47409. var samplesFactor = 1.0 / numSamples;
  47410. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  47411. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  47412. "area", "fallOff", "base", "range", "viewport"
  47413. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  47414. var viewport = new BABYLON.Vector2(0, 0);
  47415. this._ssaoPostProcess.onApply = function (effect) {
  47416. if (_this._firstUpdate) {
  47417. effect.setArray3("sampleSphere", sampleSphere);
  47418. effect.setFloat("samplesFactor", samplesFactor);
  47419. effect.setFloat("randTextureTiles", 4.0);
  47420. }
  47421. effect.setFloat("totalStrength", _this.totalStrength);
  47422. effect.setFloat("radius", _this.radius);
  47423. effect.setFloat("area", _this.area);
  47424. effect.setFloat("fallOff", _this.fallOff);
  47425. effect.setFloat("base", _this.base);
  47426. effect.setTexture("textureSampler", _this._depthTexture);
  47427. effect.setTexture("randomSampler", _this._randomTexture);
  47428. };
  47429. };
  47430. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  47431. var _this = this;
  47432. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47433. this._ssaoCombinePostProcess.onApply = function (effect) {
  47434. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  47435. };
  47436. };
  47437. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  47438. var size = 512;
  47439. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  47440. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  47441. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  47442. var context = this._randomTexture.getContext();
  47443. var rand = function (min, max) {
  47444. return Math.random() * (max - min) + min;
  47445. };
  47446. var randVector = BABYLON.Vector3.Zero();
  47447. for (var x = 0; x < size; x++) {
  47448. for (var y = 0; y < size; y++) {
  47449. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  47450. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  47451. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  47452. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  47453. context.fillRect(x, y, 1, 1);
  47454. }
  47455. }
  47456. this._randomTexture.update(false);
  47457. };
  47458. return SSAORenderingPipeline;
  47459. }(BABYLON.PostProcessRenderPipeline));
  47460. __decorate([
  47461. BABYLON.serialize()
  47462. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  47463. __decorate([
  47464. BABYLON.serialize()
  47465. ], SSAORenderingPipeline.prototype, "radius", void 0);
  47466. __decorate([
  47467. BABYLON.serialize()
  47468. ], SSAORenderingPipeline.prototype, "area", void 0);
  47469. __decorate([
  47470. BABYLON.serialize()
  47471. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  47472. __decorate([
  47473. BABYLON.serialize()
  47474. ], SSAORenderingPipeline.prototype, "base", void 0);
  47475. __decorate([
  47476. BABYLON.serialize()
  47477. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  47478. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  47479. })(BABYLON || (BABYLON = {}));
  47480. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  47481. var BABYLON;
  47482. (function (BABYLON) {
  47483. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  47484. var VolumetricLightScatteringPostProcess = (function (_super) {
  47485. __extends(VolumetricLightScatteringPostProcess, _super);
  47486. /**
  47487. * @constructor
  47488. * @param {string} name - The post-process name
  47489. * @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)
  47490. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  47491. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  47492. * @param {number} samples - The post-process quality, default 100
  47493. * @param {number} samplingMode - The post-process filtering mode
  47494. * @param {BABYLON.Engine} engine - The babylon engine
  47495. * @param {boolean} reusable - If the post-process is reusable
  47496. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  47497. */
  47498. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  47499. if (samples === void 0) { samples = 100; }
  47500. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  47501. var _this = _super.call(this, name, "volumetricLightScattering", ["decay", "exposure", "weight", "meshPositionOnScreen", "density"], ["lightScatteringSampler"], ratio.postProcessRatio || ratio, camera, samplingMode, engine, reusable, "#define NUM_SAMPLES " + samples) || this;
  47502. _this._screenCoordinates = BABYLON.Vector2.Zero();
  47503. /**
  47504. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  47505. * @type {Vector3}
  47506. */
  47507. _this.customMeshPosition = BABYLON.Vector3.Zero();
  47508. /**
  47509. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  47510. * @type {boolean}
  47511. */
  47512. _this.useCustomMeshPosition = false;
  47513. /**
  47514. * If the post-process should inverse the light scattering direction
  47515. * @type {boolean}
  47516. */
  47517. _this.invert = true;
  47518. /**
  47519. * Array containing the excluded meshes not rendered in the internal pass
  47520. */
  47521. _this.excludedMeshes = new Array();
  47522. /**
  47523. * Controls the overall intensity of the post-process
  47524. * @type {number}
  47525. */
  47526. _this.exposure = 0.3;
  47527. /**
  47528. * Dissipates each sample's contribution in range [0, 1]
  47529. * @type {number}
  47530. */
  47531. _this.decay = 0.96815;
  47532. /**
  47533. * Controls the overall intensity of each sample
  47534. * @type {number}
  47535. */
  47536. _this.weight = 0.58767;
  47537. /**
  47538. * Controls the density of each sample
  47539. * @type {number}
  47540. */
  47541. _this.density = 0.926;
  47542. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  47543. var engine = scene.getEngine();
  47544. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  47545. // Configure mesh
  47546. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  47547. // Configure
  47548. _this._createPass(scene, ratio.passRatio || ratio);
  47549. _this.onActivate = function (camera) {
  47550. if (!_this.isSupported) {
  47551. _this.dispose(camera);
  47552. }
  47553. _this.onActivate = null;
  47554. };
  47555. _this.onApplyObservable.add(function (effect) {
  47556. _this._updateMeshScreenCoordinates(scene);
  47557. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  47558. effect.setFloat("exposure", _this.exposure);
  47559. effect.setFloat("decay", _this.decay);
  47560. effect.setFloat("weight", _this.weight);
  47561. effect.setFloat("density", _this.density);
  47562. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  47563. });
  47564. return _this;
  47565. }
  47566. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  47567. get: function () {
  47568. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47569. return false;
  47570. },
  47571. set: function (useDiffuseColor) {
  47572. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  47573. },
  47574. enumerable: true,
  47575. configurable: true
  47576. });
  47577. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  47578. var mesh = subMesh.getMesh();
  47579. // Render this.mesh as default
  47580. if (mesh === this.mesh) {
  47581. return mesh.material.isReady(mesh);
  47582. }
  47583. var defines = [];
  47584. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47585. var material = subMesh.getMaterial();
  47586. var needUV = false;
  47587. // Alpha test
  47588. if (material) {
  47589. if (material.needAlphaTesting()) {
  47590. defines.push("#define ALPHATEST");
  47591. }
  47592. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47593. attribs.push(BABYLON.VertexBuffer.UVKind);
  47594. defines.push("#define UV1");
  47595. }
  47596. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47597. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47598. defines.push("#define UV2");
  47599. }
  47600. }
  47601. // Bones
  47602. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47603. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47604. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47605. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47606. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47607. }
  47608. else {
  47609. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47610. }
  47611. // Instances
  47612. if (useInstances) {
  47613. defines.push("#define INSTANCES");
  47614. attribs.push("world0");
  47615. attribs.push("world1");
  47616. attribs.push("world2");
  47617. attribs.push("world3");
  47618. }
  47619. // Get correct effect
  47620. var join = defines.join("\n");
  47621. if (this._cachedDefines !== join) {
  47622. this._cachedDefines = join;
  47623. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  47624. }
  47625. return this._volumetricLightScatteringPass.isReady();
  47626. };
  47627. /**
  47628. * Sets the new light position for light scattering effect
  47629. * @param {BABYLON.Vector3} The new custom light position
  47630. */
  47631. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  47632. this.customMeshPosition = position;
  47633. };
  47634. /**
  47635. * Returns the light position for light scattering effect
  47636. * @return {BABYLON.Vector3} The custom light position
  47637. */
  47638. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  47639. return this.customMeshPosition;
  47640. };
  47641. /**
  47642. * Disposes the internal assets and detaches the post-process from the camera
  47643. */
  47644. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  47645. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  47646. if (rttIndex !== -1) {
  47647. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  47648. }
  47649. this._volumetricLightScatteringRTT.dispose();
  47650. _super.prototype.dispose.call(this, camera);
  47651. };
  47652. /**
  47653. * Returns the render target texture used by the post-process
  47654. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  47655. */
  47656. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  47657. return this._volumetricLightScatteringRTT;
  47658. };
  47659. // Private methods
  47660. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  47661. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  47662. return true;
  47663. }
  47664. return false;
  47665. };
  47666. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  47667. var _this = this;
  47668. var engine = scene.getEngine();
  47669. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  47670. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47671. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  47672. this._volumetricLightScatteringRTT.renderList = null;
  47673. this._volumetricLightScatteringRTT.renderParticles = false;
  47674. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  47675. // Custom render function for submeshes
  47676. var renderSubMesh = function (subMesh) {
  47677. var mesh = subMesh.getRenderingMesh();
  47678. if (_this._meshExcluded(mesh)) {
  47679. return;
  47680. }
  47681. var scene = mesh.getScene();
  47682. var engine = scene.getEngine();
  47683. // Culling
  47684. engine.setState(subMesh.getMaterial().backFaceCulling);
  47685. // Managing instances
  47686. var batch = mesh._getInstancesRenderList(subMesh._id);
  47687. if (batch.mustReturn) {
  47688. return;
  47689. }
  47690. var hardwareInstancedRendering = (engine.getCaps().instancedArrays !== null) && (batch.visibleInstances[subMesh._id] !== null);
  47691. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  47692. var effect = _this._volumetricLightScatteringPass;
  47693. if (mesh === _this.mesh) {
  47694. effect = subMesh.getMaterial().getEffect();
  47695. }
  47696. engine.enableEffect(effect);
  47697. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  47698. if (mesh === _this.mesh) {
  47699. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  47700. }
  47701. else {
  47702. var material = subMesh.getMaterial();
  47703. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  47704. // Alpha test
  47705. if (material && material.needAlphaTesting()) {
  47706. var alphaTexture = material.getAlphaTestTexture();
  47707. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  47708. if (alphaTexture) {
  47709. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  47710. }
  47711. }
  47712. // Bones
  47713. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47714. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47715. }
  47716. }
  47717. // Draw
  47718. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  47719. }
  47720. };
  47721. // Render target texture callbacks
  47722. var savedSceneClearColor;
  47723. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  47724. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  47725. savedSceneClearColor = scene.clearColor;
  47726. scene.clearColor = sceneClearColor;
  47727. });
  47728. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  47729. scene.clearColor = savedSceneClearColor;
  47730. });
  47731. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  47732. var engine = scene.getEngine();
  47733. var index;
  47734. for (index = 0; index < opaqueSubMeshes.length; index++) {
  47735. renderSubMesh(opaqueSubMeshes.data[index]);
  47736. }
  47737. engine.setAlphaTesting(true);
  47738. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  47739. renderSubMesh(alphaTestSubMeshes.data[index]);
  47740. }
  47741. engine.setAlphaTesting(false);
  47742. if (transparentSubMeshes.length) {
  47743. // Sort sub meshes
  47744. for (index = 0; index < transparentSubMeshes.length; index++) {
  47745. var submesh = transparentSubMeshes.data[index];
  47746. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  47747. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  47748. }
  47749. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  47750. sortedArray.sort(function (a, b) {
  47751. // Alpha index first
  47752. if (a._alphaIndex > b._alphaIndex) {
  47753. return 1;
  47754. }
  47755. if (a._alphaIndex < b._alphaIndex) {
  47756. return -1;
  47757. }
  47758. // Then distance to camera
  47759. if (a._distanceToCamera < b._distanceToCamera) {
  47760. return 1;
  47761. }
  47762. if (a._distanceToCamera > b._distanceToCamera) {
  47763. return -1;
  47764. }
  47765. return 0;
  47766. });
  47767. // Render sub meshes
  47768. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  47769. for (index = 0; index < sortedArray.length; index++) {
  47770. renderSubMesh(sortedArray[index]);
  47771. }
  47772. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  47773. }
  47774. };
  47775. };
  47776. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  47777. var transform = scene.getTransformMatrix();
  47778. var meshPosition;
  47779. if (this.useCustomMeshPosition) {
  47780. meshPosition = this.customMeshPosition;
  47781. }
  47782. else if (this.attachedNode) {
  47783. meshPosition = this.attachedNode.position;
  47784. }
  47785. else {
  47786. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  47787. }
  47788. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  47789. this._screenCoordinates.x = pos.x / this._viewPort.width;
  47790. this._screenCoordinates.y = pos.y / this._viewPort.height;
  47791. if (this.invert)
  47792. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  47793. };
  47794. // Static methods
  47795. /**
  47796. * Creates a default mesh for the Volumeric Light Scattering post-process
  47797. * @param {string} The mesh name
  47798. * @param {BABYLON.Scene} The scene where to create the mesh
  47799. * @return {BABYLON.Mesh} the default mesh
  47800. */
  47801. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  47802. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  47803. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  47804. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  47805. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  47806. mesh.material = material;
  47807. return mesh;
  47808. };
  47809. return VolumetricLightScatteringPostProcess;
  47810. }(BABYLON.PostProcess));
  47811. __decorate([
  47812. BABYLON.serializeAsVector3()
  47813. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  47814. __decorate([
  47815. BABYLON.serialize()
  47816. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  47817. __decorate([
  47818. BABYLON.serialize()
  47819. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  47820. __decorate([
  47821. BABYLON.serializeAsMeshReference()
  47822. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  47823. __decorate([
  47824. BABYLON.serialize()
  47825. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  47826. __decorate([
  47827. BABYLON.serialize()
  47828. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  47829. __decorate([
  47830. BABYLON.serialize()
  47831. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  47832. __decorate([
  47833. BABYLON.serialize()
  47834. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  47835. __decorate([
  47836. BABYLON.serialize()
  47837. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  47838. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  47839. })(BABYLON || (BABYLON = {}));
  47840. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  47841. // BABYLON.JS Chromatic Aberration GLSL Shader
  47842. // Author: Olivier Guyot
  47843. // Separates very slightly R, G and B colors on the edges of the screen
  47844. // Inspired by Francois Tarlier & Martins Upitis
  47845. var BABYLON;
  47846. (function (BABYLON) {
  47847. var LensRenderingPipeline = (function (_super) {
  47848. __extends(LensRenderingPipeline, _super);
  47849. /**
  47850. * @constructor
  47851. *
  47852. * Effect parameters are as follow:
  47853. * {
  47854. * chromatic_aberration: number; // from 0 to x (1 for realism)
  47855. * edge_blur: number; // from 0 to x (1 for realism)
  47856. * distortion: number; // from 0 to x (1 for realism)
  47857. * grain_amount: number; // from 0 to 1
  47858. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  47859. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  47860. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  47861. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  47862. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  47863. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  47864. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  47865. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  47866. * }
  47867. * Note: if an effect parameter is unset, effect is disabled
  47868. *
  47869. * @param {string} name - The rendering pipeline name
  47870. * @param {object} parameters - An object containing all parameters (see above)
  47871. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  47872. * @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)
  47873. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  47874. */
  47875. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  47876. if (ratio === void 0) { ratio = 1.0; }
  47877. var _this = _super.call(this, scene.getEngine(), name) || this;
  47878. // Lens effects can be of the following:
  47879. // - chromatic aberration (slight shift of RGB colors)
  47880. // - blur on the edge of the lens
  47881. // - lens distortion
  47882. // - depth-of-field blur & highlights enhancing
  47883. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  47884. // - grain effect (noise or custom texture)
  47885. // Two additional texture samplers are needed:
  47886. // - depth map (for depth-of-field)
  47887. // - grain texture
  47888. /**
  47889. * The chromatic aberration PostProcess id in the pipeline
  47890. * @type {string}
  47891. */
  47892. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  47893. /**
  47894. * The highlights enhancing PostProcess id in the pipeline
  47895. * @type {string}
  47896. */
  47897. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  47898. /**
  47899. * The depth-of-field PostProcess id in the pipeline
  47900. * @type {string}
  47901. */
  47902. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  47903. _this._scene = scene;
  47904. // Fetch texture samplers
  47905. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  47906. if (parameters.grain_texture) {
  47907. _this._grainTexture = parameters.grain_texture;
  47908. }
  47909. else {
  47910. _this._createGrainTexture();
  47911. }
  47912. // save parameters
  47913. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  47914. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  47915. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  47916. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  47917. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  47918. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  47919. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  47920. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  47921. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  47922. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  47923. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  47924. // Create effects
  47925. _this._createChromaticAberrationPostProcess(ratio);
  47926. _this._createHighlightsPostProcess(ratio);
  47927. _this._createDepthOfFieldPostProcess(ratio / 4);
  47928. // Set up pipeline
  47929. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  47930. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  47931. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  47932. if (_this._highlightsGain === -1) {
  47933. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  47934. }
  47935. // Finish
  47936. scene.postProcessRenderPipelineManager.addPipeline(_this);
  47937. if (cameras) {
  47938. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  47939. }
  47940. return _this;
  47941. }
  47942. // public methods (self explanatory)
  47943. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  47944. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  47945. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  47946. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  47947. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  47948. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  47949. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  47950. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  47951. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  47952. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  47953. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  47954. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  47955. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  47956. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  47957. };
  47958. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  47959. this._highlightsPostProcess.updateEffect();
  47960. };
  47961. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  47962. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  47963. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  47964. this._highlightsGain = amount;
  47965. };
  47966. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  47967. if (this._highlightsGain === -1) {
  47968. this._highlightsGain = 1.0;
  47969. }
  47970. this._highlightsThreshold = amount;
  47971. };
  47972. LensRenderingPipeline.prototype.disableHighlights = function () {
  47973. this._highlightsGain = -1;
  47974. };
  47975. /**
  47976. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  47977. */
  47978. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  47979. if (disableDepthRender === void 0) { disableDepthRender = false; }
  47980. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  47981. this._chromaticAberrationPostProcess = undefined;
  47982. this._highlightsPostProcess = undefined;
  47983. this._depthOfFieldPostProcess = undefined;
  47984. this._grainTexture.dispose();
  47985. if (disableDepthRender)
  47986. this._scene.disableDepthRenderer();
  47987. };
  47988. // colors shifting and distortion
  47989. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  47990. var _this = this;
  47991. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  47992. [], // samplers
  47993. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  47994. this._chromaticAberrationPostProcess.onApply = function (effect) {
  47995. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  47996. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  47997. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  47998. };
  47999. };
  48000. // highlights enhancing
  48001. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  48002. var _this = this;
  48003. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  48004. [], // samplers
  48005. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  48006. this._highlightsPostProcess.onApply = function (effect) {
  48007. effect.setFloat('gain', _this._highlightsGain);
  48008. effect.setFloat('threshold', _this._highlightsThreshold);
  48009. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  48010. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48011. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48012. };
  48013. };
  48014. // colors shifting and distortion
  48015. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  48016. var _this = this;
  48017. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  48018. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  48019. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  48020. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  48021. this._depthOfFieldPostProcess.onApply = function (effect) {
  48022. effect.setTexture("depthSampler", _this._depthTexture);
  48023. effect.setTexture("grainSampler", _this._grainTexture);
  48024. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  48025. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  48026. effect.setFloat('grain_amount', _this._grainAmount);
  48027. effect.setBool('blur_noise', _this._blurNoise);
  48028. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  48029. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  48030. effect.setFloat('distortion', _this._distortion);
  48031. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  48032. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  48033. effect.setFloat('aperture', _this._dofAperture);
  48034. effect.setFloat('darken', _this._dofDarken);
  48035. effect.setFloat('edge_blur', _this._edgeBlur);
  48036. effect.setBool('highlights', (_this._highlightsGain !== -1));
  48037. effect.setFloat('near', _this._scene.activeCamera.minZ);
  48038. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  48039. };
  48040. };
  48041. // creates a black and white random noise texture, 512x512
  48042. LensRenderingPipeline.prototype._createGrainTexture = function () {
  48043. var size = 512;
  48044. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  48045. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  48046. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  48047. var context = this._grainTexture.getContext();
  48048. var rand = function (min, max) {
  48049. return Math.random() * (max - min) + min;
  48050. };
  48051. var value;
  48052. for (var x = 0; x < size; x++) {
  48053. for (var y = 0; y < size; y++) {
  48054. value = Math.floor(rand(0.42, 0.58) * 255);
  48055. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  48056. context.fillRect(x, y, 1, 1);
  48057. }
  48058. }
  48059. this._grainTexture.update(false);
  48060. };
  48061. return LensRenderingPipeline;
  48062. }(BABYLON.PostProcessRenderPipeline));
  48063. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  48064. })(BABYLON || (BABYLON = {}));
  48065. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  48066. //
  48067. // This post-process allows the modification of rendered colors by using
  48068. // a 'look-up table' (LUT). This effect is also called Color Grading.
  48069. //
  48070. // The object needs to be provided an url to a texture containing the color
  48071. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  48072. // Use an image editing software to tweak the LUT to match your needs.
  48073. //
  48074. // For an example of a color LUT, see here:
  48075. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  48076. // For explanations on color grading, see here:
  48077. // http://udn.epicgames.com/Three/ColorGrading.html
  48078. //
  48079. var BABYLON;
  48080. (function (BABYLON) {
  48081. var ColorCorrectionPostProcess = (function (_super) {
  48082. __extends(ColorCorrectionPostProcess, _super);
  48083. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  48084. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  48085. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  48086. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  48087. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48088. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  48089. _this.onApply = function (effect) {
  48090. effect.setTexture("colorTable", _this._colorTableTexture);
  48091. };
  48092. return _this;
  48093. }
  48094. return ColorCorrectionPostProcess;
  48095. }(BABYLON.PostProcess));
  48096. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  48097. })(BABYLON || (BABYLON = {}));
  48098. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  48099. var BABYLON;
  48100. (function (BABYLON) {
  48101. var AnaglyphFreeCamera = (function (_super) {
  48102. __extends(AnaglyphFreeCamera, _super);
  48103. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  48104. var _this = _super.call(this, name, position, scene) || this;
  48105. _this.interaxialDistance = interaxialDistance;
  48106. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48107. return _this;
  48108. }
  48109. AnaglyphFreeCamera.prototype.getClassName = function () {
  48110. return "AnaglyphFreeCamera";
  48111. };
  48112. return AnaglyphFreeCamera;
  48113. }(BABYLON.FreeCamera));
  48114. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  48115. var AnaglyphArcRotateCamera = (function (_super) {
  48116. __extends(AnaglyphArcRotateCamera, _super);
  48117. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  48118. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48119. _this.interaxialDistance = interaxialDistance;
  48120. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48121. return _this;
  48122. }
  48123. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  48124. return "AnaglyphArcRotateCamera";
  48125. };
  48126. return AnaglyphArcRotateCamera;
  48127. }(BABYLON.ArcRotateCamera));
  48128. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  48129. var AnaglyphGamepadCamera = (function (_super) {
  48130. __extends(AnaglyphGamepadCamera, _super);
  48131. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  48132. var _this = _super.call(this, name, position, scene) || this;
  48133. _this.interaxialDistance = interaxialDistance;
  48134. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48135. return _this;
  48136. }
  48137. AnaglyphGamepadCamera.prototype.getClassName = function () {
  48138. return "AnaglyphGamepadCamera";
  48139. };
  48140. return AnaglyphGamepadCamera;
  48141. }(BABYLON.GamepadCamera));
  48142. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  48143. var AnaglyphUniversalCamera = (function (_super) {
  48144. __extends(AnaglyphUniversalCamera, _super);
  48145. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  48146. var _this = _super.call(this, name, position, scene) || this;
  48147. _this.interaxialDistance = interaxialDistance;
  48148. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  48149. return _this;
  48150. }
  48151. AnaglyphUniversalCamera.prototype.getClassName = function () {
  48152. return "AnaglyphUniversalCamera";
  48153. };
  48154. return AnaglyphUniversalCamera;
  48155. }(BABYLON.UniversalCamera));
  48156. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  48157. var StereoscopicFreeCamera = (function (_super) {
  48158. __extends(StereoscopicFreeCamera, _super);
  48159. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48160. var _this = _super.call(this, name, position, scene) || this;
  48161. _this.interaxialDistance = interaxialDistance;
  48162. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48163. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48164. return _this;
  48165. }
  48166. StereoscopicFreeCamera.prototype.getClassName = function () {
  48167. return "StereoscopicFreeCamera";
  48168. };
  48169. return StereoscopicFreeCamera;
  48170. }(BABYLON.FreeCamera));
  48171. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  48172. var StereoscopicArcRotateCamera = (function (_super) {
  48173. __extends(StereoscopicArcRotateCamera, _super);
  48174. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  48175. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  48176. _this.interaxialDistance = interaxialDistance;
  48177. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48178. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48179. return _this;
  48180. }
  48181. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  48182. return "StereoscopicArcRotateCamera";
  48183. };
  48184. return StereoscopicArcRotateCamera;
  48185. }(BABYLON.ArcRotateCamera));
  48186. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  48187. var StereoscopicGamepadCamera = (function (_super) {
  48188. __extends(StereoscopicGamepadCamera, _super);
  48189. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48190. var _this = _super.call(this, name, position, scene) || this;
  48191. _this.interaxialDistance = interaxialDistance;
  48192. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48193. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48194. return _this;
  48195. }
  48196. StereoscopicGamepadCamera.prototype.getClassName = function () {
  48197. return "StereoscopicGamepadCamera";
  48198. };
  48199. return StereoscopicGamepadCamera;
  48200. }(BABYLON.GamepadCamera));
  48201. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  48202. var StereoscopicUniversalCamera = (function (_super) {
  48203. __extends(StereoscopicUniversalCamera, _super);
  48204. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  48205. var _this = _super.call(this, name, position, scene) || this;
  48206. _this.interaxialDistance = interaxialDistance;
  48207. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  48208. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  48209. return _this;
  48210. }
  48211. StereoscopicUniversalCamera.prototype.getClassName = function () {
  48212. return "StereoscopicUniversalCamera";
  48213. };
  48214. return StereoscopicUniversalCamera;
  48215. }(BABYLON.UniversalCamera));
  48216. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  48217. })(BABYLON || (BABYLON = {}));
  48218. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  48219. var BABYLON;
  48220. (function (BABYLON) {
  48221. var HolographicCamera = (function (_super) {
  48222. __extends(HolographicCamera, _super);
  48223. function HolographicCamera(name, scene) {
  48224. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  48225. scene.clearColor = new BABYLON.Color4(0, 0, 0, 0);
  48226. _this._holographicViewMatrix = new BABYLON.Matrix();
  48227. _this._identityProjection = BABYLON.Matrix.Identity();
  48228. _this._scriptProjection = BABYLON.Matrix.Transpose(BABYLON.Matrix.PerspectiveFovLH(30, window.innerWidth / window.innerHeight, 1, 20));
  48229. _this._scriptViewProjection = BABYLON.Matrix.Identity();
  48230. _this.fov = 30;
  48231. _this.minZ = 1.0;
  48232. _this.maxZ = 20;
  48233. _this.mode = BABYLON.Camera.PERSPECTIVE_CAMERA;
  48234. _this.isIntermediate = false;
  48235. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  48236. _this.layerMask = 0x0FFFFFFF;
  48237. _this.fovMode = BABYLON.Camera.FOVMODE_VERTICAL_FIXED;
  48238. _this.cameraRigMode = BABYLON.Camera.RIG_MODE_NONE;
  48239. var self = _this;
  48240. _this._onBeforeRenderObserver = scene.onBeforeRenderObservable.add(function (scene) {
  48241. self._holographicViewMatrix.m = window.getViewMatrix();
  48242. self.setViewMatrix(self._holographicViewMatrix);
  48243. var position = window.getCameraPositionVector();
  48244. self.position.copyFromFloats(-position[0], position[1], -position[2]);
  48245. });
  48246. _this._onBeforeCameraRenderObserver = scene.onBeforeCameraRenderObservable.add(function () {
  48247. if (scene.frustumPlanes) {
  48248. self.getFrustumPlanesToRef(scene.frustumPlanes);
  48249. }
  48250. });
  48251. scene.addCamera(_this);
  48252. if (!scene.activeCamera) {
  48253. scene.activeCamera = _this;
  48254. }
  48255. return _this;
  48256. }
  48257. HolographicCamera.prototype.getTypeName = function () {
  48258. return "HolographicCamera";
  48259. };
  48260. ;
  48261. HolographicCamera.prototype.getProjectionMatrix = function () {
  48262. return this._identityProjection;
  48263. };
  48264. ;
  48265. HolographicCamera.prototype.getViewMatrix = function () {
  48266. return this._holographicViewMatrix;
  48267. };
  48268. ;
  48269. HolographicCamera.prototype.setViewMatrix = function (view) {
  48270. this._holographicViewMatrix = view;
  48271. view.m[0] = -view.m[0];
  48272. view.m[1] = -view.m[1];
  48273. view.m[2] = -view.m[2];
  48274. view.m[3] = -view.m[3];
  48275. view.m[8] = -view.m[8];
  48276. view.m[9] = -view.m[9];
  48277. view.m[10] = -view.m[10];
  48278. view.m[11] = -view.m[11];
  48279. };
  48280. ;
  48281. HolographicCamera.prototype._initCache = function () { };
  48282. ;
  48283. HolographicCamera.prototype._updateCache = function () { };
  48284. ;
  48285. HolographicCamera.prototype._updateFromScene = function () { };
  48286. ;
  48287. // Synchronized
  48288. HolographicCamera.prototype._isSynchronizedViewMatrix = function () {
  48289. return true;
  48290. };
  48291. ;
  48292. HolographicCamera.prototype._isSynchronizedProjectionMatrix = function () {
  48293. return true;
  48294. };
  48295. ;
  48296. HolographicCamera.prototype.getFrustumPlanesToRef = function (result) {
  48297. this._holographicViewMatrix.multiplyToRef(this._scriptProjection, this._scriptViewProjection);
  48298. BABYLON.Frustum.GetPlanesToRef(this._scriptViewProjection, result);
  48299. return result;
  48300. };
  48301. ;
  48302. HolographicCamera.prototype.dispose = function () {
  48303. this.getScene().onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  48304. this.getScene().onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  48305. _super.prototype.dispose.call(this);
  48306. };
  48307. return HolographicCamera;
  48308. }(BABYLON.Camera));
  48309. BABYLON.HolographicCamera = HolographicCamera;
  48310. })(BABYLON || (BABYLON = {}));
  48311. //# sourceMappingURL=babylon.holographicCamera.js.map
  48312. var BABYLON;
  48313. (function (BABYLON) {
  48314. var HDRRenderingPipeline = (function (_super) {
  48315. __extends(HDRRenderingPipeline, _super);
  48316. /**
  48317. * @constructor
  48318. * @param {string} name - The rendering pipeline name
  48319. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  48320. * @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)
  48321. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  48322. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  48323. */
  48324. function HDRRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  48325. if (originalPostProcess === void 0) { originalPostProcess = null; }
  48326. var _this = _super.call(this, scene.getEngine(), name) || this;
  48327. /**
  48328. * Public members
  48329. */
  48330. // Gaussian Blur
  48331. /**
  48332. * Gaussian blur coefficient
  48333. * @type {number}
  48334. */
  48335. _this.gaussCoeff = 0.3;
  48336. /**
  48337. * Gaussian blur mean
  48338. * @type {number}
  48339. */
  48340. _this.gaussMean = 1.0;
  48341. /**
  48342. * Gaussian blur standard deviation
  48343. * @type {number}
  48344. */
  48345. _this.gaussStandDev = 0.8;
  48346. /**
  48347. * Gaussian blur multiplier. Multiplies the blur effect
  48348. * @type {number}
  48349. */
  48350. _this.gaussMultiplier = 4.0;
  48351. // HDR
  48352. /**
  48353. * Exposure, controls the overall intensity of the pipeline
  48354. * @type {number}
  48355. */
  48356. _this.exposure = 1.0;
  48357. /**
  48358. * Minimum luminance that the post-process can output. Luminance is >= 0
  48359. * @type {number}
  48360. */
  48361. _this.minimumLuminance = 1.0;
  48362. /**
  48363. * Maximum luminance that the post-process can output. Must be suprerior to minimumLuminance
  48364. * @type {number}
  48365. */
  48366. _this.maximumLuminance = 1e20;
  48367. /**
  48368. * Increase rate for luminance: eye adaptation speed to dark
  48369. * @type {number}
  48370. */
  48371. _this.luminanceIncreaserate = 0.5;
  48372. /**
  48373. * Decrease rate for luminance: eye adaptation speed to bright
  48374. * @type {number}
  48375. */
  48376. _this.luminanceDecreaseRate = 0.5;
  48377. // Bright pass
  48378. /**
  48379. * Minimum luminance needed to compute HDR
  48380. * @type {number}
  48381. */
  48382. _this.brightThreshold = 0.8;
  48383. _this._needUpdate = true;
  48384. _this._scene = scene;
  48385. // Bright pass
  48386. _this._createBrightPassPostProcess(scene, ratio);
  48387. // Down sample X4
  48388. _this._createDownSampleX4PostProcess(scene, ratio);
  48389. // Create gaussian blur post-processes
  48390. _this._createGaussianBlurPostProcess(scene, ratio);
  48391. // Texture adder
  48392. _this._createTextureAdderPostProcess(scene, ratio);
  48393. // Luminance generator
  48394. _this._createLuminanceGeneratorPostProcess(scene);
  48395. // HDR
  48396. _this._createHDRPostProcess(scene, ratio);
  48397. // Pass postprocess
  48398. if (originalPostProcess === null) {
  48399. _this._originalPostProcess = new BABYLON.PassPostProcess("hdr", ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  48400. }
  48401. else {
  48402. _this._originalPostProcess = originalPostProcess;
  48403. }
  48404. // Configure pipeline
  48405. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this._originalPostProcess; }, true));
  48406. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this._brightPassPostProcess; }, true));
  48407. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this._downSampleX4PostProcess; }, true));
  48408. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH", function () { return _this._guassianBlurHPostProcess; }, true));
  48409. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV", function () { return _this._guassianBlurVPostProcess; }, true));
  48410. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this._textureAdderPostProcess; }, true));
  48411. var addDownSamplerPostProcess = function (id) {
  48412. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampler" + id, function () { return _this._downSamplePostProcesses[id]; }, true));
  48413. };
  48414. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48415. addDownSamplerPostProcess(i);
  48416. }
  48417. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this._hdrPostProcess; }, true));
  48418. // Finish
  48419. scene.postProcessRenderPipelineManager.addPipeline(_this);
  48420. if (cameras !== null) {
  48421. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  48422. }
  48423. _this.update();
  48424. return _this;
  48425. }
  48426. /**
  48427. * Tells the pipeline to update its post-processes
  48428. */
  48429. HDRRenderingPipeline.prototype.update = function () {
  48430. this._needUpdate = true;
  48431. };
  48432. /**
  48433. * Returns the current calculated luminance
  48434. */
  48435. HDRRenderingPipeline.prototype.getCurrentLuminance = function () {
  48436. return this._hdrCurrentLuminance;
  48437. };
  48438. /**
  48439. * Returns the currently drawn luminance
  48440. */
  48441. HDRRenderingPipeline.prototype.getOutputLuminance = function () {
  48442. return this._hdrOutputLuminance;
  48443. };
  48444. /**
  48445. * Releases the rendering pipeline and its internal effects. Detaches pipeline from cameras
  48446. */
  48447. HDRRenderingPipeline.prototype.dispose = function () {
  48448. this._originalPostProcess = undefined;
  48449. this._brightPassPostProcess = undefined;
  48450. this._downSampleX4PostProcess = undefined;
  48451. this._guassianBlurHPostProcess = undefined;
  48452. this._guassianBlurVPostProcess = undefined;
  48453. this._textureAdderPostProcess = undefined;
  48454. for (var i = HDRRenderingPipeline.LUM_STEPS - 1; i >= 0; i--) {
  48455. this._downSamplePostProcesses[i] = undefined;
  48456. }
  48457. this._hdrPostProcess = undefined;
  48458. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  48459. };
  48460. /**
  48461. * Creates the HDR post-process and computes the luminance adaptation
  48462. */
  48463. HDRRenderingPipeline.prototype._createHDRPostProcess = function (scene, ratio) {
  48464. var _this = this;
  48465. var hdrLastLuminance = 0.0;
  48466. this._hdrOutputLuminance = -1.0;
  48467. this._hdrCurrentLuminance = 1.0;
  48468. this._hdrPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["exposure", "avgLuminance"], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR");
  48469. this._hdrPostProcess.onApply = function (effect) {
  48470. if (_this._hdrOutputLuminance < 0.0) {
  48471. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48472. }
  48473. else {
  48474. var dt = (hdrLastLuminance - (hdrLastLuminance + scene.getEngine().getDeltaTime())) / 1000.0;
  48475. if (_this._hdrCurrentLuminance < _this._hdrOutputLuminance + _this.luminanceDecreaseRate * dt) {
  48476. _this._hdrOutputLuminance += _this.luminanceDecreaseRate * dt;
  48477. }
  48478. else if (_this._hdrCurrentLuminance > _this._hdrOutputLuminance - _this.luminanceIncreaserate * dt) {
  48479. _this._hdrOutputLuminance -= _this.luminanceIncreaserate * dt;
  48480. }
  48481. else {
  48482. _this._hdrOutputLuminance = _this._hdrCurrentLuminance;
  48483. }
  48484. }
  48485. _this._hdrOutputLuminance = BABYLON.MathTools.Clamp(_this._hdrOutputLuminance, _this.minimumLuminance, _this.maximumLuminance);
  48486. hdrLastLuminance += scene.getEngine().getDeltaTime();
  48487. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48488. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48489. effect.setFloat("exposure", _this.exposure);
  48490. effect.setFloat("avgLuminance", _this._hdrOutputLuminance);
  48491. _this._needUpdate = false;
  48492. };
  48493. };
  48494. /**
  48495. * Texture Adder post-process
  48496. */
  48497. HDRRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  48498. var _this = this;
  48499. this._textureAdderPostProcess = new BABYLON.PostProcess("hdr", "hdr", [], ["otherSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER");
  48500. this._textureAdderPostProcess.onApply = function (effect) {
  48501. effect.setTextureFromPostProcess("otherSampler", _this._originalPostProcess);
  48502. };
  48503. };
  48504. /**
  48505. * Down sample X4 post-process
  48506. */
  48507. HDRRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  48508. var _this = this;
  48509. var downSampleX4Offsets = new Array(32);
  48510. this._downSampleX4PostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets"], [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4");
  48511. this._downSampleX4PostProcess.onApply = function (effect) {
  48512. if (_this._needUpdate) {
  48513. var id = 0;
  48514. for (var i = -2; i < 2; i++) {
  48515. for (var j = -2; j < 2; j++) {
  48516. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this._downSampleX4PostProcess.width);
  48517. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this._downSampleX4PostProcess.height);
  48518. id += 2;
  48519. }
  48520. }
  48521. }
  48522. effect.setArray2("dsOffsets", downSampleX4Offsets);
  48523. };
  48524. };
  48525. /**
  48526. * Bright pass post-process
  48527. */
  48528. HDRRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  48529. var _this = this;
  48530. var brightOffsets = new Array(8);
  48531. var brightPassCallback = function (effect) {
  48532. if (_this._needUpdate) {
  48533. var sU = (1.0 / _this._brightPassPostProcess.width);
  48534. var sV = (1.0 / _this._brightPassPostProcess.height);
  48535. brightOffsets[0] = -0.5 * sU;
  48536. brightOffsets[1] = 0.5 * sV;
  48537. brightOffsets[2] = 0.5 * sU;
  48538. brightOffsets[3] = 0.5 * sV;
  48539. brightOffsets[4] = -0.5 * sU;
  48540. brightOffsets[5] = -0.5 * sV;
  48541. brightOffsets[6] = 0.5 * sU;
  48542. brightOffsets[7] = -0.5 * sV;
  48543. }
  48544. effect.setArray2("dsOffsets", brightOffsets);
  48545. effect.setFloat("brightThreshold", _this.brightThreshold);
  48546. };
  48547. this._brightPassPostProcess = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS");
  48548. this._brightPassPostProcess.onApply = brightPassCallback;
  48549. };
  48550. /**
  48551. * Luminance generator. Creates the luminance post-process and down sample post-processes
  48552. */
  48553. HDRRenderingPipeline.prototype._createLuminanceGeneratorPostProcess = function (scene) {
  48554. var _this = this;
  48555. var lumSteps = HDRRenderingPipeline.LUM_STEPS;
  48556. var luminanceOffsets = new Array(8);
  48557. var downSampleOffsets = new Array(18);
  48558. var halfDestPixelSize;
  48559. this._downSamplePostProcesses = new Array(lumSteps);
  48560. // Utils for luminance
  48561. var luminanceUpdateSourceOffsets = function (width, height) {
  48562. var sU = (1.0 / width);
  48563. var sV = (1.0 / height);
  48564. luminanceOffsets[0] = -0.5 * sU;
  48565. luminanceOffsets[1] = 0.5 * sV;
  48566. luminanceOffsets[2] = 0.5 * sU;
  48567. luminanceOffsets[3] = 0.5 * sV;
  48568. luminanceOffsets[4] = -0.5 * sU;
  48569. luminanceOffsets[5] = -0.5 * sV;
  48570. luminanceOffsets[6] = 0.5 * sU;
  48571. luminanceOffsets[7] = -0.5 * sV;
  48572. };
  48573. var luminanceUpdateDestOffsets = function (width, height) {
  48574. var id = 0;
  48575. for (var x = -1; x < 2; x++) {
  48576. for (var y = -1; y < 2; y++) {
  48577. downSampleOffsets[id] = (x) / width;
  48578. downSampleOffsets[id + 1] = (y) / height;
  48579. id += 2;
  48580. }
  48581. }
  48582. };
  48583. // Luminance callback
  48584. var luminanceCallback = function (effect) {
  48585. if (_this._needUpdate) {
  48586. luminanceUpdateSourceOffsets(_this._textureAdderPostProcess.width, _this._textureAdderPostProcess.height);
  48587. }
  48588. effect.setTextureFromPostProcess("textureSampler", _this._textureAdderPostProcess);
  48589. effect.setArray2("lumOffsets", luminanceOffsets);
  48590. };
  48591. // Down sample callbacks
  48592. var downSampleCallback = function (indice) {
  48593. var i = indice;
  48594. return function (effect) {
  48595. luminanceUpdateSourceOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48596. luminanceUpdateDestOffsets(_this._downSamplePostProcesses[i].width, _this._downSamplePostProcesses[i].height);
  48597. halfDestPixelSize = 0.5 / _this._downSamplePostProcesses[i].width;
  48598. effect.setTextureFromPostProcess("textureSampler", _this._downSamplePostProcesses[i + 1]);
  48599. effect.setFloat("halfDestPixelSize", halfDestPixelSize);
  48600. effect.setArray2("dsOffsets", downSampleOffsets);
  48601. };
  48602. };
  48603. var downSampleAfterRenderCallback = function (effect) {
  48604. // Unpack result
  48605. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  48606. 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);
  48607. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  48608. };
  48609. // Create luminance post-process
  48610. var ratio = { width: Math.pow(3, lumSteps - 1), height: Math.pow(3, lumSteps - 1) };
  48611. 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);
  48612. this._downSamplePostProcesses[lumSteps - 1].onApply = luminanceCallback;
  48613. // Create down sample post-processes
  48614. for (var i = lumSteps - 2; i >= 0; i--) {
  48615. var length = Math.pow(3, i);
  48616. ratio = { width: length, height: length };
  48617. var defines = "#define DOWN_SAMPLE\n";
  48618. if (i === 0) {
  48619. defines += "#define FINAL_DOWN_SAMPLE\n"; // To pack the result
  48620. }
  48621. this._downSamplePostProcesses[i] = new BABYLON.PostProcess("hdr", "hdr", ["dsOffsets", "halfDestPixelSize"], [], ratio, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, scene.getEngine(), false, defines, BABYLON.Engine.TEXTURETYPE_FLOAT);
  48622. this._downSamplePostProcesses[i].onApply = downSampleCallback(i);
  48623. if (i === 0) {
  48624. this._downSamplePostProcesses[i].onAfterRender = downSampleAfterRenderCallback;
  48625. }
  48626. }
  48627. };
  48628. /**
  48629. * Gaussian blur post-processes. Horizontal and Vertical
  48630. */
  48631. HDRRenderingPipeline.prototype._createGaussianBlurPostProcess = function (scene, ratio) {
  48632. var _this = this;
  48633. var blurOffsetsW = new Array(9);
  48634. var blurOffsetsH = new Array(9);
  48635. var blurWeights = new Array(9);
  48636. var uniforms = ["blurOffsets", "blurWeights", "multiplier"];
  48637. // Utils for gaussian blur
  48638. var calculateBlurOffsets = function (height) {
  48639. var lastOutputDimensions = {
  48640. width: scene.getEngine().getRenderWidth(),
  48641. height: scene.getEngine().getRenderHeight()
  48642. };
  48643. for (var i = 0; i < 9; i++) {
  48644. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  48645. if (height) {
  48646. blurOffsetsH[i] = value;
  48647. }
  48648. else {
  48649. blurOffsetsW[i] = value;
  48650. }
  48651. }
  48652. };
  48653. var calculateWeights = function () {
  48654. var x = 0.0;
  48655. for (var i = 0; i < 9; i++) {
  48656. x = (i - 4.0) / 4.0;
  48657. 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));
  48658. }
  48659. };
  48660. // Callback
  48661. var gaussianBlurCallback = function (height) {
  48662. return function (effect) {
  48663. if (_this._needUpdate) {
  48664. calculateWeights();
  48665. calculateBlurOffsets(height);
  48666. }
  48667. effect.setArray("blurOffsets", height ? blurOffsetsH : blurOffsetsW);
  48668. effect.setArray("blurWeights", blurWeights);
  48669. effect.setFloat("multiplier", _this.gaussMultiplier);
  48670. };
  48671. };
  48672. // Create horizontal gaussian blur post-processes
  48673. this._guassianBlurHPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H");
  48674. this._guassianBlurHPostProcess.onApply = gaussianBlurCallback(false);
  48675. // Create vertical gaussian blur post-process
  48676. this._guassianBlurVPostProcess = new BABYLON.PostProcess("hdr", "hdr", uniforms, [], ratio / 4, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V");
  48677. this._guassianBlurVPostProcess.onApply = gaussianBlurCallback(true);
  48678. };
  48679. return HDRRenderingPipeline;
  48680. }(BABYLON.PostProcessRenderPipeline));
  48681. // Luminance generator
  48682. HDRRenderingPipeline.LUM_STEPS = 6;
  48683. BABYLON.HDRRenderingPipeline = HDRRenderingPipeline;
  48684. })(BABYLON || (BABYLON = {}));
  48685. //# sourceMappingURL=babylon.hdrRenderingPipeline.js.map
  48686. var BABYLON;
  48687. (function (BABYLON) {
  48688. var FaceAdjacencies = (function () {
  48689. function FaceAdjacencies() {
  48690. this.edges = new Array();
  48691. this.edgesConnectedCount = 0;
  48692. }
  48693. return FaceAdjacencies;
  48694. }());
  48695. var EdgesRenderer = (function () {
  48696. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  48697. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  48698. if (epsilon === void 0) { epsilon = 0.95; }
  48699. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  48700. this.edgesWidthScalerForOrthographic = 1000.0;
  48701. this.edgesWidthScalerForPerspective = 50.0;
  48702. this._linesPositions = new Array();
  48703. this._linesNormals = new Array();
  48704. this._linesIndices = new Array();
  48705. this._buffers = {};
  48706. this._checkVerticesInsteadOfIndices = false;
  48707. this._source = source;
  48708. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  48709. this._epsilon = epsilon;
  48710. this._prepareRessources();
  48711. this._generateEdgesLines();
  48712. }
  48713. EdgesRenderer.prototype._prepareRessources = function () {
  48714. if (this._lineShader) {
  48715. return;
  48716. }
  48717. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  48718. attributes: ["position", "normal"],
  48719. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  48720. });
  48721. this._lineShader.disableDepthWrite = true;
  48722. this._lineShader.backFaceCulling = false;
  48723. };
  48724. EdgesRenderer.prototype.dispose = function () {
  48725. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  48726. if (buffer) {
  48727. buffer.dispose();
  48728. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  48729. }
  48730. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  48731. if (buffer) {
  48732. buffer.dispose();
  48733. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  48734. }
  48735. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  48736. this._lineShader.dispose();
  48737. };
  48738. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  48739. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  48740. return 0;
  48741. }
  48742. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  48743. return 1;
  48744. }
  48745. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  48746. return 2;
  48747. }
  48748. return -1;
  48749. };
  48750. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  48751. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  48752. return 0;
  48753. }
  48754. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  48755. return 1;
  48756. }
  48757. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  48758. return 2;
  48759. }
  48760. return -1;
  48761. };
  48762. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  48763. var needToCreateLine;
  48764. if (edge === undefined) {
  48765. needToCreateLine = true;
  48766. }
  48767. else {
  48768. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  48769. needToCreateLine = dotProduct < this._epsilon;
  48770. }
  48771. if (needToCreateLine) {
  48772. var offset = this._linesPositions.length / 3;
  48773. var normal = p0.subtract(p1);
  48774. normal.normalize();
  48775. // Positions
  48776. this._linesPositions.push(p0.x);
  48777. this._linesPositions.push(p0.y);
  48778. this._linesPositions.push(p0.z);
  48779. this._linesPositions.push(p0.x);
  48780. this._linesPositions.push(p0.y);
  48781. this._linesPositions.push(p0.z);
  48782. this._linesPositions.push(p1.x);
  48783. this._linesPositions.push(p1.y);
  48784. this._linesPositions.push(p1.z);
  48785. this._linesPositions.push(p1.x);
  48786. this._linesPositions.push(p1.y);
  48787. this._linesPositions.push(p1.z);
  48788. // Normals
  48789. this._linesNormals.push(p1.x);
  48790. this._linesNormals.push(p1.y);
  48791. this._linesNormals.push(p1.z);
  48792. this._linesNormals.push(-1);
  48793. this._linesNormals.push(p1.x);
  48794. this._linesNormals.push(p1.y);
  48795. this._linesNormals.push(p1.z);
  48796. this._linesNormals.push(1);
  48797. this._linesNormals.push(p0.x);
  48798. this._linesNormals.push(p0.y);
  48799. this._linesNormals.push(p0.z);
  48800. this._linesNormals.push(-1);
  48801. this._linesNormals.push(p0.x);
  48802. this._linesNormals.push(p0.y);
  48803. this._linesNormals.push(p0.z);
  48804. this._linesNormals.push(1);
  48805. // Indices
  48806. this._linesIndices.push(offset);
  48807. this._linesIndices.push(offset + 1);
  48808. this._linesIndices.push(offset + 2);
  48809. this._linesIndices.push(offset);
  48810. this._linesIndices.push(offset + 2);
  48811. this._linesIndices.push(offset + 3);
  48812. }
  48813. };
  48814. EdgesRenderer.prototype._generateEdgesLines = function () {
  48815. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  48816. var indices = this._source.getIndices();
  48817. // First let's find adjacencies
  48818. var adjacencies = new Array();
  48819. var faceNormals = new Array();
  48820. var index;
  48821. var faceAdjacencies;
  48822. // Prepare faces
  48823. for (index = 0; index < indices.length; index += 3) {
  48824. faceAdjacencies = new FaceAdjacencies();
  48825. var p0Index = indices[index];
  48826. var p1Index = indices[index + 1];
  48827. var p2Index = indices[index + 2];
  48828. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  48829. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  48830. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  48831. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  48832. faceNormal.normalize();
  48833. faceNormals.push(faceNormal);
  48834. adjacencies.push(faceAdjacencies);
  48835. }
  48836. // Scan
  48837. for (index = 0; index < adjacencies.length; index++) {
  48838. faceAdjacencies = adjacencies[index];
  48839. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  48840. var otherFaceAdjacencies = adjacencies[otherIndex];
  48841. if (faceAdjacencies.edgesConnectedCount === 3) {
  48842. break;
  48843. }
  48844. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  48845. continue;
  48846. }
  48847. var otherP0 = indices[otherIndex * 3];
  48848. var otherP1 = indices[otherIndex * 3 + 1];
  48849. var otherP2 = indices[otherIndex * 3 + 2];
  48850. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  48851. var otherEdgeIndex;
  48852. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  48853. continue;
  48854. }
  48855. switch (edgeIndex) {
  48856. case 0:
  48857. if (this._checkVerticesInsteadOfIndices) {
  48858. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48859. }
  48860. else {
  48861. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  48862. }
  48863. break;
  48864. case 1:
  48865. if (this._checkVerticesInsteadOfIndices) {
  48866. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48867. }
  48868. else {
  48869. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  48870. }
  48871. break;
  48872. case 2:
  48873. if (this._checkVerticesInsteadOfIndices) {
  48874. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  48875. }
  48876. else {
  48877. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  48878. }
  48879. break;
  48880. }
  48881. if (otherEdgeIndex === -1) {
  48882. continue;
  48883. }
  48884. faceAdjacencies.edges[edgeIndex] = otherIndex;
  48885. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  48886. faceAdjacencies.edgesConnectedCount++;
  48887. otherFaceAdjacencies.edgesConnectedCount++;
  48888. if (faceAdjacencies.edgesConnectedCount === 3) {
  48889. break;
  48890. }
  48891. }
  48892. }
  48893. }
  48894. // Create lines
  48895. for (index = 0; index < adjacencies.length; index++) {
  48896. // 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
  48897. var current = adjacencies[index];
  48898. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  48899. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  48900. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  48901. }
  48902. // Merge into a single mesh
  48903. var engine = this._source.getScene().getEngine();
  48904. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  48905. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  48906. this._ib = engine.createIndexBuffer(this._linesIndices);
  48907. this._indicesCount = this._linesIndices.length;
  48908. };
  48909. EdgesRenderer.prototype.render = function () {
  48910. if (!this._lineShader.isReady()) {
  48911. return;
  48912. }
  48913. var scene = this._source.getScene();
  48914. var engine = scene.getEngine();
  48915. this._lineShader._preBind();
  48916. // VBOs
  48917. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  48918. scene.resetCachedMaterial();
  48919. this._lineShader.setColor4("color", this._source.edgesColor);
  48920. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  48921. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  48922. }
  48923. else {
  48924. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  48925. }
  48926. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  48927. this._lineShader.bind(this._source.getWorldMatrix());
  48928. // Draw order
  48929. engine.draw(true, 0, this._indicesCount);
  48930. this._lineShader.unbind();
  48931. engine.setDepthWrite(true);
  48932. };
  48933. return EdgesRenderer;
  48934. }());
  48935. BABYLON.EdgesRenderer = EdgesRenderer;
  48936. })(BABYLON || (BABYLON = {}));
  48937. //# sourceMappingURL=babylon.edgesRenderer.js.map
  48938. var BABYLON;
  48939. (function (BABYLON) {
  48940. var TonemappingOperator;
  48941. (function (TonemappingOperator) {
  48942. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  48943. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  48944. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  48945. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  48946. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  48947. ;
  48948. var TonemapPostProcess = (function (_super) {
  48949. __extends(TonemapPostProcess, _super);
  48950. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  48951. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  48952. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  48953. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  48954. _this._operator = _operator;
  48955. _this.exposureAdjustment = exposureAdjustment;
  48956. var defines = "#define ";
  48957. if (_this._operator === TonemappingOperator.Hable)
  48958. defines += "HABLE_TONEMAPPING";
  48959. else if (_this._operator === TonemappingOperator.Reinhard)
  48960. defines += "REINHARD_TONEMAPPING";
  48961. else if (_this._operator === TonemappingOperator.HejiDawson)
  48962. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  48963. else if (_this._operator === TonemappingOperator.Photographic)
  48964. defines += "PHOTOGRAPHIC_TONEMAPPING";
  48965. //sadly a second call to create the effect.
  48966. _this.updateEffect(defines);
  48967. _this.onApply = function (effect) {
  48968. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  48969. };
  48970. return _this;
  48971. }
  48972. return TonemapPostProcess;
  48973. }(BABYLON.PostProcess));
  48974. BABYLON.TonemapPostProcess = TonemapPostProcess;
  48975. })(BABYLON || (BABYLON = {}));
  48976. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  48977. var BABYLON;
  48978. (function (BABYLON) {
  48979. var ReflectionProbe = (function () {
  48980. function ReflectionProbe(name, size, scene, generateMipMaps) {
  48981. if (generateMipMaps === void 0) { generateMipMaps = true; }
  48982. var _this = this;
  48983. this.name = name;
  48984. this._viewMatrix = BABYLON.Matrix.Identity();
  48985. this._target = BABYLON.Vector3.Zero();
  48986. this._add = BABYLON.Vector3.Zero();
  48987. this.invertYAxis = false;
  48988. this.position = BABYLON.Vector3.Zero();
  48989. this._scene = scene;
  48990. this._scene.reflectionProbes.push(this);
  48991. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  48992. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  48993. switch (faceIndex) {
  48994. case 0:
  48995. _this._add.copyFromFloats(1, 0, 0);
  48996. break;
  48997. case 1:
  48998. _this._add.copyFromFloats(-1, 0, 0);
  48999. break;
  49000. case 2:
  49001. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  49002. break;
  49003. case 3:
  49004. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  49005. break;
  49006. case 4:
  49007. _this._add.copyFromFloats(0, 0, 1);
  49008. break;
  49009. case 5:
  49010. _this._add.copyFromFloats(0, 0, -1);
  49011. break;
  49012. }
  49013. if (_this._attachedMesh) {
  49014. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  49015. }
  49016. _this.position.addToRef(_this._add, _this._target);
  49017. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  49018. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  49019. });
  49020. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  49021. scene.updateTransformMatrix(true);
  49022. });
  49023. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  49024. }
  49025. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  49026. get: function () {
  49027. return this._renderTargetTexture.refreshRate;
  49028. },
  49029. set: function (value) {
  49030. this._renderTargetTexture.refreshRate = value;
  49031. },
  49032. enumerable: true,
  49033. configurable: true
  49034. });
  49035. ReflectionProbe.prototype.getScene = function () {
  49036. return this._scene;
  49037. };
  49038. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  49039. get: function () {
  49040. return this._renderTargetTexture;
  49041. },
  49042. enumerable: true,
  49043. configurable: true
  49044. });
  49045. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  49046. get: function () {
  49047. return this._renderTargetTexture.renderList;
  49048. },
  49049. enumerable: true,
  49050. configurable: true
  49051. });
  49052. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  49053. this._attachedMesh = mesh;
  49054. };
  49055. ReflectionProbe.prototype.dispose = function () {
  49056. var index = this._scene.reflectionProbes.indexOf(this);
  49057. if (index !== -1) {
  49058. // Remove from the scene if found
  49059. this._scene.reflectionProbes.splice(index, 1);
  49060. }
  49061. if (this._renderTargetTexture) {
  49062. this._renderTargetTexture.dispose();
  49063. this._renderTargetTexture = null;
  49064. }
  49065. };
  49066. return ReflectionProbe;
  49067. }());
  49068. BABYLON.ReflectionProbe = ReflectionProbe;
  49069. })(BABYLON || (BABYLON = {}));
  49070. //# sourceMappingURL=babylon.reflectionProbe.js.map
  49071. var BABYLON;
  49072. (function (BABYLON) {
  49073. var SolidParticle = (function () {
  49074. /**
  49075. * Creates a Solid Particle object.
  49076. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  49077. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  49078. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  49079. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  49080. * `shapeId` (integer) is the model shape identifier in the SPS.
  49081. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  49082. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  49083. */
  49084. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  49085. this.idx = 0; // particle global index
  49086. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  49087. this.position = BABYLON.Vector3.Zero(); // position
  49088. this.rotation = BABYLON.Vector3.Zero(); // rotation
  49089. this.scaling = new BABYLON.Vector3(1.0, 1.0, 1.0); // scaling
  49090. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  49091. this.velocity = BABYLON.Vector3.Zero(); // velocity
  49092. this.alive = true; // alive
  49093. this.isVisible = true; // visibility
  49094. this._pos = 0; // index of this particle in the global "positions" array
  49095. this.shapeId = 0; // model shape id
  49096. this.idxInShape = 0; // index of the particle in its shape id
  49097. this.idx = particleIndex;
  49098. this._pos = positionIndex;
  49099. this._model = model;
  49100. this.shapeId = shapeId;
  49101. this.idxInShape = idxInShape;
  49102. this._sps = sps;
  49103. if (modelBoundingInfo) {
  49104. this._modelBoundingInfo = modelBoundingInfo;
  49105. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  49106. }
  49107. }
  49108. Object.defineProperty(SolidParticle.prototype, "scale", {
  49109. /**
  49110. * legacy support, changed scale to scaling
  49111. */
  49112. get: function () {
  49113. return this.scaling;
  49114. },
  49115. set: function (scale) {
  49116. this.scaling = scale;
  49117. },
  49118. enumerable: true,
  49119. configurable: true
  49120. });
  49121. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  49122. /**
  49123. * legacy support, changed quaternion to rotationQuaternion
  49124. */
  49125. get: function () {
  49126. return this.rotationQuaternion;
  49127. },
  49128. set: function (q) {
  49129. this.rotationQuaternion = q;
  49130. },
  49131. enumerable: true,
  49132. configurable: true
  49133. });
  49134. /**
  49135. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  49136. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  49137. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  49138. */
  49139. SolidParticle.prototype.intersectsMesh = function (target) {
  49140. if (!this._boundingInfo || !target._boundingInfo) {
  49141. return false;
  49142. }
  49143. if (this._sps._bSphereOnly) {
  49144. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  49145. }
  49146. return this._boundingInfo.intersects(target._boundingInfo, false);
  49147. };
  49148. return SolidParticle;
  49149. }());
  49150. BABYLON.SolidParticle = SolidParticle;
  49151. var ModelShape = (function () {
  49152. /**
  49153. * Creates a ModelShape object. This is an internal simplified reference to a mesh used as for a model to replicate particles from by the SPS.
  49154. * SPS internal tool, don't use it manually.
  49155. */
  49156. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  49157. this.shapeID = id;
  49158. this._shape = shape;
  49159. this._shapeUV = shapeUV;
  49160. this._positionFunction = posFunction;
  49161. this._vertexFunction = vtxFunction;
  49162. }
  49163. return ModelShape;
  49164. }());
  49165. BABYLON.ModelShape = ModelShape;
  49166. })(BABYLON || (BABYLON = {}));
  49167. //# sourceMappingURL=babylon.solidParticle.js.map
  49168. var BABYLON;
  49169. (function (BABYLON) {
  49170. /**
  49171. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  49172. */
  49173. var SolidParticleSystem = (function () {
  49174. /**
  49175. * Creates a SPS (Solid Particle System) object.
  49176. * `name` (String) is the SPS name, this will be the underlying mesh name.
  49177. * `scene` (Scene) is the scene in which the SPS is added.
  49178. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  49179. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  49180. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  49181. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  49182. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  49183. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  49184. */
  49185. function SolidParticleSystem(name, scene, options) {
  49186. // public members
  49187. /**
  49188. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  49189. * Example : var p = SPS.particles[i];
  49190. */
  49191. this.particles = new Array();
  49192. /**
  49193. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  49194. */
  49195. this.nbParticles = 0;
  49196. /**
  49197. * If the particles must ever face the camera (default false). Useful for planar particles.
  49198. */
  49199. this.billboard = false;
  49200. /**
  49201. * Recompute normals when adding a shape
  49202. */
  49203. this.recomputeNormals = true;
  49204. /**
  49205. * This a counter ofr your own usage. It's not set by any SPS functions.
  49206. */
  49207. this.counter = 0;
  49208. /**
  49209. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  49210. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  49211. */
  49212. this.vars = {};
  49213. this._positions = new Array();
  49214. this._indices = new Array();
  49215. this._normals = new Array();
  49216. this._colors = new Array();
  49217. this._uvs = new Array();
  49218. this._index = 0; // indices index
  49219. this._updatable = true;
  49220. this._pickable = false;
  49221. this._isVisibilityBoxLocked = false;
  49222. this._alwaysVisible = false;
  49223. this._shapeCounter = 0;
  49224. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  49225. this._color = new BABYLON.Color4(0, 0, 0, 0);
  49226. this._computeParticleColor = true;
  49227. this._computeParticleTexture = true;
  49228. this._computeParticleRotation = true;
  49229. this._computeParticleVertex = false;
  49230. this._computeBoundingBox = false;
  49231. this._cam_axisZ = BABYLON.Vector3.Zero();
  49232. this._cam_axisY = BABYLON.Vector3.Zero();
  49233. this._cam_axisX = BABYLON.Vector3.Zero();
  49234. this._axisX = BABYLON.Axis.X;
  49235. this._axisY = BABYLON.Axis.Y;
  49236. this._axisZ = BABYLON.Axis.Z;
  49237. this._camDir = BABYLON.Vector3.Zero();
  49238. this._rotMatrix = new BABYLON.Matrix();
  49239. this._invertMatrix = new BABYLON.Matrix();
  49240. this._rotated = BABYLON.Vector3.Zero();
  49241. this._quaternion = new BABYLON.Quaternion();
  49242. this._vertex = BABYLON.Vector3.Zero();
  49243. this._normal = BABYLON.Vector3.Zero();
  49244. this._yaw = 0.0;
  49245. this._pitch = 0.0;
  49246. this._roll = 0.0;
  49247. this._halfroll = 0.0;
  49248. this._halfpitch = 0.0;
  49249. this._halfyaw = 0.0;
  49250. this._sinRoll = 0.0;
  49251. this._cosRoll = 0.0;
  49252. this._sinPitch = 0.0;
  49253. this._cosPitch = 0.0;
  49254. this._sinYaw = 0.0;
  49255. this._cosYaw = 0.0;
  49256. this._w = 0.0;
  49257. this._minimum = BABYLON.Tmp.Vector3[0];
  49258. this._maximum = BABYLON.Tmp.Vector3[1];
  49259. this._scale = BABYLON.Tmp.Vector3[2];
  49260. this._translation = BABYLON.Tmp.Vector3[3];
  49261. this._minBbox = BABYLON.Tmp.Vector3[4];
  49262. this._maxBbox = BABYLON.Tmp.Vector3[5];
  49263. this._particlesIntersect = false;
  49264. this._bSphereOnly = false;
  49265. this._bSphereRadiusFactor = 1.0;
  49266. this.name = name;
  49267. this._scene = scene;
  49268. this._camera = scene.activeCamera;
  49269. this._pickable = options ? options.isPickable : false;
  49270. this._particlesIntersect = options ? options.particleIntersection : false;
  49271. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  49272. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  49273. if (options && options.updatable) {
  49274. this._updatable = options.updatable;
  49275. }
  49276. else {
  49277. this._updatable = true;
  49278. }
  49279. if (this._pickable) {
  49280. this.pickedParticles = [];
  49281. }
  49282. }
  49283. /**
  49284. * Builds the SPS underlying mesh. Returns a standard Mesh.
  49285. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  49286. */
  49287. SolidParticleSystem.prototype.buildMesh = function () {
  49288. if (this.nbParticles === 0) {
  49289. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  49290. this.addShape(triangle, 1);
  49291. triangle.dispose();
  49292. }
  49293. this._positions32 = new Float32Array(this._positions);
  49294. this._uvs32 = new Float32Array(this._uvs);
  49295. this._colors32 = new Float32Array(this._colors);
  49296. if (this.recomputeNormals) {
  49297. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  49298. }
  49299. this._normals32 = new Float32Array(this._normals);
  49300. this._fixedNormal32 = new Float32Array(this._normals);
  49301. var vertexData = new BABYLON.VertexData();
  49302. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  49303. vertexData.indices = this._indices;
  49304. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  49305. if (this._uvs32) {
  49306. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  49307. ;
  49308. }
  49309. if (this._colors32) {
  49310. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  49311. }
  49312. var mesh = new BABYLON.Mesh(this.name, this._scene);
  49313. vertexData.applyToMesh(mesh, this._updatable);
  49314. this.mesh = mesh;
  49315. this.mesh.isPickable = this._pickable;
  49316. // free memory
  49317. this._positions = null;
  49318. this._normals = null;
  49319. this._uvs = null;
  49320. this._colors = null;
  49321. if (!this._updatable) {
  49322. this.particles.length = 0;
  49323. }
  49324. return mesh;
  49325. };
  49326. /**
  49327. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  49328. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  49329. * Thus the particles generated from `digest()` have their property `position` set yet.
  49330. * `mesh` ( Mesh ) is the mesh to be digested
  49331. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  49332. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  49333. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  49334. */
  49335. SolidParticleSystem.prototype.digest = function (mesh, options) {
  49336. var size = (options && options.facetNb) || 1;
  49337. var number = (options && options.number);
  49338. var delta = (options && options.delta) || 0;
  49339. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49340. var meshInd = mesh.getIndices();
  49341. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49342. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49343. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49344. var f = 0; // facet counter
  49345. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  49346. // compute size from number
  49347. if (number) {
  49348. number = (number > totalFacets) ? totalFacets : number;
  49349. size = Math.round(totalFacets / number);
  49350. delta = 0;
  49351. }
  49352. else {
  49353. size = (size > totalFacets) ? totalFacets : size;
  49354. }
  49355. var facetPos = []; // submesh positions
  49356. var facetInd = []; // submesh indices
  49357. var facetUV = []; // submesh UV
  49358. var facetCol = []; // submesh colors
  49359. var barycenter = BABYLON.Tmp.Vector3[0];
  49360. var rand;
  49361. var sizeO = size;
  49362. while (f < totalFacets) {
  49363. size = sizeO + Math.floor((1 + delta) * Math.random());
  49364. if (f > totalFacets - size) {
  49365. size = totalFacets - f;
  49366. }
  49367. // reset temp arrays
  49368. facetPos.length = 0;
  49369. facetInd.length = 0;
  49370. facetUV.length = 0;
  49371. facetCol.length = 0;
  49372. // iterate over "size" facets
  49373. var fi = 0;
  49374. for (var j = f * 3; j < (f + size) * 3; j++) {
  49375. facetInd.push(fi);
  49376. var i = meshInd[j];
  49377. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  49378. if (meshUV) {
  49379. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  49380. }
  49381. if (meshCol) {
  49382. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  49383. }
  49384. fi++;
  49385. }
  49386. // create a model shape for each single particle
  49387. var idx = this.nbParticles;
  49388. var shape = this._posToShape(facetPos);
  49389. var shapeUV = this._uvsToShapeUV(facetUV);
  49390. // compute the barycenter of the shape
  49391. var v;
  49392. for (v = 0; v < shape.length; v++) {
  49393. barycenter.addInPlace(shape[v]);
  49394. }
  49395. barycenter.scaleInPlace(1 / shape.length);
  49396. // shift the shape from its barycenter to the origin
  49397. for (v = 0; v < shape.length; v++) {
  49398. shape[v].subtractInPlace(barycenter);
  49399. }
  49400. var bInfo;
  49401. if (this._particlesIntersect) {
  49402. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  49403. }
  49404. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  49405. // add the particle in the SPS
  49406. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  49407. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, 0, bInfo);
  49408. // initialize the particle position
  49409. this.particles[this.nbParticles].position.addInPlace(barycenter);
  49410. this._index += shape.length;
  49411. idx++;
  49412. this.nbParticles++;
  49413. this._shapeCounter++;
  49414. f += size;
  49415. }
  49416. return this;
  49417. };
  49418. //reset copy
  49419. SolidParticleSystem.prototype._resetCopy = function () {
  49420. this._copy.position.x = 0;
  49421. this._copy.position.y = 0;
  49422. this._copy.position.z = 0;
  49423. this._copy.rotation.x = 0;
  49424. this._copy.rotation.y = 0;
  49425. this._copy.rotation.z = 0;
  49426. this._copy.rotationQuaternion = null;
  49427. this._copy.scaling.x = 1;
  49428. this._copy.scaling.y = 1;
  49429. this._copy.scaling.z = 1;
  49430. this._copy.uvs.x = 0;
  49431. this._copy.uvs.y = 0;
  49432. this._copy.uvs.z = 1;
  49433. this._copy.uvs.w = 1;
  49434. this._copy.color = null;
  49435. };
  49436. // _meshBuilder : inserts the shape model in the global SPS mesh
  49437. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  49438. var i;
  49439. var u = 0;
  49440. var c = 0;
  49441. var n = 0;
  49442. this._resetCopy();
  49443. if (options && options.positionFunction) {
  49444. options.positionFunction(this._copy, idx, idxInShape);
  49445. }
  49446. if (this._copy.rotationQuaternion) {
  49447. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49448. }
  49449. else {
  49450. this._yaw = this._copy.rotation.y;
  49451. this._pitch = this._copy.rotation.x;
  49452. this._roll = this._copy.rotation.z;
  49453. this._quaternionRotationYPR();
  49454. }
  49455. this._quaternionToRotationMatrix();
  49456. for (i = 0; i < shape.length; i++) {
  49457. this._vertex.x = shape[i].x;
  49458. this._vertex.y = shape[i].y;
  49459. this._vertex.z = shape[i].z;
  49460. if (options && options.vertexFunction) {
  49461. options.vertexFunction(this._copy, this._vertex, i);
  49462. }
  49463. this._vertex.x *= this._copy.scaling.x;
  49464. this._vertex.y *= this._copy.scaling.y;
  49465. this._vertex.z *= this._copy.scaling.z;
  49466. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49467. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  49468. if (meshUV) {
  49469. 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);
  49470. u += 2;
  49471. }
  49472. if (this._copy.color) {
  49473. this._color = this._copy.color;
  49474. }
  49475. else if (meshCol && meshCol[c] !== undefined) {
  49476. this._color.r = meshCol[c];
  49477. this._color.g = meshCol[c + 1];
  49478. this._color.b = meshCol[c + 2];
  49479. this._color.a = meshCol[c + 3];
  49480. }
  49481. else {
  49482. this._color.r = 1;
  49483. this._color.g = 1;
  49484. this._color.b = 1;
  49485. this._color.a = 1;
  49486. }
  49487. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  49488. c += 4;
  49489. if (!this.recomputeNormals && meshNor) {
  49490. this._normal.x = meshNor[n];
  49491. this._normal.y = meshNor[n + 1];
  49492. this._normal.z = meshNor[n + 2];
  49493. BABYLON.Vector3.TransformCoordinatesToRef(this._normal, this._rotMatrix, this._normal);
  49494. normals.push(this._normal.x, this._normal.y, this._normal.z);
  49495. n += 3;
  49496. }
  49497. }
  49498. for (i = 0; i < meshInd.length; i++) {
  49499. indices.push(p + meshInd[i]);
  49500. }
  49501. if (this._pickable) {
  49502. var nbfaces = meshInd.length / 3;
  49503. for (i = 0; i < nbfaces; i++) {
  49504. this.pickedParticles.push({ idx: idx, faceId: i });
  49505. }
  49506. }
  49507. };
  49508. // returns a shape array from positions array
  49509. SolidParticleSystem.prototype._posToShape = function (positions) {
  49510. var shape = [];
  49511. for (var i = 0; i < positions.length; i += 3) {
  49512. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  49513. }
  49514. return shape;
  49515. };
  49516. // returns a shapeUV array from a Vector4 uvs
  49517. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  49518. var shapeUV = [];
  49519. if (uvs) {
  49520. for (var i = 0; i < uvs.length; i++)
  49521. shapeUV.push(uvs[i]);
  49522. }
  49523. return shapeUV;
  49524. };
  49525. // adds a new particle object in the particles array
  49526. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  49527. this.particles.push(new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo));
  49528. };
  49529. /**
  49530. * Adds some particles to the SPS from the model shape. Returns the shape id.
  49531. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  49532. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  49533. * `nb` (positive integer) the number of particles to be created from this model
  49534. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  49535. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  49536. */
  49537. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  49538. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  49539. var meshInd = mesh.getIndices();
  49540. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  49541. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  49542. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  49543. var bbInfo;
  49544. if (this._particlesIntersect) {
  49545. bbInfo = mesh.getBoundingInfo();
  49546. }
  49547. var shape = this._posToShape(meshPos);
  49548. var shapeUV = this._uvsToShapeUV(meshUV);
  49549. var posfunc = options ? options.positionFunction : null;
  49550. var vtxfunc = options ? options.vertexFunction : null;
  49551. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  49552. // particles
  49553. var idx = this.nbParticles;
  49554. for (var i = 0; i < nb; i++) {
  49555. this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  49556. if (this._updatable) {
  49557. this._addParticle(idx, this._positions.length, modelShape, this._shapeCounter, i, bbInfo);
  49558. }
  49559. this._index += shape.length;
  49560. idx++;
  49561. }
  49562. this.nbParticles += nb;
  49563. this._shapeCounter++;
  49564. return this._shapeCounter - 1;
  49565. };
  49566. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  49567. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  49568. this._resetCopy();
  49569. if (particle._model._positionFunction) {
  49570. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  49571. }
  49572. if (this._copy.rotationQuaternion) {
  49573. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  49574. }
  49575. else {
  49576. this._yaw = this._copy.rotation.y;
  49577. this._pitch = this._copy.rotation.x;
  49578. this._roll = this._copy.rotation.z;
  49579. this._quaternionRotationYPR();
  49580. }
  49581. this._quaternionToRotationMatrix();
  49582. this._shape = particle._model._shape;
  49583. for (var pt = 0; pt < this._shape.length; pt++) {
  49584. this._vertex.x = this._shape[pt].x;
  49585. this._vertex.y = this._shape[pt].y;
  49586. this._vertex.z = this._shape[pt].z;
  49587. if (particle._model._vertexFunction) {
  49588. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  49589. }
  49590. this._vertex.x *= this._copy.scaling.x;
  49591. this._vertex.y *= this._copy.scaling.y;
  49592. this._vertex.z *= this._copy.scaling.z;
  49593. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  49594. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  49595. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  49596. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  49597. }
  49598. particle.position.x = 0.0;
  49599. particle.position.y = 0.0;
  49600. particle.position.z = 0.0;
  49601. particle.rotation.x = 0.0;
  49602. particle.rotation.y = 0.0;
  49603. particle.rotation.z = 0.0;
  49604. particle.rotationQuaternion = null;
  49605. particle.scaling.x = 1.0;
  49606. particle.scaling.y = 1.0;
  49607. particle.scaling.z = 1.0;
  49608. };
  49609. /**
  49610. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  49611. */
  49612. SolidParticleSystem.prototype.rebuildMesh = function () {
  49613. for (var p = 0; p < this.particles.length; p++) {
  49614. this._rebuildParticle(this.particles[p]);
  49615. }
  49616. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49617. };
  49618. /**
  49619. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  49620. * This method calls `updateParticle()` for each particle of the SPS.
  49621. * For an animated SPS, it is usually called within the render loop.
  49622. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  49623. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  49624. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  49625. */
  49626. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  49627. if (start === void 0) { start = 0; }
  49628. if (end === void 0) { end = this.nbParticles - 1; }
  49629. if (update === void 0) { update = true; }
  49630. if (!this._updatable) {
  49631. return;
  49632. }
  49633. // custom beforeUpdate
  49634. this.beforeUpdateParticles(start, end, update);
  49635. this._cam_axisX.x = 1.0;
  49636. this._cam_axisX.y = 0.0;
  49637. this._cam_axisX.z = 0.0;
  49638. this._cam_axisY.x = 0.0;
  49639. this._cam_axisY.y = 1.0;
  49640. this._cam_axisY.z = 0.0;
  49641. this._cam_axisZ.x = 0.0;
  49642. this._cam_axisZ.y = 0.0;
  49643. this._cam_axisZ.z = 1.0;
  49644. // if the particles will always face the camera
  49645. if (this.billboard) {
  49646. // compute the camera position and un-rotate it by the current mesh rotation
  49647. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  49648. this._quaternionToRotationMatrix();
  49649. this._rotMatrix.invertToRef(this._invertMatrix);
  49650. this._camera._currentTarget.subtractToRef(this._camera.globalPosition, this._camDir);
  49651. BABYLON.Vector3.TransformCoordinatesToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  49652. this._cam_axisZ.normalize();
  49653. // set two orthogonal vectors (_cam_axisX and and _cam_axisY) to the rotated camDir axis (_cam_axisZ)
  49654. BABYLON.Vector3.CrossToRef(this._cam_axisZ, this._axisX, this._cam_axisY);
  49655. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  49656. this._cam_axisY.normalize();
  49657. this._cam_axisX.normalize();
  49658. }
  49659. }
  49660. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  49661. var idx = 0;
  49662. var index = 0;
  49663. var colidx = 0;
  49664. var colorIndex = 0;
  49665. var uvidx = 0;
  49666. var uvIndex = 0;
  49667. var pt = 0;
  49668. if (this._computeBoundingBox) {
  49669. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  49670. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  49671. }
  49672. // particle loop
  49673. end = (end > this.nbParticles - 1) ? this.nbParticles - 1 : end;
  49674. for (var p = start; p <= end; p++) {
  49675. this._particle = this.particles[p];
  49676. this._shape = this._particle._model._shape;
  49677. this._shapeUV = this._particle._model._shapeUV;
  49678. // call to custom user function to update the particle properties
  49679. this.updateParticle(this._particle);
  49680. if (this._particle.isVisible) {
  49681. // particle rotation matrix
  49682. if (this.billboard) {
  49683. this._particle.rotation.x = 0.0;
  49684. this._particle.rotation.y = 0.0;
  49685. }
  49686. if (this._computeParticleRotation || this.billboard) {
  49687. if (this._particle.rotationQuaternion) {
  49688. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  49689. }
  49690. else {
  49691. this._yaw = this._particle.rotation.y;
  49692. this._pitch = this._particle.rotation.x;
  49693. this._roll = this._particle.rotation.z;
  49694. this._quaternionRotationYPR();
  49695. }
  49696. this._quaternionToRotationMatrix();
  49697. }
  49698. // particle vertex loop
  49699. for (pt = 0; pt < this._shape.length; pt++) {
  49700. idx = index + pt * 3;
  49701. colidx = colorIndex + pt * 4;
  49702. uvidx = uvIndex + pt * 2;
  49703. this._vertex.x = this._shape[pt].x;
  49704. this._vertex.y = this._shape[pt].y;
  49705. this._vertex.z = this._shape[pt].z;
  49706. if (this._computeParticleVertex) {
  49707. this.updateParticleVertex(this._particle, this._vertex, pt);
  49708. }
  49709. // positions
  49710. this._vertex.x *= this._particle.scaling.x;
  49711. this._vertex.y *= this._particle.scaling.y;
  49712. this._vertex.z *= this._particle.scaling.z;
  49713. 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];
  49714. 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;
  49715. 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;
  49716. 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;
  49717. 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;
  49718. 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;
  49719. 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;
  49720. if (this._computeBoundingBox) {
  49721. if (this._positions32[idx] < this._minimum.x) {
  49722. this._minimum.x = this._positions32[idx];
  49723. }
  49724. if (this._positions32[idx] > this._maximum.x) {
  49725. this._maximum.x = this._positions32[idx];
  49726. }
  49727. if (this._positions32[idx + 1] < this._minimum.y) {
  49728. this._minimum.y = this._positions32[idx + 1];
  49729. }
  49730. if (this._positions32[idx + 1] > this._maximum.y) {
  49731. this._maximum.y = this._positions32[idx + 1];
  49732. }
  49733. if (this._positions32[idx + 2] < this._minimum.z) {
  49734. this._minimum.z = this._positions32[idx + 2];
  49735. }
  49736. if (this._positions32[idx + 2] > this._maximum.z) {
  49737. this._maximum.z = this._positions32[idx + 2];
  49738. }
  49739. }
  49740. // normals : if the particles can't be morphed then just rotate the normals, what if much more faster than ComputeNormals()
  49741. if (!this._computeParticleVertex) {
  49742. this._normal.x = this._fixedNormal32[idx];
  49743. this._normal.y = this._fixedNormal32[idx + 1];
  49744. this._normal.z = this._fixedNormal32[idx + 2];
  49745. 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];
  49746. 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;
  49747. 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;
  49748. 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;
  49749. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  49750. 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;
  49751. 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;
  49752. }
  49753. if (this._computeParticleColor) {
  49754. this._colors32[colidx] = this._particle.color.r;
  49755. this._colors32[colidx + 1] = this._particle.color.g;
  49756. this._colors32[colidx + 2] = this._particle.color.b;
  49757. this._colors32[colidx + 3] = this._particle.color.a;
  49758. }
  49759. if (this._computeParticleTexture) {
  49760. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49761. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49762. }
  49763. }
  49764. }
  49765. else {
  49766. for (pt = 0; pt < this._shape.length; pt++) {
  49767. idx = index + pt * 3;
  49768. colidx = colorIndex + pt * 4;
  49769. uvidx = uvIndex + pt * 2;
  49770. this._positions32[idx] = this._camera.position.x;
  49771. this._positions32[idx + 1] = this._camera.position.y;
  49772. this._positions32[idx + 2] = this._camera.position.z;
  49773. this._normals32[idx] = 0.0;
  49774. this._normals32[idx + 1] = 0.0;
  49775. this._normals32[idx + 2] = 0.0;
  49776. if (this._computeParticleColor) {
  49777. this._colors32[colidx] = this._particle.color.r;
  49778. this._colors32[colidx + 1] = this._particle.color.g;
  49779. this._colors32[colidx + 2] = this._particle.color.b;
  49780. this._colors32[colidx + 3] = this._particle.color.a;
  49781. }
  49782. if (this._computeParticleTexture) {
  49783. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  49784. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  49785. }
  49786. }
  49787. }
  49788. // if the particle intersections must be computed : update the bbInfo
  49789. if (this._particlesIntersect) {
  49790. var bInfo = this._particle._boundingInfo;
  49791. var bBox = bInfo.boundingBox;
  49792. var bSphere = bInfo.boundingSphere;
  49793. if (!this._bSphereOnly) {
  49794. // place, scale and rotate the particle bbox within the SPS local system, then update it
  49795. for (var b = 0; b < bBox.vectors.length; b++) {
  49796. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  49797. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  49798. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  49799. 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];
  49800. 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;
  49801. 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;
  49802. 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;
  49803. bBox.vectors[b].x = 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;
  49804. bBox.vectors[b].y = 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;
  49805. bBox.vectors[b].z = 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;
  49806. }
  49807. bBox._update(this.mesh._worldMatrix);
  49808. }
  49809. // place and scale the particle bouding sphere in the SPS local system, then update it
  49810. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  49811. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  49812. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  49813. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  49814. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  49815. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  49816. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  49817. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  49818. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  49819. bSphere.radius = this._bSphereRadiusFactor * 0.5 * Math.sqrt((this._maxBbox.x - this._minBbox.x) * (this._maxBbox.x - this._minBbox.x) + (this._maxBbox.y - this._minBbox.y) * (this._maxBbox.y - this._minBbox.y) + (this._maxBbox.z - this._minBbox.z) * (this._maxBbox.z - this._minBbox.z));
  49820. bSphere._update(this.mesh._worldMatrix);
  49821. }
  49822. // increment indexes for the next particle
  49823. index = idx + 3;
  49824. colorIndex = colidx + 4;
  49825. uvIndex = uvidx + 2;
  49826. }
  49827. // if the VBO must be updated
  49828. if (update) {
  49829. if (this._computeParticleColor) {
  49830. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  49831. }
  49832. if (this._computeParticleTexture) {
  49833. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  49834. }
  49835. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  49836. if (!this.mesh.areNormalsFrozen) {
  49837. if (this._computeParticleVertex) {
  49838. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  49839. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32);
  49840. for (var i = 0; i < this._normals32.length; i++) {
  49841. this._fixedNormal32[i] = this._normals32[i];
  49842. }
  49843. }
  49844. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  49845. }
  49846. }
  49847. if (this._computeBoundingBox) {
  49848. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  49849. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  49850. }
  49851. this.afterUpdateParticles(start, end, update);
  49852. };
  49853. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  49854. this._halfroll = this._roll * 0.5;
  49855. this._halfpitch = this._pitch * 0.5;
  49856. this._halfyaw = this._yaw * 0.5;
  49857. this._sinRoll = Math.sin(this._halfroll);
  49858. this._cosRoll = Math.cos(this._halfroll);
  49859. this._sinPitch = Math.sin(this._halfpitch);
  49860. this._cosPitch = Math.cos(this._halfpitch);
  49861. this._sinYaw = Math.sin(this._halfyaw);
  49862. this._cosYaw = Math.cos(this._halfyaw);
  49863. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  49864. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  49865. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  49866. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  49867. };
  49868. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  49869. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  49870. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  49871. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  49872. this._rotMatrix.m[3] = 0;
  49873. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  49874. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  49875. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  49876. this._rotMatrix.m[7] = 0;
  49877. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  49878. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  49879. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  49880. this._rotMatrix.m[11] = 0;
  49881. this._rotMatrix.m[12] = 0;
  49882. this._rotMatrix.m[13] = 0;
  49883. this._rotMatrix.m[14] = 0;
  49884. this._rotMatrix.m[15] = 1.0;
  49885. };
  49886. /**
  49887. * Disposes the SPS
  49888. */
  49889. SolidParticleSystem.prototype.dispose = function () {
  49890. this.mesh.dispose();
  49891. this.vars = null;
  49892. // drop references to internal big arrays for the GC
  49893. this._positions = null;
  49894. this._indices = null;
  49895. this._normals = null;
  49896. this._uvs = null;
  49897. this._colors = null;
  49898. this._positions32 = null;
  49899. this._normals32 = null;
  49900. this._fixedNormal32 = null;
  49901. this._uvs32 = null;
  49902. this._colors32 = null;
  49903. this.pickedParticles = null;
  49904. };
  49905. /**
  49906. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  49907. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49908. */
  49909. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  49910. if (!this._isVisibilityBoxLocked) {
  49911. this.mesh.refreshBoundingInfo();
  49912. }
  49913. };
  49914. /**
  49915. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  49916. * @param size the size (float) of the visibility box
  49917. * note : this doesn't lock the SPS mesh bounding box.
  49918. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49919. */
  49920. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  49921. var vis = size / 2;
  49922. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  49923. };
  49924. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  49925. // getter and setter
  49926. get: function () {
  49927. return this._alwaysVisible;
  49928. },
  49929. /**
  49930. * Sets the SPS as always visible or not
  49931. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49932. */
  49933. set: function (val) {
  49934. this._alwaysVisible = val;
  49935. this.mesh.alwaysSelectAsActiveMesh = val;
  49936. },
  49937. enumerable: true,
  49938. configurable: true
  49939. });
  49940. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  49941. get: function () {
  49942. return this._isVisibilityBoxLocked;
  49943. },
  49944. /**
  49945. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  49946. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  49947. */
  49948. set: function (val) {
  49949. this._isVisibilityBoxLocked = val;
  49950. this.mesh.getBoundingInfo().isLocked = val;
  49951. },
  49952. enumerable: true,
  49953. configurable: true
  49954. });
  49955. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  49956. // getters
  49957. get: function () {
  49958. return this._computeParticleRotation;
  49959. },
  49960. // Optimizer setters
  49961. /**
  49962. * Tells to `setParticles()` to compute the particle rotations or not.
  49963. * Default value : true. The SPS is faster when it's set to false.
  49964. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  49965. */
  49966. set: function (val) {
  49967. this._computeParticleRotation = val;
  49968. },
  49969. enumerable: true,
  49970. configurable: true
  49971. });
  49972. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  49973. get: function () {
  49974. return this._computeParticleColor;
  49975. },
  49976. /**
  49977. * Tells to `setParticles()` to compute the particle colors or not.
  49978. * Default value : true. The SPS is faster when it's set to false.
  49979. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  49980. */
  49981. set: function (val) {
  49982. this._computeParticleColor = val;
  49983. },
  49984. enumerable: true,
  49985. configurable: true
  49986. });
  49987. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  49988. get: function () {
  49989. return this._computeParticleTexture;
  49990. },
  49991. /**
  49992. * Tells to `setParticles()` to compute the particle textures or not.
  49993. * Default value : true. The SPS is faster when it's set to false.
  49994. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  49995. */
  49996. set: function (val) {
  49997. this._computeParticleTexture = val;
  49998. },
  49999. enumerable: true,
  50000. configurable: true
  50001. });
  50002. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  50003. get: function () {
  50004. return this._computeParticleVertex;
  50005. },
  50006. /**
  50007. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  50008. * Default value : false. The SPS is faster when it's set to false.
  50009. * Note : the particle custom vertex positions aren't stored values.
  50010. */
  50011. set: function (val) {
  50012. this._computeParticleVertex = val;
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  50018. get: function () {
  50019. return this._computeBoundingBox;
  50020. },
  50021. /**
  50022. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  50023. */
  50024. set: function (val) {
  50025. this._computeBoundingBox = val;
  50026. },
  50027. enumerable: true,
  50028. configurable: true
  50029. });
  50030. // =======================================================================
  50031. // Particle behavior logic
  50032. // these following methods may be overwritten by the user to fit his needs
  50033. /**
  50034. * This function does nothing. It may be overwritten to set all the particle first values.
  50035. * The SPS doesn't call this function, you may have to call it by your own.
  50036. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50037. */
  50038. SolidParticleSystem.prototype.initParticles = function () {
  50039. };
  50040. /**
  50041. * This function does nothing. It may be overwritten to recycle a particle.
  50042. * The SPS doesn't call this function, you may have to call it by your own.
  50043. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50044. */
  50045. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  50046. return particle;
  50047. };
  50048. /**
  50049. * Updates a particle : this function should be overwritten by the user.
  50050. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  50051. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  50052. * ex : just set a particle position or velocity and recycle conditions
  50053. */
  50054. SolidParticleSystem.prototype.updateParticle = function (particle) {
  50055. return particle;
  50056. };
  50057. /**
  50058. * Updates a vertex of a particle : it can be overwritten by the user.
  50059. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  50060. * @param particle the current particle
  50061. * @param vertex the current index of the current particle
  50062. * @param pt the index of the current vertex in the particle shape
  50063. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  50064. * ex : just set a vertex particle position
  50065. */
  50066. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  50067. return vertex;
  50068. };
  50069. /**
  50070. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  50071. * This does nothing and may be overwritten by the user.
  50072. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50073. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50074. * @param update the boolean update value actually passed to setParticles()
  50075. */
  50076. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  50077. };
  50078. /**
  50079. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  50080. * This will be passed three parameters.
  50081. * This does nothing and may be overwritten by the user.
  50082. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50083. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  50084. * @param update the boolean update value actually passed to setParticles()
  50085. */
  50086. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  50087. };
  50088. return SolidParticleSystem;
  50089. }());
  50090. BABYLON.SolidParticleSystem = SolidParticleSystem;
  50091. })(BABYLON || (BABYLON = {}));
  50092. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  50093. var BABYLON;
  50094. (function (BABYLON) {
  50095. var Internals;
  50096. (function (Internals) {
  50097. var FileFaceOrientation = (function () {
  50098. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  50099. this.name = name;
  50100. this.worldAxisForNormal = worldAxisForNormal;
  50101. this.worldAxisForFileX = worldAxisForFileX;
  50102. this.worldAxisForFileY = worldAxisForFileY;
  50103. }
  50104. return FileFaceOrientation;
  50105. }());
  50106. ;
  50107. /**
  50108. * Helper class dealing with the extraction of spherical polynomial dataArray
  50109. * from a cube map.
  50110. */
  50111. var CubeMapToSphericalPolynomialTools = (function () {
  50112. function CubeMapToSphericalPolynomialTools() {
  50113. }
  50114. /**
  50115. * Converts a cubemap to the according Spherical Polynomial data.
  50116. * This extracts the first 3 orders only as they are the only one used in the lighting.
  50117. *
  50118. * @param cubeInfo The Cube map to extract the information from.
  50119. * @return The Spherical Polynomial data.
  50120. */
  50121. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  50122. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  50123. var totalSolidAngle = 0.0;
  50124. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  50125. var du = 2.0 / cubeInfo.size;
  50126. var dv = du;
  50127. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  50128. var minUV = du * 0.5 - 1.0;
  50129. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  50130. var fileFace = this.FileFaces[faceIndex];
  50131. var dataArray = cubeInfo[fileFace.name];
  50132. var v = minUV;
  50133. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  50134. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  50135. // Because SP is still linear, so summation is fine in that basis.
  50136. for (var y = 0; y < cubeInfo.size; y++) {
  50137. var u = minUV;
  50138. for (var x = 0; x < cubeInfo.size; x++) {
  50139. // World direction (not normalised)
  50140. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  50141. worldDirection.normalize();
  50142. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  50143. if (1) {
  50144. var r = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0];
  50145. var g = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1];
  50146. var b = dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2];
  50147. var color = new BABYLON.Color3(r, g, b);
  50148. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50149. }
  50150. else {
  50151. if (faceIndex == 0) {
  50152. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50153. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50154. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50155. }
  50156. else if (faceIndex == 1) {
  50157. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50158. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50159. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50160. }
  50161. else if (faceIndex == 2) {
  50162. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50163. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50164. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50165. }
  50166. else if (faceIndex == 3) {
  50167. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50168. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50169. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 0;
  50170. }
  50171. else if (faceIndex == 4) {
  50172. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 1;
  50173. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 0;
  50174. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50175. }
  50176. else if (faceIndex == 5) {
  50177. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 0] = 0;
  50178. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 1] = 1;
  50179. dataArray[(y * cubeInfo.size * 3) + (x * 3) + 2] = 1;
  50180. }
  50181. 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]);
  50182. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  50183. }
  50184. totalSolidAngle += deltaSolidAngle;
  50185. u += du;
  50186. }
  50187. v += dv;
  50188. }
  50189. }
  50190. var correctSolidAngle = 4.0 * Math.PI; // Solid angle for entire sphere is 4*pi
  50191. var correction = correctSolidAngle / totalSolidAngle;
  50192. sphericalHarmonics.scale(correction);
  50193. // Additionally scale by pi -- audit needed
  50194. sphericalHarmonics.scale(1.0 / Math.PI);
  50195. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  50196. };
  50197. return CubeMapToSphericalPolynomialTools;
  50198. }());
  50199. CubeMapToSphericalPolynomialTools.FileFaces = [
  50200. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  50201. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  50202. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  50203. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  50204. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  50205. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  50206. ];
  50207. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  50208. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50209. })(BABYLON || (BABYLON = {}));
  50210. //# sourceMappingURL=babylon.tools.cubemapToSphericalPolynomial.js.map
  50211. var BABYLON;
  50212. (function (BABYLON) {
  50213. var Internals;
  50214. (function (Internals) {
  50215. /**
  50216. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  50217. */
  50218. var PanoramaToCubeMapTools = (function () {
  50219. function PanoramaToCubeMapTools() {
  50220. }
  50221. /**
  50222. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  50223. *
  50224. * @param float32Array The source data.
  50225. * @param inputWidth The width of the input panorama.
  50226. * @param inputhHeight The height of the input panorama.
  50227. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  50228. * @return The cubemap data
  50229. */
  50230. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  50231. if (!float32Array) {
  50232. throw "ConvertPanoramaToCubemap: input cannot be null";
  50233. }
  50234. if (float32Array.length != inputWidth * inputHeight * 3) {
  50235. throw "ConvertPanoramaToCubemap: input size is wrong";
  50236. }
  50237. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  50238. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  50239. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  50240. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  50241. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  50242. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  50243. return {
  50244. front: textureFront,
  50245. back: textureBack,
  50246. left: textureLeft,
  50247. right: textureRight,
  50248. up: textureUp,
  50249. down: textureDown,
  50250. size: size
  50251. };
  50252. };
  50253. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  50254. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  50255. var textureArray = new Float32Array(buffer);
  50256. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  50257. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  50258. var dy = 1 / texSize;
  50259. var fy = 0;
  50260. for (var y = 0; y < texSize; y++) {
  50261. var xv1 = faceData[0];
  50262. var xv2 = faceData[2];
  50263. for (var x = 0; x < texSize; x++) {
  50264. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  50265. v.normalize();
  50266. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  50267. // 3 channels per pixels
  50268. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  50269. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  50270. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  50271. xv1 = xv1.add(rotDX1);
  50272. xv2 = xv2.add(rotDX2);
  50273. }
  50274. fy += dy;
  50275. }
  50276. return textureArray;
  50277. };
  50278. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  50279. var theta = Math.atan2(vDir.z, vDir.x);
  50280. var phi = Math.acos(vDir.y);
  50281. while (theta < -Math.PI)
  50282. theta += 2 * Math.PI;
  50283. while (theta > Math.PI)
  50284. theta -= 2 * Math.PI;
  50285. var dx = theta / Math.PI;
  50286. var dy = phi / Math.PI;
  50287. // recenter.
  50288. dx = dx * 0.5 + 0.5;
  50289. var px = Math.round(dx * inputWidth);
  50290. if (px < 0)
  50291. px = 0;
  50292. else if (px >= inputWidth)
  50293. px = inputWidth - 1;
  50294. var py = Math.round(dy * inputHeight);
  50295. if (py < 0)
  50296. py = 0;
  50297. else if (py >= inputHeight)
  50298. py = inputHeight - 1;
  50299. var inputY = (inputHeight - py - 1);
  50300. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  50301. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  50302. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  50303. return {
  50304. r: r,
  50305. g: g,
  50306. b: b
  50307. };
  50308. };
  50309. return PanoramaToCubeMapTools;
  50310. }());
  50311. PanoramaToCubeMapTools.FACE_FRONT = [
  50312. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50313. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50314. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50315. new BABYLON.Vector3(1.0, 1.0, -1.0)
  50316. ];
  50317. PanoramaToCubeMapTools.FACE_BACK = [
  50318. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50319. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50320. new BABYLON.Vector3(1.0, 1.0, 1.0),
  50321. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  50322. ];
  50323. PanoramaToCubeMapTools.FACE_RIGHT = [
  50324. new BABYLON.Vector3(1.0, -1.0, -1.0),
  50325. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50326. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50327. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50328. ];
  50329. PanoramaToCubeMapTools.FACE_LEFT = [
  50330. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50331. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50332. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50333. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  50334. ];
  50335. PanoramaToCubeMapTools.FACE_DOWN = [
  50336. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  50337. new BABYLON.Vector3(1.0, 1.0, -1.0),
  50338. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  50339. new BABYLON.Vector3(1.0, 1.0, 1.0)
  50340. ];
  50341. PanoramaToCubeMapTools.FACE_UP = [
  50342. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  50343. new BABYLON.Vector3(1.0, -1.0, 1.0),
  50344. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  50345. new BABYLON.Vector3(1.0, -1.0, -1.0)
  50346. ];
  50347. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  50348. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50349. })(BABYLON || (BABYLON = {}));
  50350. //# sourceMappingURL=babylon.tools.panoramaToCubemap.js.map
  50351. var BABYLON;
  50352. (function (BABYLON) {
  50353. var Internals;
  50354. (function (Internals) {
  50355. ;
  50356. /**
  50357. * This groups tools to convert HDR texture to native colors array.
  50358. */
  50359. var HDRTools = (function () {
  50360. function HDRTools() {
  50361. }
  50362. HDRTools.Ldexp = function (mantissa, exponent) {
  50363. if (exponent > 1023) {
  50364. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  50365. }
  50366. if (exponent < -1074) {
  50367. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  50368. }
  50369. return mantissa * Math.pow(2, exponent);
  50370. };
  50371. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  50372. if (exponent > 0) {
  50373. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  50374. float32array[index + 0] = red * exponent;
  50375. float32array[index + 1] = green * exponent;
  50376. float32array[index + 2] = blue * exponent;
  50377. }
  50378. else {
  50379. float32array[index + 0] = 0;
  50380. float32array[index + 1] = 0;
  50381. float32array[index + 2] = 0;
  50382. }
  50383. };
  50384. HDRTools.readStringLine = function (uint8array, startIndex) {
  50385. var line = "";
  50386. var character = "";
  50387. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  50388. character = String.fromCharCode(uint8array[i]);
  50389. if (character == "\n") {
  50390. break;
  50391. }
  50392. line += character;
  50393. }
  50394. return line;
  50395. };
  50396. /**
  50397. * Reads header information from an RGBE texture stored in a native array.
  50398. * More information on this format are available here:
  50399. * https://en.wikipedia.org/wiki/RGBE_image_format
  50400. *
  50401. * @param uint8array The binary file stored in native array.
  50402. * @return The header information.
  50403. */
  50404. HDRTools.RGBE_ReadHeader = function (uint8array) {
  50405. var height = 0;
  50406. var width = 0;
  50407. var line = this.readStringLine(uint8array, 0);
  50408. if (line[0] != '#' || line[1] != '?') {
  50409. throw "Bad HDR Format.";
  50410. }
  50411. var endOfHeader = false;
  50412. var findFormat = false;
  50413. var lineIndex = 0;
  50414. do {
  50415. lineIndex += (line.length + 1);
  50416. line = this.readStringLine(uint8array, lineIndex);
  50417. if (line == "FORMAT=32-bit_rle_rgbe") {
  50418. findFormat = true;
  50419. }
  50420. else if (line.length == 0) {
  50421. endOfHeader = true;
  50422. }
  50423. } while (!endOfHeader);
  50424. if (!findFormat) {
  50425. throw "HDR Bad header format, unsupported FORMAT";
  50426. }
  50427. lineIndex += (line.length + 1);
  50428. line = this.readStringLine(uint8array, lineIndex);
  50429. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  50430. var match = sizeRegexp.exec(line);
  50431. // TODO. Support +Y and -X if needed.
  50432. if (match.length < 3) {
  50433. throw "HDR Bad header format, no size";
  50434. }
  50435. width = parseInt(match[2]);
  50436. height = parseInt(match[1]);
  50437. if (width < 8 || width > 0x7fff) {
  50438. throw "HDR Bad header format, unsupported size";
  50439. }
  50440. lineIndex += (line.length + 1);
  50441. return {
  50442. height: height,
  50443. width: width,
  50444. dataPosition: lineIndex
  50445. };
  50446. };
  50447. /**
  50448. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  50449. * This RGBE texture needs to store the information as a panorama.
  50450. *
  50451. * More information on this format are available here:
  50452. * https://en.wikipedia.org/wiki/RGBE_image_format
  50453. *
  50454. * @param buffer The binary file stored in an array buffer.
  50455. * @param size The expected size of the extracted cubemap.
  50456. * @return The Cube Map information.
  50457. */
  50458. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  50459. var uint8array = new Uint8Array(buffer);
  50460. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  50461. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50462. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  50463. return cubeMapData;
  50464. };
  50465. /**
  50466. * Returns the pixels data extracted from an RGBE texture.
  50467. * This pixels will be stored left to right up to down in the R G B order in one array.
  50468. *
  50469. * More information on this format are available here:
  50470. * https://en.wikipedia.org/wiki/RGBE_image_format
  50471. *
  50472. * @param uint8array The binary file stored in an array buffer.
  50473. * @param hdrInfo The header information of the file.
  50474. * @return The pixels data in RGB right to left up to down order.
  50475. */
  50476. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  50477. // Keep for multi format supports.
  50478. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  50479. };
  50480. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  50481. var num_scanlines = hdrInfo.height;
  50482. var scanline_width = hdrInfo.width;
  50483. var a, b, c, d, count;
  50484. var dataIndex = hdrInfo.dataPosition;
  50485. var index = 0, endIndex = 0, i = 0;
  50486. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  50487. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  50488. // 3 channels of 4 bytes per pixel in float.
  50489. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  50490. var resultArray = new Float32Array(resultBuffer);
  50491. // read in each successive scanline
  50492. while (num_scanlines > 0) {
  50493. a = uint8array[dataIndex++];
  50494. b = uint8array[dataIndex++];
  50495. c = uint8array[dataIndex++];
  50496. d = uint8array[dataIndex++];
  50497. if (a != 2 || b != 2 || (c & 0x80)) {
  50498. // this file is not run length encoded
  50499. throw "HDR Bad header format, not RLE";
  50500. }
  50501. if (((c << 8) | d) != scanline_width) {
  50502. throw "HDR Bad header format, wrong scan line width";
  50503. }
  50504. index = 0;
  50505. // read each of the four channels for the scanline into the buffer
  50506. for (i = 0; i < 4; i++) {
  50507. endIndex = (i + 1) * scanline_width;
  50508. while (index < endIndex) {
  50509. a = uint8array[dataIndex++];
  50510. b = uint8array[dataIndex++];
  50511. if (a > 128) {
  50512. // a run of the same value
  50513. count = a - 128;
  50514. if ((count == 0) || (count > endIndex - index)) {
  50515. throw "HDR Bad Format, bad scanline data (run)";
  50516. }
  50517. while (count-- > 0) {
  50518. scanLineArray[index++] = b;
  50519. }
  50520. }
  50521. else {
  50522. // a non-run
  50523. count = a;
  50524. if ((count == 0) || (count > endIndex - index)) {
  50525. throw "HDR Bad Format, bad scanline data (non-run)";
  50526. }
  50527. scanLineArray[index++] = b;
  50528. if (--count > 0) {
  50529. for (var j = 0; j < count; j++) {
  50530. scanLineArray[index++] = uint8array[dataIndex++];
  50531. }
  50532. }
  50533. }
  50534. }
  50535. }
  50536. // now convert data from buffer into floats
  50537. for (i = 0; i < scanline_width; i++) {
  50538. a = scanLineArray[i];
  50539. b = scanLineArray[i + scanline_width];
  50540. c = scanLineArray[i + 2 * scanline_width];
  50541. d = scanLineArray[i + 3 * scanline_width];
  50542. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  50543. }
  50544. num_scanlines--;
  50545. }
  50546. return resultArray;
  50547. };
  50548. return HDRTools;
  50549. }());
  50550. Internals.HDRTools = HDRTools;
  50551. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  50552. })(BABYLON || (BABYLON = {}));
  50553. //# sourceMappingURL=babylon.tools.hdr.js.map
  50554. //_______________________________________________________________
  50555. // Extracted from CubeMapGen:
  50556. // https://code.google.com/archive/p/cubemapgen/
  50557. //
  50558. // Following https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50559. //_______________________________________________________________
  50560. var BABYLON;
  50561. (function (BABYLON) {
  50562. var Internals;
  50563. (function (Internals) {
  50564. /**
  50565. * The bounding box information used during the conversion process.
  50566. */
  50567. var CMGBoundinBox = (function () {
  50568. function CMGBoundinBox() {
  50569. this.min = new BABYLON.Vector3(0, 0, 0);
  50570. this.max = new BABYLON.Vector3(0, 0, 0);
  50571. this.clear();
  50572. }
  50573. CMGBoundinBox.prototype.clear = function () {
  50574. this.min.x = CMGBoundinBox.MAX;
  50575. this.min.y = CMGBoundinBox.MAX;
  50576. this.min.z = CMGBoundinBox.MAX;
  50577. this.max.x = CMGBoundinBox.MIN;
  50578. this.max.y = CMGBoundinBox.MIN;
  50579. this.max.z = CMGBoundinBox.MIN;
  50580. };
  50581. CMGBoundinBox.prototype.augment = function (x, y, z) {
  50582. this.min.x = Math.min(this.min.x, x);
  50583. this.min.y = Math.min(this.min.y, y);
  50584. this.min.z = Math.min(this.min.z, z);
  50585. this.max.x = Math.max(this.max.x, x);
  50586. this.max.y = Math.max(this.max.y, y);
  50587. this.max.z = Math.max(this.max.z, z);
  50588. };
  50589. CMGBoundinBox.prototype.clampMin = function (x, y, z) {
  50590. this.min.x = Math.max(this.min.x, x);
  50591. this.min.y = Math.max(this.min.y, y);
  50592. this.min.z = Math.max(this.min.z, z);
  50593. };
  50594. CMGBoundinBox.prototype.clampMax = function (x, y, z) {
  50595. this.max.x = Math.min(this.max.x, x);
  50596. this.max.y = Math.min(this.max.y, y);
  50597. this.max.z = Math.min(this.max.z, z);
  50598. };
  50599. CMGBoundinBox.prototype.empty = function () {
  50600. if ((this.min.x > this.max.y) ||
  50601. (this.min.y > this.max.y) ||
  50602. (this.min.z > this.max.y)) {
  50603. return true;
  50604. }
  50605. else {
  50606. return false;
  50607. }
  50608. };
  50609. return CMGBoundinBox;
  50610. }());
  50611. CMGBoundinBox.MAX = Number.MAX_VALUE;
  50612. CMGBoundinBox.MIN = Number.MIN_VALUE;
  50613. /**
  50614. * Helper class to PreProcess a cubemap in order to generate mipmap according to the level of blur
  50615. * required by the glossinees of a material.
  50616. *
  50617. * This only supports the cosine drop power as well as Warp fixup generation method.
  50618. *
  50619. * This is using the process from CubeMapGen described here:
  50620. * https://seblagarde.wordpress.com/2012/06/10/amd-cubemapgen-for-physically-based-rendering/
  50621. */
  50622. var PMREMGenerator = (function () {
  50623. /**
  50624. * Constructor of the generator.
  50625. *
  50626. * @param input The different faces data from the original cubemap in the order X+ X- Y+ Y- Z+ Z-
  50627. * @param inputSize The size of the cubemap faces
  50628. * @param outputSize The size of the output cubemap faces
  50629. * @param maxNumMipLevels The max number of mip map to generate (0 means all)
  50630. * @param numChannels The number of channels stored in the cubemap (3 for RBGE for instance)
  50631. * @param isFloat Specifies if the input texture is in float or int (hdr is usually in float)
  50632. * @param specularPower The max specular level of the desired cubemap
  50633. * @param cosinePowerDropPerMip The amount of drop the specular power will follow on each mip
  50634. * @param excludeBase Specifies wether to process the level 0 (original level) or not
  50635. * @param fixup Specifies wether to apply the edge fixup algorythm or not
  50636. */
  50637. function PMREMGenerator(input, inputSize, outputSize, maxNumMipLevels, numChannels, isFloat, specularPower, cosinePowerDropPerMip, excludeBase, fixup) {
  50638. this.input = input;
  50639. this.inputSize = inputSize;
  50640. this.outputSize = outputSize;
  50641. this.maxNumMipLevels = maxNumMipLevels;
  50642. this.numChannels = numChannels;
  50643. this.isFloat = isFloat;
  50644. this.specularPower = specularPower;
  50645. this.cosinePowerDropPerMip = cosinePowerDropPerMip;
  50646. this.excludeBase = excludeBase;
  50647. this.fixup = fixup;
  50648. this._outputSurface = [];
  50649. this._numMipLevels = 0;
  50650. }
  50651. /**
  50652. * Launches the filter process and return the result.
  50653. *
  50654. * @return the filter cubemap in the form mip0 [faces1..6] .. mipN [faces1..6]
  50655. */
  50656. PMREMGenerator.prototype.filterCubeMap = function () {
  50657. // Init cubemap processor
  50658. this.init();
  50659. // Filters the cubemap
  50660. this.filterCubeMapMipChain();
  50661. // Returns the filtered mips.
  50662. return this._outputSurface;
  50663. };
  50664. PMREMGenerator.prototype.init = function () {
  50665. var i;
  50666. var j;
  50667. var mipLevelSize;
  50668. //if nax num mip levels is set to 0, set it to generate the entire mip chain
  50669. if (this.maxNumMipLevels == 0) {
  50670. this.maxNumMipLevels = PMREMGenerator.CP_MAX_MIPLEVELS;
  50671. }
  50672. //first miplevel size
  50673. mipLevelSize = this.outputSize;
  50674. //Iterate over mip chain, and init ArrayBufferView for mip-chain
  50675. for (j = 0; j < this.maxNumMipLevels; j++) {
  50676. this._outputSurface.length++;
  50677. this._outputSurface[j] = [];
  50678. //Iterate over faces for output images
  50679. for (i = 0; i < 6; i++) {
  50680. this._outputSurface[j].length++;
  50681. // Initializes a new array for the output.
  50682. if (this.isFloat) {
  50683. this._outputSurface[j][i] = new Float32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50684. }
  50685. else {
  50686. this._outputSurface[j][i] = new Uint32Array(mipLevelSize * mipLevelSize * this.numChannels);
  50687. }
  50688. }
  50689. //next mip level is half size
  50690. mipLevelSize >>= 1;
  50691. this._numMipLevels++;
  50692. //terminate if mip chain becomes too small
  50693. if (mipLevelSize == 0) {
  50694. this.maxNumMipLevels = j;
  50695. return;
  50696. }
  50697. }
  50698. };
  50699. //--------------------------------------------------------------------------------------
  50700. //Cube map filtering and mip chain generation.
  50701. // the cube map filtereing is specified using a number of parameters:
  50702. // Filtering per miplevel is specified using 2D cone angle (in degrees) that
  50703. // indicates the region of the hemisphere to filter over for each tap.
  50704. //
  50705. // Note that the top mip level is also a filtered version of the original input images
  50706. // as well in order to create mip chains for diffuse environment illumination.
  50707. // The cone angle for the top level is specified by a_BaseAngle. This can be used to
  50708. // generate mipchains used to store the resutls of preintegration across the hemisphere.
  50709. //
  50710. // Then the mip angle used to genreate the next level of the mip chain from the first level
  50711. // is a_InitialMipAngle
  50712. //
  50713. // The angle for the subsequent levels of the mip chain are specified by their parents
  50714. // filtering angle and a per-level scale and bias
  50715. // newAngle = oldAngle * a_MipAnglePerLevelScale;
  50716. //
  50717. //--------------------------------------------------------------------------------------
  50718. PMREMGenerator.prototype.filterCubeMapMipChain = function () {
  50719. // First, take count of the lighting model to modify SpecularPower
  50720. // 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;
  50721. // var refSpecularPower = this.specularPower; // Only Phong BRDF yet. This explains the line below using this.specularpower.
  50722. //Cone angle start (for generating subsequent mip levels)
  50723. var currentSpecularPower = this.specularPower;
  50724. //Build filter lookup tables based on the source miplevel size
  50725. this.precomputeFilterLookupTables(this.inputSize);
  50726. // Note that we need to filter the first level before generating mipmap
  50727. // So LevelIndex == 0 is base filtering hen LevelIndex > 0 is mipmap generation
  50728. for (var levelIndex = 0; levelIndex < this._numMipLevels; levelIndex++) {
  50729. // TODO : Write a function to copy and scale the base mipmap in output
  50730. // I am just lazy here and just put a high specular power value, and do some if.
  50731. if (this.excludeBase && (levelIndex == 0)) {
  50732. // 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).
  50733. currentSpecularPower = 100000.0;
  50734. }
  50735. // Special case for cosine power mipmap chain. For quality requirement, we always process the current mipmap from the top mipmap
  50736. var srcCubeImage = this.input;
  50737. var dstCubeImage = this._outputSurface[levelIndex];
  50738. var dstSize = this.outputSize >> levelIndex;
  50739. // Compute required angle.
  50740. var angle = this.getBaseFilterAngle(currentSpecularPower);
  50741. // filter cube surfaces
  50742. this.filterCubeSurfaces(srcCubeImage, this.inputSize, dstCubeImage, dstSize, angle, currentSpecularPower);
  50743. // fix seams
  50744. if (this.fixup) {
  50745. this.fixupCubeEdges(dstCubeImage, dstSize);
  50746. }
  50747. // Decrease the specular power to generate the mipmap chain
  50748. // TODO : Use another method for Exclude (see first comment at start of the function
  50749. if (this.excludeBase && (levelIndex == 0)) {
  50750. currentSpecularPower = this.specularPower;
  50751. }
  50752. currentSpecularPower *= this.cosinePowerDropPerMip;
  50753. }
  50754. };
  50755. //--------------------------------------------------------------------------------------
  50756. // This function return the BaseFilterAngle require by PMREMGenerator to its FilterExtends
  50757. // It allow to optimize the texel to access base on the specular power.
  50758. //--------------------------------------------------------------------------------------
  50759. PMREMGenerator.prototype.getBaseFilterAngle = function (cosinePower) {
  50760. // We want to find the alpha such that:
  50761. // cos(alpha)^cosinePower = epsilon
  50762. // That's: acos(epsilon^(1/cosinePower))
  50763. var threshold = 0.000001; // Empirical threshold (Work perfectly, didn't check for a more big number, may get some performance and still god approximation)
  50764. var angle = 180.0;
  50765. angle = Math.acos(Math.pow(threshold, 1.0 / cosinePower));
  50766. angle *= 180.0 / Math.PI; // Convert to degree
  50767. angle *= 2.0; // * 2.0f because PMREMGenerator divide by 2 later
  50768. return angle;
  50769. };
  50770. //--------------------------------------------------------------------------------------
  50771. //Builds the following lookup tables prior to filtering:
  50772. // -normalizer cube map
  50773. // -tap weight lookup table
  50774. //
  50775. //--------------------------------------------------------------------------------------
  50776. PMREMGenerator.prototype.precomputeFilterLookupTables = function (srcCubeMapWidth) {
  50777. var srcTexelAngle;
  50778. var iCubeFace;
  50779. //clear pre-existing normalizer cube map
  50780. this._normCubeMap = [];
  50781. //Normalized vectors per cubeface and per-texel solid angle
  50782. this.buildNormalizerSolidAngleCubemap(srcCubeMapWidth);
  50783. };
  50784. //--------------------------------------------------------------------------------------
  50785. //Builds a normalizer cubemap, with the texels solid angle stored in the fourth component
  50786. //
  50787. //Takes in a cube face size, and an array of 6 surfaces to write the cube faces into
  50788. //
  50789. //Note that this normalizer cube map stores the vectors in unbiased -1 to 1 range.
  50790. // if _bx2 style scaled and biased vectors are needed, uncomment the SCALE and BIAS
  50791. // below
  50792. //--------------------------------------------------------------------------------------
  50793. PMREMGenerator.prototype.buildNormalizerSolidAngleCubemap = function (size) {
  50794. var iCubeFace;
  50795. var u;
  50796. var v;
  50797. //iterate over cube faces
  50798. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50799. //First three channels for norm cube, and last channel for solid angle
  50800. this._normCubeMap.push(new Float32Array(size * size * 4));
  50801. //fast texture walk, build normalizer cube map
  50802. var facesData = this.input[iCubeFace];
  50803. for (v = 0; v < size; v++) {
  50804. for (u = 0; u < size; u++) {
  50805. var vect = this.texelCoordToVect(iCubeFace, u, v, size, this.fixup);
  50806. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 0] = vect.x;
  50807. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 1] = vect.y;
  50808. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 2] = vect.z;
  50809. var solidAngle = this.texelCoordSolidAngle(iCubeFace, u, v, size);
  50810. this._normCubeMap[iCubeFace][(v * size + u) * 4 + 4] = solidAngle;
  50811. }
  50812. }
  50813. }
  50814. };
  50815. //--------------------------------------------------------------------------------------
  50816. // Convert cubemap face texel coordinates and face idx to 3D vector
  50817. // note the U and V coords are integer coords and range from 0 to size-1
  50818. // this routine can be used to generate a normalizer cube map
  50819. //--------------------------------------------------------------------------------------
  50820. // SL BEGIN
  50821. PMREMGenerator.prototype.texelCoordToVect = function (faceIdx, u, v, size, fixup) {
  50822. var nvcU;
  50823. var nvcV;
  50824. var tempVec;
  50825. // Change from original AMD code
  50826. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50827. // + 0.5f is for texel center addressing
  50828. nvcU = (2.0 * (u + 0.5) / size) - 1.0;
  50829. nvcV = (2.0 * (v + 0.5) / size) - 1.0;
  50830. // warp fixup
  50831. if (fixup && size > 1) {
  50832. // Code from Nvtt : http://code.google.com/p/nvidia-texture-tools/source/browse/trunk/src/nvtt/CubeSurface.cpp
  50833. var a = Math.pow(size, 2.0) / Math.pow(size - 1, 3.0);
  50834. nvcU = a * Math.pow(nvcU, 3) + nvcU;
  50835. nvcV = a * Math.pow(nvcV, 3) + nvcV;
  50836. }
  50837. // Get current vector
  50838. // generate x,y,z vector (xform 2d NVC coord to 3D vector)
  50839. // U contribution
  50840. var UVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50841. PMREMGenerator._vectorTemp.x = UVec[0] * nvcU;
  50842. PMREMGenerator._vectorTemp.y = UVec[1] * nvcU;
  50843. PMREMGenerator._vectorTemp.z = UVec[2] * nvcU;
  50844. // V contribution and Sum
  50845. var VVec = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50846. PMREMGenerator._vectorTemp.x += VVec[0] * nvcV;
  50847. PMREMGenerator._vectorTemp.y += VVec[1] * nvcV;
  50848. PMREMGenerator._vectorTemp.z += VVec[2] * nvcV;
  50849. //add face axis
  50850. var faceAxis = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_FACEAXIS];
  50851. PMREMGenerator._vectorTemp.x += faceAxis[0];
  50852. PMREMGenerator._vectorTemp.y += faceAxis[1];
  50853. PMREMGenerator._vectorTemp.z += faceAxis[2];
  50854. //normalize vector
  50855. PMREMGenerator._vectorTemp.normalize();
  50856. return PMREMGenerator._vectorTemp;
  50857. };
  50858. //--------------------------------------------------------------------------------------
  50859. // Convert 3D vector to cubemap face texel coordinates and face idx
  50860. // note the U and V coords are integer coords and range from 0 to size-1
  50861. // this routine can be used to generate a normalizer cube map
  50862. //
  50863. // returns face IDX and texel coords
  50864. //--------------------------------------------------------------------------------------
  50865. // SL BEGIN
  50866. /*
  50867. Mapping Texture Coordinates to Cube Map Faces
  50868. Because there are multiple faces, the mapping of texture coordinates to positions on cube map faces
  50869. is more complicated than the other texturing targets. The EXT_texture_cube_map extension is purposefully
  50870. designed to be consistent with DirectX 7's cube map arrangement. This is also consistent with the cube
  50871. map arrangement in Pixar's RenderMan package.
  50872. For cube map texturing, the (s,t,r) texture coordinates are treated as a direction vector (rx,ry,rz)
  50873. emanating from the center of a cube. (The q coordinate can be ignored since it merely scales the vector
  50874. without affecting the direction.) At texture application time, the interpolated per-fragment (s,t,r)
  50875. selects one of the cube map face's 2D mipmap sets based on the largest magnitude coordinate direction
  50876. the major axis direction). The target column in the table below explains how the major axis direction
  50877. maps to the 2D image of a particular cube map target.
  50878. major axis
  50879. direction target sc tc ma
  50880. ---------- --------------------------------- --- --- ---
  50881. +rx GL_TEXTURE_CUBE_MAP_POSITIVE_X_EXT -rz -ry rx
  50882. -rx GL_TEXTURE_CUBE_MAP_NEGATIVE_X_EXT +rz -ry rx
  50883. +ry GL_TEXTURE_CUBE_MAP_POSITIVE_Y_EXT +rx +rz ry
  50884. -ry GL_TEXTURE_CUBE_MAP_NEGATIVE_Y_EXT +rx -rz ry
  50885. +rz GL_TEXTURE_CUBE_MAP_POSITIVE_Z_EXT +rx -ry rz
  50886. -rz GL_TEXTURE_CUBE_MAP_NEGATIVE_Z_EXT -rx -ry rz
  50887. Using the sc, tc, and ma determined by the major axis direction as specified in the table above,
  50888. an updated (s,t) is calculated as follows
  50889. s = ( sc/|ma| + 1 ) / 2
  50890. t = ( tc/|ma| + 1 ) / 2
  50891. If |ma| is zero or very nearly zero, the results of the above two equations need not be defined
  50892. (though the result may not lead to GL interruption or termination). Once the cube map face's 2D mipmap
  50893. set and (s,t) is determined, texture fetching and filtering proceeds like standard OpenGL 2D texturing.
  50894. */
  50895. // Note this method return U and V in range from 0 to size-1
  50896. // SL END
  50897. // Store the information in vector3 for convenience (faceindex, u, v)
  50898. PMREMGenerator.prototype.vectToTexelCoord = function (x, y, z, size) {
  50899. var maxCoord;
  50900. var faceIdx;
  50901. //absolute value 3
  50902. var absX = Math.abs(x);
  50903. var absY = Math.abs(y);
  50904. var absZ = Math.abs(z);
  50905. if (absX >= absY && absX >= absZ) {
  50906. maxCoord = absX;
  50907. if (x >= 0) {
  50908. faceIdx = PMREMGenerator.CP_FACE_X_POS;
  50909. }
  50910. else {
  50911. faceIdx = PMREMGenerator.CP_FACE_X_NEG;
  50912. }
  50913. }
  50914. else if (absY >= absX && absY >= absZ) {
  50915. maxCoord = absY;
  50916. if (y >= 0) {
  50917. faceIdx = PMREMGenerator.CP_FACE_Y_POS;
  50918. }
  50919. else {
  50920. faceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  50921. }
  50922. }
  50923. else {
  50924. maxCoord = absZ;
  50925. if (z >= 0) {
  50926. faceIdx = PMREMGenerator.CP_FACE_Z_POS;
  50927. }
  50928. else {
  50929. faceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  50930. }
  50931. }
  50932. //divide through by max coord so face vector lies on cube face
  50933. var scale = 1 / maxCoord;
  50934. x *= scale;
  50935. y *= scale;
  50936. z *= scale;
  50937. var temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_UDIR];
  50938. var nvcU = temp[0] * x + temp[1] * y + temp[2] * z;
  50939. temp = PMREMGenerator._sgFace2DMapping[faceIdx][PMREMGenerator.CP_VDIR];
  50940. var nvcV = temp[0] * x + temp[1] * y + temp[2] * z;
  50941. // Modify original AMD code to return value from 0 to Size - 1
  50942. var u = Math.floor((size - 1) * 0.5 * (nvcU + 1.0));
  50943. var v = Math.floor((size - 1) * 0.5 * (nvcV + 1.0));
  50944. PMREMGenerator._vectorTemp.x = faceIdx;
  50945. PMREMGenerator._vectorTemp.y = u;
  50946. PMREMGenerator._vectorTemp.z = v;
  50947. return PMREMGenerator._vectorTemp;
  50948. };
  50949. //--------------------------------------------------------------------------------------
  50950. //Original code from Ignacio CastaÒo
  50951. // This formula is from Manne ÷hrstrˆm's thesis.
  50952. // Take two coordiantes in the range [-1, 1] that define a portion of a
  50953. // cube face and return the area of the projection of that portion on the
  50954. // surface of the sphere.
  50955. //--------------------------------------------------------------------------------------
  50956. PMREMGenerator.prototype.areaElement = function (x, y) {
  50957. return Math.atan2(x * y, Math.sqrt(x * x + y * y + 1));
  50958. };
  50959. PMREMGenerator.prototype.texelCoordSolidAngle = function (faceIdx, u, v, size) {
  50960. // transform from [0..res - 1] to [- (1 - 1 / res) .. (1 - 1 / res)]
  50961. // (+ 0.5f is for texel center addressing)
  50962. u = (2.0 * (u + 0.5) / size) - 1.0;
  50963. v = (2.0 * (v + 0.5) / size) - 1.0;
  50964. // Shift from a demi texel, mean 1.0f / a_Size with U and V in [-1..1]
  50965. var invResolution = 1.0 / size;
  50966. // U and V are the -1..1 texture coordinate on the current face.
  50967. // Get projected area for this texel
  50968. var x0 = u - invResolution;
  50969. var y0 = v - invResolution;
  50970. var x1 = u + invResolution;
  50971. var y1 = v + invResolution;
  50972. var solidAngle = this.areaElement(x0, y0) - this.areaElement(x0, y1) - this.areaElement(x1, y0) + this.areaElement(x1, y1);
  50973. return solidAngle;
  50974. };
  50975. //--------------------------------------------------------------------------------------
  50976. //The key to the speed of these filtering routines is to quickly define a per-face
  50977. // bounding box of pixels which enclose all the taps in the filter kernel efficiently.
  50978. // Later these pixels are selectively processed based on their dot products to see if
  50979. // they reside within the filtering cone.
  50980. //
  50981. //This is done by computing the smallest per-texel angle to get a conservative estimate
  50982. // of the number of texels needed to be covered in width and height order to filter the
  50983. // region. the bounding box for the center taps face is defined first, and if the
  50984. // filtereing region bleeds onto the other faces, bounding boxes for the other faces are
  50985. // defined next
  50986. //--------------------------------------------------------------------------------------
  50987. PMREMGenerator.prototype.filterCubeSurfaces = function (srcCubeMap, srcSize, dstCubeMap, dstSize, filterConeAngle, specularPower) {
  50988. // note that pixels within these regions may be rejected
  50989. // based on the anlge
  50990. var iCubeFace;
  50991. var u;
  50992. var v;
  50993. // bounding box per face to specify region to process
  50994. var filterExtents = [];
  50995. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  50996. filterExtents.push(new CMGBoundinBox());
  50997. }
  50998. // min angle a src texel can cover (in degrees)
  50999. var srcTexelAngle = (180.0 / (Math.PI) * Math.atan2(1.0, srcSize));
  51000. // angle about center tap to define filter cone
  51001. // filter angle is 1/2 the cone angle
  51002. var filterAngle = filterConeAngle / 2.0;
  51003. //ensure filter angle is larger than a texel
  51004. if (filterAngle < srcTexelAngle) {
  51005. filterAngle = srcTexelAngle;
  51006. }
  51007. //ensure filter cone is always smaller than the hemisphere
  51008. if (filterAngle > 90.0) {
  51009. filterAngle = 90.0;
  51010. }
  51011. // the maximum number of texels in 1D the filter cone angle will cover
  51012. // used to determine bounding box size for filter extents
  51013. var filterSize = Math.ceil(filterAngle / srcTexelAngle);
  51014. // ensure conservative region always covers at least one texel
  51015. if (filterSize < 1) {
  51016. filterSize = 1;
  51017. }
  51018. // dotProdThresh threshold based on cone angle to determine whether or not taps
  51019. // reside within the cone angle
  51020. var dotProdThresh = Math.cos((Math.PI / 180.0) * filterAngle);
  51021. // process required faces
  51022. for (iCubeFace = 0; iCubeFace < 6; iCubeFace++) {
  51023. //iterate over dst cube map face texel
  51024. for (v = 0; v < dstSize; v++) {
  51025. for (u = 0; u < dstSize; u++) {
  51026. //get center tap direction
  51027. var centerTapDir = this.texelCoordToVect(iCubeFace, u, v, dstSize, this.fixup).clone();
  51028. //clear old per-face filter extents
  51029. this.clearFilterExtents(filterExtents);
  51030. //define per-face filter extents
  51031. this.determineFilterExtents(centerTapDir, srcSize, filterSize, filterExtents);
  51032. //perform filtering of src faces using filter extents
  51033. var vect = this.processFilterExtents(centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower);
  51034. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 0] = vect.x;
  51035. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 1] = vect.y;
  51036. dstCubeMap[iCubeFace][(v * dstSize + u) * this.numChannels + 2] = vect.z;
  51037. }
  51038. }
  51039. }
  51040. };
  51041. //--------------------------------------------------------------------------------------
  51042. //Clear filter extents for the 6 cube map faces
  51043. //--------------------------------------------------------------------------------------
  51044. PMREMGenerator.prototype.clearFilterExtents = function (filterExtents) {
  51045. for (var iCubeFaces = 0; iCubeFaces < 6; iCubeFaces++) {
  51046. filterExtents[iCubeFaces].clear();
  51047. }
  51048. };
  51049. //--------------------------------------------------------------------------------------
  51050. //Define per-face bounding box filter extents
  51051. //
  51052. // These define conservative texel regions in each of the faces the filter can possibly
  51053. // process. When the pixels in the regions are actually processed, the dot product
  51054. // between the tap vector and the center tap vector is used to determine the weight of
  51055. // the tap and whether or not the tap is within the cone.
  51056. //
  51057. //--------------------------------------------------------------------------------------
  51058. PMREMGenerator.prototype.determineFilterExtents = function (centerTapDir, srcSize, bboxSize, filterExtents) {
  51059. //neighboring face and bleed over amount, and width of BBOX for
  51060. // left, right, top, and bottom edges of this face
  51061. var bleedOverAmount = [0, 0, 0, 0];
  51062. var bleedOverBBoxMin = [0, 0, 0, 0];
  51063. var bleedOverBBoxMax = [0, 0, 0, 0];
  51064. var neighborFace;
  51065. var neighborEdge;
  51066. var oppositeFaceIdx;
  51067. //get face idx, and u, v info from center tap dir
  51068. var result = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize);
  51069. var faceIdx = result.x;
  51070. var u = result.y;
  51071. var v = result.z;
  51072. //define bbox size within face
  51073. filterExtents[faceIdx].augment(u - bboxSize, v - bboxSize, 0);
  51074. filterExtents[faceIdx].augment(u + bboxSize, v + bboxSize, 0);
  51075. filterExtents[faceIdx].clampMin(0, 0, 0);
  51076. filterExtents[faceIdx].clampMax(srcSize - 1, srcSize - 1, 0);
  51077. //u and v extent in face corresponding to center tap
  51078. var minU = filterExtents[faceIdx].min.x;
  51079. var minV = filterExtents[faceIdx].min.y;
  51080. var maxU = filterExtents[faceIdx].max.x;
  51081. var maxV = filterExtents[faceIdx].max.y;
  51082. //bleed over amounts for face across u=0 edge (left)
  51083. bleedOverAmount[0] = (bboxSize - u);
  51084. bleedOverBBoxMin[0] = minV;
  51085. bleedOverBBoxMax[0] = maxV;
  51086. //bleed over amounts for face across u=1 edge (right)
  51087. bleedOverAmount[1] = (u + bboxSize) - (srcSize - 1);
  51088. bleedOverBBoxMin[1] = minV;
  51089. bleedOverBBoxMax[1] = maxV;
  51090. //bleed over to face across v=0 edge (up)
  51091. bleedOverAmount[2] = (bboxSize - v);
  51092. bleedOverBBoxMin[2] = minU;
  51093. bleedOverBBoxMax[2] = maxU;
  51094. //bleed over to face across v=1 edge (down)
  51095. bleedOverAmount[3] = (v + bboxSize) - (srcSize - 1);
  51096. bleedOverBBoxMin[3] = minU;
  51097. bleedOverBBoxMax[3] = maxU;
  51098. //compute bleed over regions in neighboring faces
  51099. for (var i = 0; i < 4; i++) {
  51100. if (bleedOverAmount[i] > 0) {
  51101. neighborFace = PMREMGenerator._sgCubeNgh[faceIdx][i][0];
  51102. neighborEdge = PMREMGenerator._sgCubeNgh[faceIdx][i][1];
  51103. //For certain types of edge abutments, the bleedOverBBoxMin, and bleedOverBBoxMax need to
  51104. // be flipped: the cases are
  51105. // if a left edge mates with a left or bottom edge on the neighbor
  51106. // if a top edge mates with a top or right edge on the neighbor
  51107. // if a right edge mates with a right or top edge on the neighbor
  51108. // if a bottom edge mates with a bottom or left edge on the neighbor
  51109. //Seeing as the edges are enumerated as follows
  51110. // left =0
  51111. // right =1
  51112. // top =2
  51113. // bottom =3
  51114. //
  51115. // so if the edge enums are the same, or the sum of the enums == 3,
  51116. // the bbox needs to be flipped
  51117. if ((i == neighborEdge) || ((i + neighborEdge) == 3)) {
  51118. bleedOverBBoxMin[i] = (srcSize - 1) - bleedOverBBoxMin[i];
  51119. bleedOverBBoxMax[i] = (srcSize - 1) - bleedOverBBoxMax[i];
  51120. }
  51121. //The way the bounding box is extended onto the neighboring face
  51122. // depends on which edge of neighboring face abuts with this one
  51123. switch (PMREMGenerator._sgCubeNgh[faceIdx][i][1]) {
  51124. case PMREMGenerator.CP_EDGE_LEFT:
  51125. filterExtents[neighborFace].augment(0, bleedOverBBoxMin[i], 0);
  51126. filterExtents[neighborFace].augment(bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51127. break;
  51128. case PMREMGenerator.CP_EDGE_RIGHT:
  51129. filterExtents[neighborFace].augment((srcSize - 1), bleedOverBBoxMin[i], 0);
  51130. filterExtents[neighborFace].augment((srcSize - 1) - bleedOverAmount[i], bleedOverBBoxMax[i], 0);
  51131. break;
  51132. case PMREMGenerator.CP_EDGE_TOP:
  51133. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], 0, 0);
  51134. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], bleedOverAmount[i], 0);
  51135. break;
  51136. case PMREMGenerator.CP_EDGE_BOTTOM:
  51137. filterExtents[neighborFace].augment(bleedOverBBoxMin[i], (srcSize - 1), 0);
  51138. filterExtents[neighborFace].augment(bleedOverBBoxMax[i], (srcSize - 1) - bleedOverAmount[i], 0);
  51139. break;
  51140. }
  51141. //clamp filter extents in non-center tap faces to remain within surface
  51142. filterExtents[neighborFace].clampMin(0, 0, 0);
  51143. filterExtents[neighborFace].clampMax(srcSize - 1, srcSize - 1, 0);
  51144. }
  51145. //If the bleed over amount bleeds past the adjacent face onto the opposite face
  51146. // from the center tap face, then process the opposite face entirely for now.
  51147. //Note that the cases in which this happens, what usually happens is that
  51148. // more than one edge bleeds onto the opposite face, and the bounding box
  51149. // encompasses the entire cube map face.
  51150. if (bleedOverAmount[i] > srcSize) {
  51151. //determine opposite face
  51152. switch (faceIdx) {
  51153. case PMREMGenerator.CP_FACE_X_POS:
  51154. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_NEG;
  51155. break;
  51156. case PMREMGenerator.CP_FACE_X_NEG:
  51157. oppositeFaceIdx = PMREMGenerator.CP_FACE_X_POS;
  51158. break;
  51159. case PMREMGenerator.CP_FACE_Y_POS:
  51160. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_NEG;
  51161. break;
  51162. case PMREMGenerator.CP_FACE_Y_NEG:
  51163. oppositeFaceIdx = PMREMGenerator.CP_FACE_Y_POS;
  51164. break;
  51165. case PMREMGenerator.CP_FACE_Z_POS:
  51166. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_NEG;
  51167. break;
  51168. case PMREMGenerator.CP_FACE_Z_NEG:
  51169. oppositeFaceIdx = PMREMGenerator.CP_FACE_Z_POS;
  51170. break;
  51171. default:
  51172. break;
  51173. }
  51174. //just encompass entire face for now
  51175. filterExtents[oppositeFaceIdx].augment(0, 0, 0);
  51176. filterExtents[oppositeFaceIdx].augment((srcSize - 1), (srcSize - 1), 0);
  51177. }
  51178. }
  51179. };
  51180. //--------------------------------------------------------------------------------------
  51181. //ProcessFilterExtents
  51182. // Process bounding box in each cube face
  51183. //
  51184. //--------------------------------------------------------------------------------------
  51185. PMREMGenerator.prototype.processFilterExtents = function (centerTapDir, dotProdThresh, filterExtents, srcCubeMap, srcSize, specularPower) {
  51186. //accumulators are 64-bit floats in order to have the precision needed
  51187. // over a summation of a large number of pixels
  51188. var dstAccum = [0, 0, 0, 0];
  51189. var weightAccum = 0;
  51190. var k = 0;
  51191. var nSrcChannels = this.numChannels;
  51192. // norm cube map and srcCubeMap have same face width
  51193. var faceWidth = srcSize;
  51194. //amount to add to pointer to move to next scanline in images
  51195. var normCubePitch = faceWidth * 4; // 4 channels in normCubeMap.
  51196. var srcCubePitch = faceWidth * this.numChannels; // numChannels correponds to the cubemap number of channel
  51197. var IsPhongBRDF = 1; // Only works in Phong BRDF yet.
  51198. //(a_LightingModel == CP_LIGHTINGMODEL_PHONG_BRDF || a_LightingModel == CP_LIGHTINGMODEL_BLINN_BRDF) ? 1 : 0; // This value will be added to the specular power
  51199. // iterate over cubefaces
  51200. for (var iFaceIdx = 0; iFaceIdx < 6; iFaceIdx++) {
  51201. //if bbox is non empty
  51202. if (!filterExtents[iFaceIdx].empty()) {
  51203. var uStart = filterExtents[iFaceIdx].min.x;
  51204. var vStart = filterExtents[iFaceIdx].min.y;
  51205. var uEnd = filterExtents[iFaceIdx].max.x;
  51206. var vEnd = filterExtents[iFaceIdx].max.y;
  51207. var startIndexNormCubeMap = (4 * ((vStart * faceWidth) + uStart));
  51208. var startIndexSrcCubeMap = (this.numChannels * ((vStart * faceWidth) + uStart));
  51209. //note that <= is used to ensure filter extents always encompass at least one pixel if bbox is non empty
  51210. for (var v = vStart; v <= vEnd; v++) {
  51211. var normCubeRowWalk = 0;
  51212. var srcCubeRowWalk = 0;
  51213. for (var u = uStart; u <= uEnd; u++) {
  51214. //pointer to direction in cube map associated with texel
  51215. var texelVectX = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 0];
  51216. var texelVectY = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 1];
  51217. var texelVectZ = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 2];
  51218. //check dot product to see if texel is within cone
  51219. var tapDotProd = texelVectX * centerTapDir.x +
  51220. texelVectY * centerTapDir.y +
  51221. texelVectZ * centerTapDir.z;
  51222. if (tapDotProd >= dotProdThresh && tapDotProd > 0.0) {
  51223. //solid angle stored in 4th channel of normalizer/solid angle cube map
  51224. var weight = this._normCubeMap[iFaceIdx][startIndexNormCubeMap + normCubeRowWalk + 3];
  51225. // Here we decide if we use a Phong/Blinn or a Phong/Blinn BRDF.
  51226. // Phong/Blinn BRDF is just the Phong/Blinn model multiply by the cosine of the lambert law
  51227. // so just adding one to specularpower do the trick.
  51228. weight *= Math.pow(tapDotProd, (specularPower + IsPhongBRDF));
  51229. //iterate over channels
  51230. for (k = 0; k < nSrcChannels; k++) {
  51231. dstAccum[k] += weight * srcCubeMap[iFaceIdx][startIndexSrcCubeMap + srcCubeRowWalk];
  51232. srcCubeRowWalk++;
  51233. }
  51234. weightAccum += weight; //accumulate weight
  51235. }
  51236. else {
  51237. //step across source pixel
  51238. srcCubeRowWalk += nSrcChannels;
  51239. }
  51240. normCubeRowWalk += 4; // 4 channels per norm cube map.
  51241. }
  51242. startIndexNormCubeMap += normCubePitch;
  51243. startIndexSrcCubeMap += srcCubePitch;
  51244. }
  51245. }
  51246. }
  51247. //divide through by weights if weight is non zero
  51248. if (weightAccum != 0.0) {
  51249. PMREMGenerator._vectorTemp.x = (dstAccum[0] / weightAccum);
  51250. PMREMGenerator._vectorTemp.y = (dstAccum[1] / weightAccum);
  51251. PMREMGenerator._vectorTemp.z = (dstAccum[2] / weightAccum);
  51252. if (this.numChannels > 3) {
  51253. PMREMGenerator._vectorTemp.w = (dstAccum[3] / weightAccum);
  51254. }
  51255. }
  51256. else {
  51257. // otherwise sample nearest
  51258. // get face idx and u, v texel coordinate in face
  51259. var coord = this.vectToTexelCoord(centerTapDir.x, centerTapDir.y, centerTapDir.z, srcSize).clone();
  51260. PMREMGenerator._vectorTemp.x = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 0];
  51261. PMREMGenerator._vectorTemp.y = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 1];
  51262. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 2];
  51263. if (this.numChannels > 3) {
  51264. PMREMGenerator._vectorTemp.z = srcCubeMap[coord.x][this.numChannels * (coord.z * srcSize + coord.y) + 3];
  51265. }
  51266. }
  51267. return PMREMGenerator._vectorTemp;
  51268. };
  51269. //--------------------------------------------------------------------------------------
  51270. // Fixup cube edges
  51271. //
  51272. // average texels on cube map faces across the edges
  51273. // WARP/BENT Method Only.
  51274. //--------------------------------------------------------------------------------------
  51275. PMREMGenerator.prototype.fixupCubeEdges = function (cubeMap, cubeMapSize) {
  51276. var k;
  51277. var j;
  51278. var i;
  51279. var iFace;
  51280. var iCorner = 0;
  51281. var cornerNumPtrs = [0, 0, 0, 0, 0, 0, 0, 0]; //indexed by corner and face idx
  51282. var faceCornerStartIndicies = [[], [], [], []]; //corner pointers for face keeping track of the face they belong to.
  51283. // note that if functionality to filter across the three texels for each corner, then
  51284. //indexed by corner and face idx. the array contains the face the start points belongs to.
  51285. var cornerPtr = [
  51286. [[], [], []],
  51287. [[], [], []],
  51288. [[], [], []],
  51289. [[], [], []],
  51290. [[], [], []],
  51291. [[], [], []],
  51292. [[], [], []],
  51293. [[], [], []]
  51294. ];
  51295. //if there is no fixup, or fixup width = 0, do nothing
  51296. if (cubeMapSize < 1) {
  51297. return;
  51298. }
  51299. //special case 1x1 cubemap, average face colors
  51300. if (cubeMapSize == 1) {
  51301. //iterate over channels
  51302. for (k = 0; k < this.numChannels; k++) {
  51303. var accum = 0.0;
  51304. //iterate over faces to accumulate face colors
  51305. for (iFace = 0; iFace < 6; iFace++) {
  51306. accum += cubeMap[iFace][k];
  51307. }
  51308. //compute average over 6 face colors
  51309. accum /= 6.0;
  51310. //iterate over faces to distribute face colors
  51311. for (iFace = 0; iFace < 6; iFace++) {
  51312. cubeMap[iFace][k] = accum;
  51313. }
  51314. }
  51315. return;
  51316. }
  51317. //iterate over faces to collect list of corner texel pointers
  51318. for (iFace = 0; iFace < 6; iFace++) {
  51319. //the 4 corner pointers for this face
  51320. faceCornerStartIndicies[0] = [iFace, 0];
  51321. faceCornerStartIndicies[1] = [iFace, ((cubeMapSize - 1) * this.numChannels)];
  51322. faceCornerStartIndicies[2] = [iFace, ((cubeMapSize) * (cubeMapSize - 1) * this.numChannels)];
  51323. faceCornerStartIndicies[3] = [iFace, ((((cubeMapSize) * (cubeMapSize - 1)) + (cubeMapSize - 1)) * this.numChannels)];
  51324. //iterate over face corners to collect cube corner pointers
  51325. for (iCorner = 0; iCorner < 4; iCorner++) {
  51326. var corner = PMREMGenerator._sgCubeCornerList[iFace][iCorner];
  51327. cornerPtr[corner][cornerNumPtrs[corner]] = faceCornerStartIndicies[iCorner];
  51328. cornerNumPtrs[corner]++;
  51329. }
  51330. }
  51331. //iterate over corners to average across corner tap values
  51332. for (iCorner = 0; iCorner < 8; iCorner++) {
  51333. for (k = 0; k < this.numChannels; k++) {
  51334. var cornerTapAccum = 0.0;
  51335. //iterate over corner texels and average results
  51336. for (i = 0; i < 3; i++) {
  51337. cornerTapAccum += cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k]; // Get in the cube map face the start point + channel.
  51338. }
  51339. //divide by 3 to compute average of corner tap values
  51340. cornerTapAccum *= (1.0 / 3.0);
  51341. //iterate over corner texels and average results
  51342. for (i = 0; i < 3; i++) {
  51343. cubeMap[cornerPtr[iCorner][i][0]][cornerPtr[iCorner][i][1] + k] = cornerTapAccum;
  51344. }
  51345. }
  51346. }
  51347. //iterate over the twelve edges of the cube to average across edges
  51348. for (i = 0; i < 12; i++) {
  51349. var face = PMREMGenerator._sgCubeEdgeList[i][0];
  51350. var edge = PMREMGenerator._sgCubeEdgeList[i][1];
  51351. var neighborFace = PMREMGenerator._sgCubeNgh[face][edge][0];
  51352. var neighborEdge = PMREMGenerator._sgCubeNgh[face][edge][1];
  51353. var edgeStartIndex = 0; // a_CubeMap[face].m_ImgData;
  51354. var neighborEdgeStartIndex = 0; // a_CubeMap[neighborFace].m_ImgData;
  51355. var edgeWalk = 0;
  51356. var neighborEdgeWalk = 0;
  51357. //Determine walking pointers based on edge type
  51358. // e.g. CP_EDGE_LEFT, CP_EDGE_RIGHT, CP_EDGE_TOP, CP_EDGE_BOTTOM
  51359. switch (edge) {
  51360. case PMREMGenerator.CP_EDGE_LEFT:
  51361. // no change to faceEdgeStartPtr
  51362. edgeWalk = this.numChannels * cubeMapSize;
  51363. break;
  51364. case PMREMGenerator.CP_EDGE_RIGHT:
  51365. edgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51366. edgeWalk = this.numChannels * cubeMapSize;
  51367. break;
  51368. case PMREMGenerator.CP_EDGE_TOP:
  51369. // no change to faceEdgeStartPtr
  51370. edgeWalk = this.numChannels;
  51371. break;
  51372. case PMREMGenerator.CP_EDGE_BOTTOM:
  51373. edgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51374. edgeWalk = this.numChannels;
  51375. break;
  51376. }
  51377. //For certain types of edge abutments, the neighbor edge walk needs to
  51378. // be flipped: the cases are
  51379. // if a left edge mates with a left or bottom edge on the neighbor
  51380. // if a top edge mates with a top or right edge on the neighbor
  51381. // if a right edge mates with a right or top edge on the neighbor
  51382. // if a bottom edge mates with a bottom or left edge on the neighbor
  51383. //Seeing as the edges are enumerated as follows
  51384. // left =0
  51385. // right =1
  51386. // top =2
  51387. // bottom =3
  51388. //
  51389. //If the edge enums are the same, or the sum of the enums == 3,
  51390. // the neighbor edge walk needs to be flipped
  51391. if ((edge == neighborEdge) || ((edge + neighborEdge) == 3)) {
  51392. switch (neighborEdge) {
  51393. case PMREMGenerator.CP_EDGE_LEFT:
  51394. neighborEdgeStartIndex += (cubeMapSize - 1) * (cubeMapSize) * this.numChannels;
  51395. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51396. break;
  51397. case PMREMGenerator.CP_EDGE_RIGHT:
  51398. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51399. neighborEdgeWalk = -(this.numChannels * cubeMapSize);
  51400. break;
  51401. case PMREMGenerator.CP_EDGE_TOP:
  51402. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51403. neighborEdgeWalk = -this.numChannels;
  51404. break;
  51405. case PMREMGenerator.CP_EDGE_BOTTOM:
  51406. neighborEdgeStartIndex += ((cubeMapSize - 1) * (cubeMapSize) + (cubeMapSize - 1)) * this.numChannels;
  51407. neighborEdgeWalk = -this.numChannels;
  51408. break;
  51409. }
  51410. }
  51411. else {
  51412. //swapped direction neighbor edge walk
  51413. switch (neighborEdge) {
  51414. case PMREMGenerator.CP_EDGE_LEFT:
  51415. //no change to neighborEdgeStartPtr for this case since it points
  51416. // to the upper left corner already
  51417. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51418. break;
  51419. case PMREMGenerator.CP_EDGE_RIGHT:
  51420. neighborEdgeStartIndex += (cubeMapSize - 1) * this.numChannels;
  51421. neighborEdgeWalk = this.numChannels * cubeMapSize;
  51422. break;
  51423. case PMREMGenerator.CP_EDGE_TOP:
  51424. //no change to neighborEdgeStartPtr for this case since it points
  51425. // to the upper left corner already
  51426. neighborEdgeWalk = this.numChannels;
  51427. break;
  51428. case PMREMGenerator.CP_EDGE_BOTTOM:
  51429. neighborEdgeStartIndex += (cubeMapSize) * (cubeMapSize - 1) * this.numChannels;
  51430. neighborEdgeWalk = this.numChannels;
  51431. break;
  51432. }
  51433. }
  51434. //Perform edge walk, to average across the 12 edges and smoothly propagate change to
  51435. //nearby neighborhood
  51436. //step ahead one texel on edge
  51437. edgeStartIndex += edgeWalk;
  51438. neighborEdgeStartIndex += neighborEdgeWalk;
  51439. // note that this loop does not process the corner texels, since they have already been
  51440. // averaged across faces across earlier
  51441. for (j = 1; j < (cubeMapSize - 1); j++) {
  51442. //for each set of taps along edge, average them
  51443. // and rewrite the results into the edges
  51444. for (k = 0; k < this.numChannels; k++) {
  51445. var edgeTap = cubeMap[face][edgeStartIndex + k];
  51446. var neighborEdgeTap = cubeMap[neighborFace][neighborEdgeStartIndex + k];
  51447. //compute average of tap intensity values
  51448. var avgTap = 0.5 * (edgeTap + neighborEdgeTap);
  51449. //propagate average of taps to edge taps
  51450. cubeMap[face][edgeStartIndex + k] = avgTap;
  51451. cubeMap[neighborFace][neighborEdgeStartIndex + k] = avgTap;
  51452. }
  51453. edgeStartIndex += edgeWalk;
  51454. neighborEdgeStartIndex += neighborEdgeWalk;
  51455. }
  51456. }
  51457. };
  51458. return PMREMGenerator;
  51459. }());
  51460. PMREMGenerator.CP_MAX_MIPLEVELS = 16;
  51461. PMREMGenerator.CP_UDIR = 0;
  51462. PMREMGenerator.CP_VDIR = 1;
  51463. PMREMGenerator.CP_FACEAXIS = 2;
  51464. //used to index cube faces
  51465. PMREMGenerator.CP_FACE_X_POS = 0;
  51466. PMREMGenerator.CP_FACE_X_NEG = 1;
  51467. PMREMGenerator.CP_FACE_Y_POS = 2;
  51468. PMREMGenerator.CP_FACE_Y_NEG = 3;
  51469. PMREMGenerator.CP_FACE_Z_POS = 4;
  51470. PMREMGenerator.CP_FACE_Z_NEG = 5;
  51471. //used to index image edges
  51472. // NOTE.. the actual number corresponding to the edge is important
  51473. // do not change these, or the code will break
  51474. //
  51475. // CP_EDGE_LEFT is u = 0
  51476. // CP_EDGE_RIGHT is u = width-1
  51477. // CP_EDGE_TOP is v = 0
  51478. // CP_EDGE_BOTTOM is v = height-1
  51479. PMREMGenerator.CP_EDGE_LEFT = 0;
  51480. PMREMGenerator.CP_EDGE_RIGHT = 1;
  51481. PMREMGenerator.CP_EDGE_TOP = 2;
  51482. PMREMGenerator.CP_EDGE_BOTTOM = 3;
  51483. //corners of CUBE map (P or N specifys if it corresponds to the
  51484. // positive or negative direction each of X, Y, and Z
  51485. PMREMGenerator.CP_CORNER_NNN = 0;
  51486. PMREMGenerator.CP_CORNER_NNP = 1;
  51487. PMREMGenerator.CP_CORNER_NPN = 2;
  51488. PMREMGenerator.CP_CORNER_NPP = 3;
  51489. PMREMGenerator.CP_CORNER_PNN = 4;
  51490. PMREMGenerator.CP_CORNER_PNP = 5;
  51491. PMREMGenerator.CP_CORNER_PPN = 6;
  51492. PMREMGenerator.CP_CORNER_PPP = 7;
  51493. PMREMGenerator._vectorTemp = new BABYLON.Vector4(0, 0, 0, 0);
  51494. //3x2 matrices that map cube map indexing vectors in 3d
  51495. // (after face selection and divide through by the
  51496. // _ABSOLUTE VALUE_ of the max coord)
  51497. // into NVC space
  51498. //Note this currently assumes the D3D cube face ordering and orientation
  51499. PMREMGenerator._sgFace2DMapping = [
  51500. //XPOS face
  51501. [[0, 0, -1],
  51502. [0, -1, 0],
  51503. [1, 0, 0]],
  51504. //XNEG face
  51505. [[0, 0, 1],
  51506. [0, -1, 0],
  51507. [-1, 0, 0]],
  51508. //YPOS face
  51509. [[1, 0, 0],
  51510. [0, 0, 1],
  51511. [0, 1, 0]],
  51512. //YNEG face
  51513. [[1, 0, 0],
  51514. [0, 0, -1],
  51515. [0, -1, 0]],
  51516. //ZPOS face
  51517. [[1, 0, 0],
  51518. [0, -1, 0],
  51519. [0, 0, 1]],
  51520. //ZNEG face
  51521. [[-1, 0, 0],
  51522. [0, -1, 0],
  51523. [0, 0, -1]],
  51524. ];
  51525. //------------------------------------------------------------------------------
  51526. // D3D cube map face specification
  51527. // mapping from 3D x,y,z cube map lookup coordinates
  51528. // to 2D within face u,v coordinates
  51529. //
  51530. // --------------------> U direction
  51531. // | (within-face texture space)
  51532. // | _____
  51533. // | | |
  51534. // | | +Y |
  51535. // | _____|_____|_____ _____
  51536. // | | | | | |
  51537. // | | -X | +Z | +X | -Z |
  51538. // | |_____|_____|_____|_____|
  51539. // | | |
  51540. // | | -Y |
  51541. // | |_____|
  51542. // |
  51543. // v V direction
  51544. // (within-face texture space)
  51545. //------------------------------------------------------------------------------
  51546. //Information about neighbors and how texture coorrdinates change across faces
  51547. // in ORDER of left, right, top, bottom (e.g. edges corresponding to u=0,
  51548. // u=1, v=0, v=1 in the 2D coordinate system of the particular face.
  51549. //Note this currently assumes the D3D cube face ordering and orientation
  51550. PMREMGenerator._sgCubeNgh = [
  51551. //XPOS face
  51552. [[PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51553. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51554. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51555. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_RIGHT]],
  51556. //XNEG face
  51557. [[PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51558. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_LEFT],
  51559. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_LEFT],
  51560. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_LEFT]],
  51561. //YPOS face
  51562. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51563. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51564. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51565. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP]],
  51566. //YNEG face
  51567. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51568. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51569. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51570. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]],
  51571. //ZPOS face
  51572. [[PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51573. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51574. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51575. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_TOP]],
  51576. //ZNEG face
  51577. [[PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51578. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51579. [PMREMGenerator.CP_FACE_Y_POS, PMREMGenerator.CP_EDGE_TOP],
  51580. [PMREMGenerator.CP_FACE_Y_NEG, PMREMGenerator.CP_EDGE_BOTTOM]]
  51581. ];
  51582. //The 12 edges of the cubemap, (entries are used to index into the neighbor table)
  51583. // this table is used to average over the edges.
  51584. PMREMGenerator._sgCubeEdgeList = [
  51585. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_LEFT],
  51586. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_RIGHT],
  51587. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_TOP],
  51588. [PMREMGenerator.CP_FACE_X_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51589. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_LEFT],
  51590. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_RIGHT],
  51591. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_TOP],
  51592. [PMREMGenerator.CP_FACE_X_NEG, PMREMGenerator.CP_EDGE_BOTTOM],
  51593. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_TOP],
  51594. [PMREMGenerator.CP_FACE_Z_POS, PMREMGenerator.CP_EDGE_BOTTOM],
  51595. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_TOP],
  51596. [PMREMGenerator.CP_FACE_Z_NEG, PMREMGenerator.CP_EDGE_BOTTOM]
  51597. ];
  51598. //Information about which of the 8 cube corners are correspond to the
  51599. // the 4 corners in each cube face
  51600. // the order is upper left, upper right, lower left, lower right
  51601. PMREMGenerator._sgCubeCornerList = [
  51602. [PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_PNN],
  51603. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_NNP],
  51604. [PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP],
  51605. [PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP, PMREMGenerator.CP_CORNER_NNN, PMREMGenerator.CP_CORNER_PNN],
  51606. [PMREMGenerator.CP_CORNER_NPP, PMREMGenerator.CP_CORNER_PPP, PMREMGenerator.CP_CORNER_NNP, PMREMGenerator.CP_CORNER_PNP],
  51607. [PMREMGenerator.CP_CORNER_PPN, PMREMGenerator.CP_CORNER_NPN, PMREMGenerator.CP_CORNER_PNN, PMREMGenerator.CP_CORNER_NNN] // ZNEG face
  51608. ];
  51609. Internals.PMREMGenerator = PMREMGenerator;
  51610. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  51611. })(BABYLON || (BABYLON = {}));
  51612. //# sourceMappingURL=babylon.tools.pmremGenerator.js.map
  51613. var BABYLON;
  51614. (function (BABYLON) {
  51615. /**
  51616. * This represents a texture coming from an HDR input.
  51617. *
  51618. * The only supported format is currently panorama picture stored in RGBE format.
  51619. * Example of such files can be found on HDRLib: http://hdrlib.com/
  51620. */
  51621. var HDRCubeTexture = (function (_super) {
  51622. __extends(HDRCubeTexture, _super);
  51623. /**
  51624. * Instantiates an HDRTexture from the following parameters.
  51625. *
  51626. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  51627. * @param scene The scene the texture will be used in
  51628. * @param size The cubemap desired size (the more it increases the longer the generation will be) If the size is omitted this implies you are using a preprocessed cubemap.
  51629. * @param noMipmap Forces to not generate the mipmap if true
  51630. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  51631. * @param useInGammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  51632. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  51633. */
  51634. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  51635. if (noMipmap === void 0) { noMipmap = false; }
  51636. if (generateHarmonics === void 0) { generateHarmonics = true; }
  51637. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  51638. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  51639. var _this = _super.call(this, scene) || this;
  51640. _this._useInGammaSpace = false;
  51641. _this._generateHarmonics = true;
  51642. _this._isBABYLONPreprocessed = false;
  51643. /**
  51644. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  51645. */
  51646. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  51647. /**
  51648. * The spherical polynomial data extracted from the texture.
  51649. */
  51650. _this.sphericalPolynomial = null;
  51651. /**
  51652. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  51653. * This is usefull at run time to apply the good shader.
  51654. */
  51655. _this.isPMREM = false;
  51656. if (!url) {
  51657. return _this;
  51658. }
  51659. _this.name = url;
  51660. _this.url = url;
  51661. _this.hasAlpha = false;
  51662. _this.isCube = true;
  51663. _this._textureMatrix = BABYLON.Matrix.Identity();
  51664. if (size) {
  51665. _this._isBABYLONPreprocessed = false;
  51666. _this._noMipmap = noMipmap;
  51667. _this._size = size;
  51668. _this._useInGammaSpace = useInGammaSpace;
  51669. _this._usePMREMGenerator = usePMREMGenerator &&
  51670. scene.getEngine().getCaps().textureLOD &&
  51671. _this.getScene().getEngine().getCaps().textureFloat &&
  51672. !_this._useInGammaSpace;
  51673. }
  51674. else {
  51675. _this._isBABYLONPreprocessed = true;
  51676. _this._noMipmap = false;
  51677. _this._useInGammaSpace = false;
  51678. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  51679. _this.getScene().getEngine().getCaps().textureFloat &&
  51680. !_this._useInGammaSpace;
  51681. }
  51682. _this.isPMREM = _this._usePMREMGenerator;
  51683. _this._texture = _this._getFromCache(url, _this._noMipmap);
  51684. if (!_this._texture) {
  51685. if (!scene.useDelayedTextureLoading) {
  51686. _this.loadTexture();
  51687. }
  51688. else {
  51689. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  51690. }
  51691. }
  51692. return _this;
  51693. }
  51694. /**
  51695. * Occurs when the file is a preprocessed .babylon.hdr file.
  51696. */
  51697. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  51698. var _this = this;
  51699. var mipLevels = 0;
  51700. var floatArrayView = null;
  51701. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  51702. var mips = [];
  51703. var startIndex = 30;
  51704. for (var level = 0; level < mipLevels; level++) {
  51705. mips.push([]);
  51706. // Fill each pixel of the mip level.
  51707. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  51708. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51709. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  51710. mips[level].push(faceData);
  51711. startIndex += faceSize;
  51712. }
  51713. }
  51714. return mips;
  51715. } : null;
  51716. var callback = function (buffer) {
  51717. // Create Native Array Views
  51718. var intArrayView = new Int32Array(buffer);
  51719. floatArrayView = new Float32Array(buffer);
  51720. // Fill header.
  51721. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  51722. _this._size = intArrayView[1]; // CubeMap max mip face size.
  51723. // Update Texture Information.
  51724. _this.getScene().getEngine().updateTextureSize(_this._texture, _this._size, _this._size);
  51725. // Fill polynomial information.
  51726. _this.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  51727. _this.sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  51728. _this.sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  51729. _this.sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  51730. _this.sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  51731. _this.sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  51732. _this.sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  51733. _this.sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  51734. _this.sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  51735. _this.sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  51736. // Fill pixel data.
  51737. mipLevels = intArrayView[29]; // Number of mip levels.
  51738. var startIndex = 30;
  51739. var data = [];
  51740. var faceSize = Math.pow(_this._size, 2) * 3;
  51741. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  51742. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  51743. startIndex += faceSize;
  51744. }
  51745. var results = [];
  51746. var byteArray = null;
  51747. // Push each faces.
  51748. for (var k = 0; k < 6; k++) {
  51749. var dataFace = null;
  51750. // If special cases.
  51751. if (!mipmapGenerator) {
  51752. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y... if no mipmapgenerator...
  51753. dataFace = data[j];
  51754. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51755. // 3 channels of 1 bytes per pixel in bytes.
  51756. var byteBuffer = new ArrayBuffer(faceSize);
  51757. byteArray = new Uint8Array(byteBuffer);
  51758. }
  51759. for (var i = 0; i < _this._size * _this._size; i++) {
  51760. // Put in gamma space if requested.
  51761. if (_this._useInGammaSpace) {
  51762. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51763. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51764. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51765. }
  51766. // Convert to int texture for fallback.
  51767. if (byteArray) {
  51768. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51769. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51770. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51771. // May use luminance instead if the result is not accurate.
  51772. var max = Math.max(Math.max(r, g), b);
  51773. if (max > 255) {
  51774. var scale = 255 / max;
  51775. r *= scale;
  51776. g *= scale;
  51777. b *= scale;
  51778. }
  51779. byteArray[(i * 3) + 0] = r;
  51780. byteArray[(i * 3) + 1] = g;
  51781. byteArray[(i * 3) + 2] = b;
  51782. }
  51783. }
  51784. }
  51785. else {
  51786. dataFace = data[k];
  51787. }
  51788. // Fill the array accordingly.
  51789. if (byteArray) {
  51790. results.push(byteArray);
  51791. }
  51792. else {
  51793. results.push(dataFace);
  51794. }
  51795. }
  51796. return results;
  51797. };
  51798. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  51799. };
  51800. /**
  51801. * Occurs when the file is raw .hdr file.
  51802. */
  51803. HDRCubeTexture.prototype.loadHDRTexture = function () {
  51804. var _this = this;
  51805. var callback = function (buffer) {
  51806. // Extract the raw linear data.
  51807. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  51808. // Generate harmonics if needed.
  51809. if (_this._generateHarmonics) {
  51810. _this.sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  51811. }
  51812. var results = [];
  51813. var byteArray = null;
  51814. // Push each faces.
  51815. for (var j = 0; j < 6; j++) {
  51816. // Create uintarray fallback.
  51817. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  51818. // 3 channels of 1 bytes per pixel in bytes.
  51819. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  51820. byteArray = new Uint8Array(byteBuffer);
  51821. }
  51822. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  51823. // If special cases.
  51824. if (_this._useInGammaSpace || byteArray) {
  51825. for (var i = 0; i < _this._size * _this._size; i++) {
  51826. // Put in gamma space if requested.
  51827. if (_this._useInGammaSpace) {
  51828. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  51829. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  51830. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  51831. }
  51832. // Convert to int texture for fallback.
  51833. if (byteArray) {
  51834. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  51835. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  51836. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  51837. // May use luminance instead if the result is not accurate.
  51838. var max = Math.max(Math.max(r, g), b);
  51839. if (max > 255) {
  51840. var scale = 255 / max;
  51841. r *= scale;
  51842. g *= scale;
  51843. b *= scale;
  51844. }
  51845. byteArray[(i * 3) + 0] = r;
  51846. byteArray[(i * 3) + 1] = g;
  51847. byteArray[(i * 3) + 2] = b;
  51848. }
  51849. }
  51850. }
  51851. if (byteArray) {
  51852. results.push(byteArray);
  51853. }
  51854. else {
  51855. results.push(dataFace);
  51856. }
  51857. }
  51858. return results;
  51859. };
  51860. var mipmapGenerator = null;
  51861. if (!this._noMipmap &&
  51862. this._usePMREMGenerator) {
  51863. mipmapGenerator = function (data) {
  51864. // Custom setup of the generator matching with the PBR shader values.
  51865. var generator = new BABYLON.Internals.PMREMGenerator(data, _this._size, _this._size, 0, 3, _this.getScene().getEngine().getCaps().textureFloat, 2048, 0.25, false, true);
  51866. return generator.filterCubeMap();
  51867. };
  51868. }
  51869. this._texture = this.getScene().getEngine().createRawCubeTexture(this.url, this.getScene(), this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, this.getScene().getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, mipmapGenerator);
  51870. };
  51871. /**
  51872. * Starts the loading process of the texture.
  51873. */
  51874. HDRCubeTexture.prototype.loadTexture = function () {
  51875. if (this._isBABYLONPreprocessed) {
  51876. this.loadBabylonTexture();
  51877. }
  51878. else {
  51879. this.loadHDRTexture();
  51880. }
  51881. };
  51882. HDRCubeTexture.prototype.clone = function () {
  51883. var size = this._isBABYLONPreprocessed ? null : this._size;
  51884. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  51885. // Base texture
  51886. newTexture.level = this.level;
  51887. newTexture.wrapU = this.wrapU;
  51888. newTexture.wrapV = this.wrapV;
  51889. newTexture.coordinatesIndex = this.coordinatesIndex;
  51890. newTexture.coordinatesMode = this.coordinatesMode;
  51891. return newTexture;
  51892. };
  51893. // Methods
  51894. HDRCubeTexture.prototype.delayLoad = function () {
  51895. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  51896. return;
  51897. }
  51898. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  51899. this._texture = this._getFromCache(this.url, this._noMipmap);
  51900. if (!this._texture) {
  51901. this.loadTexture();
  51902. }
  51903. };
  51904. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  51905. return this._textureMatrix;
  51906. };
  51907. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  51908. var texture = null;
  51909. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  51910. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  51911. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  51912. texture.name = parsedTexture.name;
  51913. texture.hasAlpha = parsedTexture.hasAlpha;
  51914. texture.level = parsedTexture.level;
  51915. texture.coordinatesMode = parsedTexture.coordinatesMode;
  51916. }
  51917. return texture;
  51918. };
  51919. HDRCubeTexture.prototype.serialize = function () {
  51920. if (!this.name) {
  51921. return null;
  51922. }
  51923. var serializationObject = {};
  51924. serializationObject.name = this.name;
  51925. serializationObject.hasAlpha = this.hasAlpha;
  51926. serializationObject.isCube = true;
  51927. serializationObject.level = this.level;
  51928. serializationObject.size = this._size;
  51929. serializationObject.coordinatesMode = this.coordinatesMode;
  51930. serializationObject.useInGammaSpace = this._useInGammaSpace;
  51931. serializationObject.generateHarmonics = this._generateHarmonics;
  51932. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  51933. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  51934. serializationObject.customType = "BABYLON.HDRCubeTexture";
  51935. return serializationObject;
  51936. };
  51937. /**
  51938. * Saves as a file the data contained in the texture in a binary format.
  51939. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51940. * as the spherical used in the lighting.
  51941. * @param url The HDR file url.
  51942. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51943. * @param onError Method called if any error happens during download.
  51944. * @return The packed binary data.
  51945. */
  51946. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  51947. if (onError === void 0) { onError = null; }
  51948. var callback = function (buffer) {
  51949. var data = new Blob([buffer], { type: 'application/octet-stream' });
  51950. // Returns a URL you can use as a href.
  51951. var objUrl = window.URL.createObjectURL(data);
  51952. // Simulates a link to it and click to dowload.
  51953. var a = document.createElement("a");
  51954. document.body.appendChild(a);
  51955. a.style.display = "none";
  51956. a.href = objUrl;
  51957. a.download = "envmap.babylon.hdr";
  51958. a.click();
  51959. };
  51960. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  51961. };
  51962. /**
  51963. * Serializes the data contained in the texture in a binary format.
  51964. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  51965. * as the spherical used in the lighting.
  51966. * @param url The HDR file url.
  51967. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  51968. * @param onError Method called if any error happens during download.
  51969. * @return The packed binary data.
  51970. */
  51971. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  51972. if (onError === void 0) { onError = null; }
  51973. // Needs the url tho create the texture.
  51974. if (!url) {
  51975. return null;
  51976. }
  51977. // Check Power of two size.
  51978. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  51979. return null;
  51980. }
  51981. var getDataCallback = function (dataBuffer) {
  51982. // Extract the raw linear data.
  51983. var cubeData = BABYLON.Internals.HDRTools.GetCubeMapTextureData(dataBuffer, size);
  51984. // Generate harmonics if needed.
  51985. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(cubeData);
  51986. // Generate seamless faces
  51987. var mipGeneratorArray = [];
  51988. // Data are known to be in +X +Y +Z -X -Y -Z
  51989. // mipmmapGenerator data is expected to be order in +X -X +Y -Y +Z -Z
  51990. mipGeneratorArray.push(cubeData.right); // +X
  51991. mipGeneratorArray.push(cubeData.left); // -X
  51992. mipGeneratorArray.push(cubeData.up); // +Y
  51993. mipGeneratorArray.push(cubeData.down); // -Y
  51994. mipGeneratorArray.push(cubeData.front); // +Z
  51995. mipGeneratorArray.push(cubeData.back); // -Z
  51996. // Custom setup of the generator matching with the PBR shader values.
  51997. var generator = new BABYLON.Internals.PMREMGenerator(mipGeneratorArray, size, size, 0, 3, true, 2048, 0.25, false, true);
  51998. var mippedData = generator.filterCubeMap();
  51999. // Compute required byte length.
  52000. var byteLength = 1 * 4; // Raw Data Version int32.
  52001. byteLength += 4; // CubeMap max mip face size int32.
  52002. byteLength += (9 * 3 * 4); // Spherical polynomial byte length 9 Vector 3 of floats.
  52003. // Add data size.
  52004. byteLength += 4; // Number of mip levels int32.
  52005. for (var level = 0; level < mippedData.length; level++) {
  52006. var mipSize = size >> level;
  52007. byteLength += (6 * mipSize * mipSize * 3 * 4); // 6 faces of size squared rgb float pixels.
  52008. }
  52009. // Prepare binary structure.
  52010. var buffer = new ArrayBuffer(byteLength);
  52011. var intArrayView = new Int32Array(buffer);
  52012. var floatArrayView = new Float32Array(buffer);
  52013. // Fill header.
  52014. intArrayView[0] = 1; // Version 1.
  52015. intArrayView[1] = size; // CubeMap max mip face size.
  52016. // Fill polynomial information.
  52017. sphericalPolynomial.x.toArray(floatArrayView, 2);
  52018. sphericalPolynomial.y.toArray(floatArrayView, 5);
  52019. sphericalPolynomial.z.toArray(floatArrayView, 8);
  52020. sphericalPolynomial.xx.toArray(floatArrayView, 11);
  52021. sphericalPolynomial.yy.toArray(floatArrayView, 14);
  52022. sphericalPolynomial.zz.toArray(floatArrayView, 17);
  52023. sphericalPolynomial.xy.toArray(floatArrayView, 20);
  52024. sphericalPolynomial.yz.toArray(floatArrayView, 23);
  52025. sphericalPolynomial.zx.toArray(floatArrayView, 26);
  52026. // Fill pixel data.
  52027. intArrayView[29] = mippedData.length; // Number of mip levels.
  52028. var startIndex = 30;
  52029. for (var level = 0; level < mippedData.length; level++) {
  52030. // Fill each pixel of the mip level.
  52031. var faceSize = Math.pow(size >> level, 2) * 3;
  52032. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  52033. floatArrayView.set(mippedData[level][faceIndex], startIndex);
  52034. startIndex += faceSize;
  52035. }
  52036. }
  52037. // Callback.
  52038. callback(buffer);
  52039. };
  52040. // Download and process.
  52041. BABYLON.Tools.LoadFile(url, function (data) {
  52042. getDataCallback(data);
  52043. }, null, null, true, onError);
  52044. };
  52045. return HDRCubeTexture;
  52046. }(BABYLON.BaseTexture));
  52047. HDRCubeTexture._facesMapping = [
  52048. "right",
  52049. "up",
  52050. "front",
  52051. "left",
  52052. "down",
  52053. "back"
  52054. ];
  52055. BABYLON.HDRCubeTexture = HDRCubeTexture;
  52056. })(BABYLON || (BABYLON = {}));
  52057. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  52058. var BABYLON;
  52059. (function (BABYLON) {
  52060. var Debug;
  52061. (function (Debug) {
  52062. /**
  52063. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  52064. */
  52065. var SkeletonViewer = (function () {
  52066. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  52067. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  52068. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  52069. this.skeleton = skeleton;
  52070. this.mesh = mesh;
  52071. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  52072. this.renderingGroupId = renderingGroupId;
  52073. this.color = BABYLON.Color3.White();
  52074. this._debugLines = [];
  52075. this._isEnabled = false;
  52076. this._scene = scene;
  52077. this.update();
  52078. this._renderFunction = this.update.bind(this);
  52079. }
  52080. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  52081. get: function () {
  52082. return this._isEnabled;
  52083. },
  52084. set: function (value) {
  52085. if (this._isEnabled === value) {
  52086. return;
  52087. }
  52088. this._isEnabled = value;
  52089. if (value) {
  52090. this._scene.registerBeforeRender(this._renderFunction);
  52091. }
  52092. else {
  52093. this._scene.unregisterBeforeRender(this._renderFunction);
  52094. }
  52095. },
  52096. enumerable: true,
  52097. configurable: true
  52098. });
  52099. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  52100. if (x === void 0) { x = 0; }
  52101. if (y === void 0) { y = 0; }
  52102. if (z === void 0) { z = 0; }
  52103. var tmat = BABYLON.Tmp.Matrix[0];
  52104. var parentBone = bone.getParent();
  52105. tmat.copyFrom(bone.getLocalMatrix());
  52106. if (x !== 0 || y !== 0 || z !== 0) {
  52107. var tmat2 = BABYLON.Tmp.Matrix[1];
  52108. BABYLON.Matrix.IdentityToRef(tmat2);
  52109. tmat2.m[12] = x;
  52110. tmat2.m[13] = y;
  52111. tmat2.m[14] = z;
  52112. tmat2.multiplyToRef(tmat, tmat);
  52113. }
  52114. if (parentBone) {
  52115. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  52116. }
  52117. tmat.multiplyToRef(meshMat, tmat);
  52118. position.x = tmat.m[12];
  52119. position.y = tmat.m[13];
  52120. position.z = tmat.m[14];
  52121. };
  52122. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  52123. var len = bones.length;
  52124. for (var i = 0; i < len; i++) {
  52125. var bone = bones[i];
  52126. var points = this._debugLines[i];
  52127. if (!points) {
  52128. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52129. this._debugLines[i] = points;
  52130. }
  52131. this._getBonePosition(points[0], bone, meshMat);
  52132. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  52133. }
  52134. };
  52135. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  52136. var len = bones.length;
  52137. var boneNum = 0;
  52138. for (var i = len - 1; i >= 0; i--) {
  52139. var childBone = bones[i];
  52140. var parentBone = childBone.getParent();
  52141. if (!parentBone) {
  52142. continue;
  52143. }
  52144. var points = this._debugLines[boneNum];
  52145. if (!points) {
  52146. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52147. this._debugLines[boneNum] = points;
  52148. }
  52149. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  52150. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  52151. boneNum++;
  52152. }
  52153. };
  52154. SkeletonViewer.prototype.update = function () {
  52155. if (this.autoUpdateBonesMatrices) {
  52156. this.skeleton.computeAbsoluteTransforms();
  52157. }
  52158. if (this.skeleton.bones[0].length === undefined) {
  52159. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52160. }
  52161. else {
  52162. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  52163. }
  52164. if (!this._debugMesh) {
  52165. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  52166. this._debugMesh.renderingGroupId = this.renderingGroupId;
  52167. }
  52168. else {
  52169. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  52170. }
  52171. this._debugMesh.color = this.color;
  52172. };
  52173. SkeletonViewer.prototype.dispose = function () {
  52174. if (this._debugMesh) {
  52175. this.isEnabled = false;
  52176. this._debugMesh.dispose();
  52177. this._debugMesh = null;
  52178. }
  52179. };
  52180. return SkeletonViewer;
  52181. }());
  52182. Debug.SkeletonViewer = SkeletonViewer;
  52183. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52184. })(BABYLON || (BABYLON = {}));
  52185. //# sourceMappingURL=babylon.skeletonViewer.js.map
  52186. var BABYLON;
  52187. (function (BABYLON) {
  52188. var Debug;
  52189. (function (Debug) {
  52190. var AxesViewer = (function () {
  52191. function AxesViewer(scene, scaleLines) {
  52192. if (scaleLines === void 0) { scaleLines = 1; }
  52193. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52194. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52195. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  52196. this.scaleLines = 1;
  52197. this.scaleLines = scaleLines;
  52198. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  52199. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  52200. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  52201. this._xmesh.renderingGroupId = 2;
  52202. this._ymesh.renderingGroupId = 2;
  52203. this._zmesh.renderingGroupId = 2;
  52204. this._xmesh.material.checkReadyOnlyOnce = true;
  52205. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  52206. this._ymesh.material.checkReadyOnlyOnce = true;
  52207. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  52208. this._zmesh.material.checkReadyOnlyOnce = true;
  52209. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  52210. this.scene = scene;
  52211. }
  52212. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  52213. var scaleLines = this.scaleLines;
  52214. var point1 = this._xline[0];
  52215. var point2 = this._xline[1];
  52216. point1.x = position.x;
  52217. point1.y = position.y;
  52218. point1.z = position.z;
  52219. point2.x = point1.x + xaxis.x * scaleLines;
  52220. point2.y = point1.y + xaxis.y * scaleLines;
  52221. point2.z = point1.z + xaxis.z * scaleLines;
  52222. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  52223. point1 = this._yline[0];
  52224. point2 = this._yline[1];
  52225. point1.x = position.x;
  52226. point1.y = position.y;
  52227. point1.z = position.z;
  52228. point2.x = point1.x + yaxis.x * scaleLines;
  52229. point2.y = point1.y + yaxis.y * scaleLines;
  52230. point2.z = point1.z + yaxis.z * scaleLines;
  52231. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  52232. point1 = this._zline[0];
  52233. point2 = this._zline[1];
  52234. point1.x = position.x;
  52235. point1.y = position.y;
  52236. point1.z = position.z;
  52237. point2.x = point1.x + zaxis.x * scaleLines;
  52238. point2.y = point1.y + zaxis.y * scaleLines;
  52239. point2.z = point1.z + zaxis.z * scaleLines;
  52240. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  52241. };
  52242. AxesViewer.prototype.dispose = function () {
  52243. if (this._xmesh) {
  52244. this._xmesh.dispose();
  52245. this._ymesh.dispose();
  52246. this._zmesh.dispose();
  52247. this._xmesh = null;
  52248. this._ymesh = null;
  52249. this._zmesh = null;
  52250. this._xline = null;
  52251. this._yline = null;
  52252. this._zline = null;
  52253. this.scene = null;
  52254. }
  52255. };
  52256. return AxesViewer;
  52257. }());
  52258. Debug.AxesViewer = AxesViewer;
  52259. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52260. })(BABYLON || (BABYLON = {}));
  52261. //# sourceMappingURL=babylon.axesViewer.js.map
  52262. var BABYLON;
  52263. (function (BABYLON) {
  52264. var Debug;
  52265. (function (Debug) {
  52266. var BoneAxesViewer = (function (_super) {
  52267. __extends(BoneAxesViewer, _super);
  52268. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  52269. if (scaleLines === void 0) { scaleLines = 1; }
  52270. var _this = _super.call(this, scene, scaleLines) || this;
  52271. _this.pos = BABYLON.Vector3.Zero();
  52272. _this.xaxis = BABYLON.Vector3.Zero();
  52273. _this.yaxis = BABYLON.Vector3.Zero();
  52274. _this.zaxis = BABYLON.Vector3.Zero();
  52275. _this.mesh = mesh;
  52276. _this.bone = bone;
  52277. return _this;
  52278. }
  52279. BoneAxesViewer.prototype.update = function () {
  52280. var bone = this.bone;
  52281. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  52282. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  52283. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  52284. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  52285. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  52286. };
  52287. BoneAxesViewer.prototype.dispose = function () {
  52288. if (this.pos) {
  52289. this.pos = null;
  52290. this.xaxis = null;
  52291. this.yaxis = null;
  52292. this.zaxis = null;
  52293. this.mesh = null;
  52294. this.bone = null;
  52295. _super.prototype.dispose.call(this);
  52296. }
  52297. };
  52298. return BoneAxesViewer;
  52299. }(Debug.AxesViewer));
  52300. Debug.BoneAxesViewer = BoneAxesViewer;
  52301. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  52302. })(BABYLON || (BABYLON = {}));
  52303. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  52304. var BABYLON;
  52305. (function (BABYLON) {
  52306. /**
  52307. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  52308. * It can help converting any input color in a desired output one. This can then be used to create effects
  52309. * from sepia, black and white to sixties or futuristic rendering...
  52310. *
  52311. * The only supported format is currently 3dl.
  52312. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  52313. */
  52314. var ColorGradingTexture = (function (_super) {
  52315. __extends(ColorGradingTexture, _super);
  52316. /**
  52317. * Instantiates a ColorGradingTexture from the following parameters.
  52318. *
  52319. * @param url The location of the color gradind data (currently only supporting 3dl)
  52320. * @param scene The scene the texture will be used in
  52321. */
  52322. function ColorGradingTexture(url, scene) {
  52323. var _this = _super.call(this, scene) || this;
  52324. if (!url) {
  52325. return _this;
  52326. }
  52327. _this._textureMatrix = BABYLON.Matrix.Identity();
  52328. _this.name = url;
  52329. _this.url = url;
  52330. _this.hasAlpha = false;
  52331. _this.isCube = false;
  52332. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52333. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  52334. _this.anisotropicFilteringLevel = 1;
  52335. _this._texture = _this._getFromCache(url, true);
  52336. if (!_this._texture) {
  52337. if (!scene.useDelayedTextureLoading) {
  52338. _this.loadTexture();
  52339. }
  52340. else {
  52341. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  52342. }
  52343. }
  52344. return _this;
  52345. }
  52346. /**
  52347. * Returns the texture matrix used in most of the material.
  52348. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  52349. */
  52350. ColorGradingTexture.prototype.getTextureMatrix = function () {
  52351. return this._textureMatrix;
  52352. };
  52353. /**
  52354. * Occurs when the file being loaded is a .3dl LUT file.
  52355. */
  52356. ColorGradingTexture.prototype.load3dlTexture = function () {
  52357. var _this = this;
  52358. var mipLevels = 0;
  52359. var floatArrayView = null;
  52360. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52361. this._texture = texture;
  52362. var callback = function (text) {
  52363. var data;
  52364. var tempData;
  52365. var line;
  52366. var lines = text.split('\n');
  52367. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  52368. var maxColor = 0;
  52369. for (var i = 0; i < lines.length; i++) {
  52370. line = lines[i];
  52371. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  52372. continue;
  52373. if (line.indexOf('#') === 0)
  52374. continue;
  52375. var words = line.split(" ");
  52376. if (size === 0) {
  52377. // Number of space + one
  52378. size = words.length;
  52379. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  52380. tempData = new Float32Array(size * size * size * 4);
  52381. continue;
  52382. }
  52383. if (size != 0) {
  52384. var r = Math.max(parseInt(words[0]), 0);
  52385. var g = Math.max(parseInt(words[1]), 0);
  52386. var b = Math.max(parseInt(words[2]), 0);
  52387. maxColor = Math.max(r, maxColor);
  52388. maxColor = Math.max(g, maxColor);
  52389. maxColor = Math.max(b, maxColor);
  52390. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  52391. tempData[pixelStorageIndex + 0] = r;
  52392. tempData[pixelStorageIndex + 1] = g;
  52393. tempData[pixelStorageIndex + 2] = b;
  52394. tempData[pixelStorageIndex + 3] = 0;
  52395. pixelIndexSlice++;
  52396. if (pixelIndexSlice % size == 0) {
  52397. pixelIndexH++;
  52398. pixelIndexSlice = 0;
  52399. if (pixelIndexH % size == 0) {
  52400. pixelIndexW++;
  52401. pixelIndexH = 0;
  52402. }
  52403. }
  52404. }
  52405. }
  52406. for (var i = 0; i < tempData.length; i++) {
  52407. var value = tempData[i];
  52408. data[i] = (value / maxColor * 255);
  52409. }
  52410. _this.getScene().getEngine().updateTextureSize(texture, size * size, size);
  52411. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  52412. };
  52413. BABYLON.Tools.LoadFile(this.url, callback);
  52414. return this._texture;
  52415. };
  52416. /**
  52417. * Starts the loading process of the texture.
  52418. */
  52419. ColorGradingTexture.prototype.loadTexture = function () {
  52420. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  52421. this.load3dlTexture();
  52422. }
  52423. };
  52424. /**
  52425. * Clones the color gradind texture.
  52426. */
  52427. ColorGradingTexture.prototype.clone = function () {
  52428. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  52429. // Base texture
  52430. newTexture.level = this.level;
  52431. return newTexture;
  52432. };
  52433. /**
  52434. * Called during delayed load for textures.
  52435. */
  52436. ColorGradingTexture.prototype.delayLoad = function () {
  52437. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  52438. return;
  52439. }
  52440. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  52441. this._texture = this._getFromCache(this.url, true);
  52442. if (!this._texture) {
  52443. this.loadTexture();
  52444. }
  52445. };
  52446. /**
  52447. * Binds the color grading to the shader.
  52448. * @param colorGrading The texture to bind
  52449. * @param effect The effect to bind to
  52450. */
  52451. ColorGradingTexture.Bind = function (colorGrading, effect) {
  52452. effect.setTexture("cameraColorGrading2DSampler", colorGrading);
  52453. var x = colorGrading.level; // Texture Level
  52454. var y = colorGrading.getSize().height; // Texture Size example with 8
  52455. var z = y - 1.0; // SizeMinusOne 8 - 1
  52456. var w = 1 / y; // Space of 1 slice 1 / 8
  52457. effect.setFloat4("vCameraColorGradingInfos", x, y, z, w);
  52458. var slicePixelSizeU = w / y; // Space of 1 pixel in U direction, e.g. 1/64
  52459. var slicePixelSizeV = w; // Space of 1 pixel in V direction, e.g. 1/8 // Space of 1 pixel in V direction, e.g. 1/8
  52460. var x2 = z * slicePixelSizeU; // Extent of lookup range in U for a single slice so that range corresponds to (size-1) texels, for example 7/64
  52461. var y2 = z / y; // Extent of lookup range in V for a single slice so that range corresponds to (size-1) texels, for example 7/8
  52462. var z2 = 0.5 * slicePixelSizeU; // Offset of lookup range in U to align sample position with texel centre, for example 0.5/64
  52463. var w2 = 0.5 * slicePixelSizeV; // Offset of lookup range in V to align sample position with texel centre, for example 0.5/8
  52464. effect.setFloat4("vCameraColorGradingScaleOffset", x2, y2, z2, w2);
  52465. };
  52466. /**
  52467. * Prepare the list of uniforms associated with the ColorGrading effects.
  52468. * @param uniformsList The list of uniforms used in the effect
  52469. * @param samplersList The list of samplers used in the effect
  52470. */
  52471. ColorGradingTexture.PrepareUniformsAndSamplers = function (uniformsList, samplersList) {
  52472. uniformsList.push("vCameraColorGradingInfos", "vCameraColorGradingScaleOffset");
  52473. samplersList.push("cameraColorGrading2DSampler");
  52474. };
  52475. /**
  52476. * Parses a color grading texture serialized by Babylon.
  52477. * @param parsedTexture The texture information being parsedTexture
  52478. * @param scene The scene to load the texture in
  52479. * @param rootUrl The root url of the data assets to load
  52480. * @return A color gradind texture
  52481. */
  52482. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  52483. var texture = null;
  52484. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  52485. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  52486. texture.name = parsedTexture.name;
  52487. texture.level = parsedTexture.level;
  52488. }
  52489. return texture;
  52490. };
  52491. /**
  52492. * Serializes the LUT texture to json format.
  52493. */
  52494. ColorGradingTexture.prototype.serialize = function () {
  52495. if (!this.name) {
  52496. return null;
  52497. }
  52498. var serializationObject = {};
  52499. serializationObject.name = this.name;
  52500. serializationObject.level = this.level;
  52501. serializationObject.customType = "BABYLON.ColorGradingTexture";
  52502. return serializationObject;
  52503. };
  52504. return ColorGradingTexture;
  52505. }(BABYLON.BaseTexture));
  52506. /**
  52507. * Empty line regex stored for GC.
  52508. */
  52509. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  52510. BABYLON.ColorGradingTexture = ColorGradingTexture;
  52511. })(BABYLON || (BABYLON = {}));
  52512. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  52513. var BABYLON;
  52514. (function (BABYLON) {
  52515. /**
  52516. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  52517. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  52518. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  52519. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  52520. */
  52521. var ColorCurves = (function () {
  52522. function ColorCurves() {
  52523. this._dirty = true;
  52524. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  52525. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  52526. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52527. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  52528. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  52529. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  52530. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  52531. this._globalHue = 30;
  52532. this._globalDensity = 0;
  52533. this._globalSaturation = 0;
  52534. this._globalExposure = 0;
  52535. this._highlightsHue = 30;
  52536. this._highlightsDensity = 0;
  52537. this._highlightsSaturation = 0;
  52538. this._highlightsExposure = 0;
  52539. this._midtonesHue = 30;
  52540. this._midtonesDensity = 0;
  52541. this._midtonesSaturation = 0;
  52542. this._midtonesExposure = 0;
  52543. this._shadowsHue = 30;
  52544. this._shadowsDensity = 0;
  52545. this._shadowsSaturation = 0;
  52546. this._shadowsExposure = 0;
  52547. }
  52548. Object.defineProperty(ColorCurves.prototype, "GlobalHue", {
  52549. /**
  52550. * Gets the global Hue value.
  52551. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52552. */
  52553. get: function () {
  52554. return this._globalHue;
  52555. },
  52556. /**
  52557. * Sets the global Hue value.
  52558. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52559. */
  52560. set: function (value) {
  52561. this._globalHue = value;
  52562. this._dirty = true;
  52563. },
  52564. enumerable: true,
  52565. configurable: true
  52566. });
  52567. Object.defineProperty(ColorCurves.prototype, "GlobalDensity", {
  52568. /**
  52569. * Gets the global Density value.
  52570. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52571. * Values less than zero provide a filter of opposite hue.
  52572. */
  52573. get: function () {
  52574. return this._globalDensity;
  52575. },
  52576. /**
  52577. * Sets the global Density value.
  52578. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52579. * Values less than zero provide a filter of opposite hue.
  52580. */
  52581. set: function (value) {
  52582. this._globalDensity = value;
  52583. this._dirty = true;
  52584. },
  52585. enumerable: true,
  52586. configurable: true
  52587. });
  52588. Object.defineProperty(ColorCurves.prototype, "GlobalSaturation", {
  52589. /**
  52590. * Gets the global Saturation value.
  52591. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52592. */
  52593. get: function () {
  52594. return this._globalSaturation;
  52595. },
  52596. /**
  52597. * Sets the global Saturation value.
  52598. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52599. */
  52600. set: function (value) {
  52601. this._globalSaturation = value;
  52602. this._dirty = true;
  52603. },
  52604. enumerable: true,
  52605. configurable: true
  52606. });
  52607. Object.defineProperty(ColorCurves.prototype, "HighlightsHue", {
  52608. /**
  52609. * Gets the highlights Hue value.
  52610. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52611. */
  52612. get: function () {
  52613. return this._highlightsHue;
  52614. },
  52615. /**
  52616. * Sets the highlights Hue value.
  52617. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52618. */
  52619. set: function (value) {
  52620. this._highlightsHue = value;
  52621. this._dirty = true;
  52622. },
  52623. enumerable: true,
  52624. configurable: true
  52625. });
  52626. Object.defineProperty(ColorCurves.prototype, "HighlightsDensity", {
  52627. /**
  52628. * Gets the highlights Density value.
  52629. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52630. * Values less than zero provide a filter of opposite hue.
  52631. */
  52632. get: function () {
  52633. return this._highlightsDensity;
  52634. },
  52635. /**
  52636. * Sets the highlights Density value.
  52637. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52638. * Values less than zero provide a filter of opposite hue.
  52639. */
  52640. set: function (value) {
  52641. this._highlightsDensity = value;
  52642. this._dirty = true;
  52643. },
  52644. enumerable: true,
  52645. configurable: true
  52646. });
  52647. Object.defineProperty(ColorCurves.prototype, "HighlightsSaturation", {
  52648. /**
  52649. * Gets the highlights Saturation value.
  52650. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52651. */
  52652. get: function () {
  52653. return this._highlightsSaturation;
  52654. },
  52655. /**
  52656. * Sets the highlights Saturation value.
  52657. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52658. */
  52659. set: function (value) {
  52660. this._highlightsSaturation = value;
  52661. this._dirty = true;
  52662. },
  52663. enumerable: true,
  52664. configurable: true
  52665. });
  52666. Object.defineProperty(ColorCurves.prototype, "HighlightsExposure", {
  52667. /**
  52668. * Gets the highlights Exposure value.
  52669. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52670. */
  52671. get: function () {
  52672. return this._highlightsExposure;
  52673. },
  52674. /**
  52675. * Sets the highlights Exposure value.
  52676. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52677. */
  52678. set: function (value) {
  52679. this._highlightsExposure = value;
  52680. this._dirty = true;
  52681. },
  52682. enumerable: true,
  52683. configurable: true
  52684. });
  52685. Object.defineProperty(ColorCurves.prototype, "MidtonesHue", {
  52686. /**
  52687. * Gets the midtones Hue value.
  52688. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52689. */
  52690. get: function () {
  52691. return this._midtonesHue;
  52692. },
  52693. /**
  52694. * Sets the midtones Hue value.
  52695. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52696. */
  52697. set: function (value) {
  52698. this._midtonesHue = value;
  52699. this._dirty = true;
  52700. },
  52701. enumerable: true,
  52702. configurable: true
  52703. });
  52704. Object.defineProperty(ColorCurves.prototype, "MidtonesDensity", {
  52705. /**
  52706. * Gets the midtones Density value.
  52707. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52708. * Values less than zero provide a filter of opposite hue.
  52709. */
  52710. get: function () {
  52711. return this._midtonesDensity;
  52712. },
  52713. /**
  52714. * Sets the midtones Density value.
  52715. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52716. * Values less than zero provide a filter of opposite hue.
  52717. */
  52718. set: function (value) {
  52719. this._midtonesDensity = value;
  52720. this._dirty = true;
  52721. },
  52722. enumerable: true,
  52723. configurable: true
  52724. });
  52725. Object.defineProperty(ColorCurves.prototype, "MidtonesSaturation", {
  52726. /**
  52727. * Gets the midtones Saturation value.
  52728. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52729. */
  52730. get: function () {
  52731. return this._midtonesSaturation;
  52732. },
  52733. /**
  52734. * Sets the midtones Saturation value.
  52735. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52736. */
  52737. set: function (value) {
  52738. this._midtonesSaturation = value;
  52739. this._dirty = true;
  52740. },
  52741. enumerable: true,
  52742. configurable: true
  52743. });
  52744. Object.defineProperty(ColorCurves.prototype, "MidtonesExposure", {
  52745. /**
  52746. * Gets the midtones Exposure value.
  52747. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52748. */
  52749. get: function () {
  52750. return this._midtonesExposure;
  52751. },
  52752. /**
  52753. * Sets the midtones Exposure value.
  52754. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52755. */
  52756. set: function (value) {
  52757. this._midtonesExposure = value;
  52758. this._dirty = true;
  52759. },
  52760. enumerable: true,
  52761. configurable: true
  52762. });
  52763. Object.defineProperty(ColorCurves.prototype, "ShadowsHue", {
  52764. /**
  52765. * Gets the shadows Hue value.
  52766. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52767. */
  52768. get: function () {
  52769. return this._shadowsHue;
  52770. },
  52771. /**
  52772. * Sets the shadows Hue value.
  52773. * The hue value is a standard HSB hue in the range [0,360] where 0=red, 120=green and 240=blue. The default value is 30 degrees (orange).
  52774. */
  52775. set: function (value) {
  52776. this._shadowsHue = value;
  52777. this._dirty = true;
  52778. },
  52779. enumerable: true,
  52780. configurable: true
  52781. });
  52782. Object.defineProperty(ColorCurves.prototype, "ShadowsDensity", {
  52783. /**
  52784. * Gets the shadows Density value.
  52785. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52786. * Values less than zero provide a filter of opposite hue.
  52787. */
  52788. get: function () {
  52789. return this._shadowsDensity;
  52790. },
  52791. /**
  52792. * Sets the shadows Density value.
  52793. * The density value is in range [-100,+100] where 0 means the color filter has no effect and +100 means the color filter has maximum effect.
  52794. * Values less than zero provide a filter of opposite hue.
  52795. */
  52796. set: function (value) {
  52797. this._shadowsDensity = value;
  52798. this._dirty = true;
  52799. },
  52800. enumerable: true,
  52801. configurable: true
  52802. });
  52803. Object.defineProperty(ColorCurves.prototype, "ShadowsSaturation", {
  52804. /**
  52805. * Gets the shadows Saturation value.
  52806. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52807. */
  52808. get: function () {
  52809. return this._shadowsSaturation;
  52810. },
  52811. /**
  52812. * Sets the shadows Saturation value.
  52813. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase saturation and negative values decrease saturation.
  52814. */
  52815. set: function (value) {
  52816. this._shadowsSaturation = value;
  52817. this._dirty = true;
  52818. },
  52819. enumerable: true,
  52820. configurable: true
  52821. });
  52822. Object.defineProperty(ColorCurves.prototype, "ShadowsExposure", {
  52823. /**
  52824. * Gets the shadows Exposure value.
  52825. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52826. */
  52827. get: function () {
  52828. return this._shadowsExposure;
  52829. },
  52830. /**
  52831. * Sets the shadows Exposure value.
  52832. * This is an adjustment value in the range [-100,+100], where the default value of 0.0 makes no adjustment, positive values increase exposure and negative values decrease exposure.
  52833. */
  52834. set: function (value) {
  52835. this._shadowsExposure = value;
  52836. this._dirty = true;
  52837. },
  52838. enumerable: true,
  52839. configurable: true
  52840. });
  52841. /**
  52842. * Binds the color curves to the shader.
  52843. * @param colorCurves The color curve to bind
  52844. * @param effect The effect to bind to
  52845. */
  52846. ColorCurves.Bind = function (colorCurves, effect) {
  52847. if (colorCurves._dirty) {
  52848. colorCurves._dirty = false;
  52849. // Fill in global info.
  52850. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  52851. // Compute highlights info.
  52852. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  52853. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  52854. // Compute midtones info.
  52855. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  52856. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  52857. // Compute shadows info.
  52858. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  52859. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  52860. // Compute deltas (neutral is midtones).
  52861. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  52862. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  52863. }
  52864. effect.setFloat4("vCameraColorCurvePositive", colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  52865. effect.setFloat4("vCameraColorCurveNeutral", colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  52866. effect.setFloat4("vCameraColorCurveNegative", colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  52867. };
  52868. /**
  52869. * Prepare the list of uniforms associated with the ColorCurves effects.
  52870. * @param uniformsList The list of uniforms used in the effect
  52871. */
  52872. ColorCurves.PrepareUniforms = function (uniformsList) {
  52873. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  52874. };
  52875. /**
  52876. * Returns color grading data based on a hue, density, saturation and exposure value.
  52877. * @param filterHue The hue of the color filter.
  52878. * @param filterDensity The density of the color filter.
  52879. * @param saturation The saturation.
  52880. * @param exposure The exposure.
  52881. * @param result The result data container.
  52882. */
  52883. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  52884. if (hue == null) {
  52885. return;
  52886. }
  52887. hue = ColorCurves.clamp(hue, 0, 360);
  52888. density = ColorCurves.clamp(density, -100, 100);
  52889. saturation = ColorCurves.clamp(saturation, -100, 100);
  52890. exposure = ColorCurves.clamp(exposure, -100, 100);
  52891. // Remap the slider/config filter density with non-linear mapping and also scale by half
  52892. // so that the maximum filter density is only 50% control. This provides fine control
  52893. // for small values and reasonable range.
  52894. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  52895. density *= 0.5;
  52896. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  52897. if (density < 0) {
  52898. density *= -1;
  52899. hue = (hue + 180) % 360;
  52900. }
  52901. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  52902. result.scaleToRef(2, result);
  52903. result.a = 1 + 0.01 * saturation;
  52904. };
  52905. /**
  52906. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  52907. * @param value The input slider value in range [-100,100].
  52908. * @returns Adjusted value.
  52909. */
  52910. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  52911. value /= 100;
  52912. var x = Math.abs(value);
  52913. x = Math.pow(x, 2);
  52914. if (value < 0) {
  52915. x *= -1;
  52916. }
  52917. x *= 100;
  52918. return x;
  52919. };
  52920. /**
  52921. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  52922. * @param hue The hue (H) input.
  52923. * @param saturation The saturation (S) input.
  52924. * @param brightness The brightness (B) input.
  52925. * @result An RGBA color represented as Vector4.
  52926. */
  52927. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  52928. var h = ColorCurves.clamp(hue, 0, 360);
  52929. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  52930. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  52931. if (s === 0) {
  52932. result.r = v;
  52933. result.g = v;
  52934. result.b = v;
  52935. }
  52936. else {
  52937. // sector 0 to 5
  52938. h /= 60;
  52939. var i = Math.floor(h);
  52940. // fractional part of h
  52941. var f = h - i;
  52942. var p = v * (1 - s);
  52943. var q = v * (1 - s * f);
  52944. var t = v * (1 - s * (1 - f));
  52945. switch (i) {
  52946. case 0:
  52947. result.r = v;
  52948. result.g = t;
  52949. result.b = p;
  52950. break;
  52951. case 1:
  52952. result.r = q;
  52953. result.g = v;
  52954. result.b = p;
  52955. break;
  52956. case 2:
  52957. result.r = p;
  52958. result.g = v;
  52959. result.b = t;
  52960. break;
  52961. case 3:
  52962. result.r = p;
  52963. result.g = q;
  52964. result.b = v;
  52965. break;
  52966. case 4:
  52967. result.r = t;
  52968. result.g = p;
  52969. result.b = v;
  52970. break;
  52971. default:
  52972. result.r = v;
  52973. result.g = p;
  52974. result.b = q;
  52975. break;
  52976. }
  52977. }
  52978. result.a = 1;
  52979. };
  52980. /**
  52981. * Returns a value clamped between min and max
  52982. * @param value The value to clamp
  52983. * @param min The minimum of value
  52984. * @param max The maximum of value
  52985. * @returns The clamped value.
  52986. */
  52987. ColorCurves.clamp = function (value, min, max) {
  52988. return Math.min(Math.max(value, min), max);
  52989. };
  52990. /**
  52991. * Clones the current color curve instance.
  52992. * @return The cloned curves
  52993. */
  52994. ColorCurves.prototype.clone = function () {
  52995. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  52996. };
  52997. /**
  52998. * Serializes the current color curve instance to a json representation.
  52999. * @return a JSON representation
  53000. */
  53001. ColorCurves.prototype.serialize = function () {
  53002. return BABYLON.SerializationHelper.Serialize(this);
  53003. };
  53004. /**
  53005. * Parses the color curve from a json representation.
  53006. * @param source the JSON source to parse
  53007. * @return The parsed curves
  53008. */
  53009. ColorCurves.Parse = function (source) {
  53010. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  53011. };
  53012. return ColorCurves;
  53013. }());
  53014. __decorate([
  53015. BABYLON.serialize()
  53016. ], ColorCurves.prototype, "_globalHue", void 0);
  53017. __decorate([
  53018. BABYLON.serialize()
  53019. ], ColorCurves.prototype, "_globalDensity", void 0);
  53020. __decorate([
  53021. BABYLON.serialize()
  53022. ], ColorCurves.prototype, "_globalSaturation", void 0);
  53023. __decorate([
  53024. BABYLON.serialize()
  53025. ], ColorCurves.prototype, "_globalExposure", void 0);
  53026. __decorate([
  53027. BABYLON.serialize()
  53028. ], ColorCurves.prototype, "_highlightsHue", void 0);
  53029. __decorate([
  53030. BABYLON.serialize()
  53031. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  53032. __decorate([
  53033. BABYLON.serialize()
  53034. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  53035. __decorate([
  53036. BABYLON.serialize()
  53037. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  53038. __decorate([
  53039. BABYLON.serialize()
  53040. ], ColorCurves.prototype, "_midtonesHue", void 0);
  53041. __decorate([
  53042. BABYLON.serialize()
  53043. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  53044. __decorate([
  53045. BABYLON.serialize()
  53046. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  53047. __decorate([
  53048. BABYLON.serialize()
  53049. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  53050. BABYLON.ColorCurves = ColorCurves;
  53051. })(BABYLON || (BABYLON = {}));
  53052. //# sourceMappingURL=babylon.colorCurves.js.map
  53053. var BABYLON;
  53054. (function (BABYLON) {
  53055. var PBRMaterialDefines = (function (_super) {
  53056. __extends(PBRMaterialDefines, _super);
  53057. function PBRMaterialDefines() {
  53058. var _this = _super.call(this) || this;
  53059. _this.ALBEDO = false;
  53060. _this.AMBIENT = false;
  53061. _this.OPACITY = false;
  53062. _this.OPACITYRGB = false;
  53063. _this.REFLECTION = false;
  53064. _this.EMISSIVE = false;
  53065. _this.REFLECTIVITY = false;
  53066. _this.BUMP = false;
  53067. _this.PARALLAX = false;
  53068. _this.PARALLAXOCCLUSION = false;
  53069. _this.SPECULAROVERALPHA = false;
  53070. _this.CLIPPLANE = false;
  53071. _this.ALPHATEST = false;
  53072. _this.ALPHAFROMALBEDO = false;
  53073. _this.POINTSIZE = false;
  53074. _this.FOG = false;
  53075. _this.SPECULARTERM = false;
  53076. _this.OPACITYFRESNEL = false;
  53077. _this.EMISSIVEFRESNEL = false;
  53078. _this.FRESNEL = false;
  53079. _this.NORMAL = false;
  53080. _this.UV1 = false;
  53081. _this.UV2 = false;
  53082. _this.VERTEXCOLOR = false;
  53083. _this.VERTEXALPHA = false;
  53084. _this.NUM_BONE_INFLUENCERS = 0;
  53085. _this.BonesPerMesh = 0;
  53086. _this.INSTANCES = false;
  53087. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  53088. _this.MICROSURFACEAUTOMATIC = false;
  53089. _this.EMISSIVEASILLUMINATION = false;
  53090. _this.LINKEMISSIVEWITHALBEDO = false;
  53091. _this.LIGHTMAP = false;
  53092. _this.USELIGHTMAPASSHADOWMAP = false;
  53093. _this.REFLECTIONMAP_3D = false;
  53094. _this.REFLECTIONMAP_SPHERICAL = false;
  53095. _this.REFLECTIONMAP_PLANAR = false;
  53096. _this.REFLECTIONMAP_CUBIC = false;
  53097. _this.REFLECTIONMAP_PROJECTION = false;
  53098. _this.REFLECTIONMAP_SKYBOX = false;
  53099. _this.REFLECTIONMAP_EXPLICIT = false;
  53100. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  53101. _this.INVERTCUBICMAP = false;
  53102. _this.LOGARITHMICDEPTH = false;
  53103. _this.CAMERATONEMAP = false;
  53104. _this.CAMERACONTRAST = false;
  53105. _this.CAMERACOLORGRADING = false;
  53106. _this.CAMERACOLORCURVES = false;
  53107. _this.OVERLOADEDVALUES = false;
  53108. _this.OVERLOADEDSHADOWVALUES = false;
  53109. _this.USESPHERICALFROMREFLECTIONMAP = false;
  53110. _this.REFRACTION = false;
  53111. _this.REFRACTIONMAP_3D = false;
  53112. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  53113. _this.REFRACTIONMAPINLINEARSPACE = false;
  53114. _this.LODBASEDMICROSFURACE = false;
  53115. _this.USEPHYSICALLIGHTFALLOFF = false;
  53116. _this.RADIANCEOVERALPHA = false;
  53117. _this.USEPMREMREFLECTION = false;
  53118. _this.USEPMREMREFRACTION = false;
  53119. _this.OPENGLNORMALMAP = false;
  53120. _this.INVERTNORMALMAPX = false;
  53121. _this.INVERTNORMALMAPY = false;
  53122. _this.SHADOWFULLFLOAT = false;
  53123. _this.METALLICWORKFLOW = false;
  53124. _this.METALLICROUGHNESSMAP = false;
  53125. _this.METALLICROUGHNESSGSTOREINALPHA = false;
  53126. _this.METALLICROUGHNESSGSTOREINGREEN = false;
  53127. _this.rebuild();
  53128. return _this;
  53129. }
  53130. return PBRMaterialDefines;
  53131. }(BABYLON.MaterialDefines));
  53132. /**
  53133. * The Physically based material of BJS.
  53134. *
  53135. * This offers the main features of a standard PBR material.
  53136. * For more information, please refer to the documentation :
  53137. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  53138. */
  53139. var PBRMaterial = (function (_super) {
  53140. __extends(PBRMaterial, _super);
  53141. /**
  53142. * Instantiates a new PBRMaterial instance.
  53143. *
  53144. * @param name The material name
  53145. * @param scene The scene the material will be use in.
  53146. */
  53147. function PBRMaterial(name, scene) {
  53148. var _this = _super.call(this, name, scene) || this;
  53149. /**
  53150. * Intensity of the direct lights e.g. the four lights available in your scene.
  53151. * This impacts both the direct diffuse and specular highlights.
  53152. */
  53153. _this.directIntensity = 1.0;
  53154. /**
  53155. * Intensity of the emissive part of the material.
  53156. * This helps controlling the emissive effect without modifying the emissive color.
  53157. */
  53158. _this.emissiveIntensity = 1.0;
  53159. /**
  53160. * Intensity of the environment e.g. how much the environment will light the object
  53161. * either through harmonics for rough material or through the refelction for shiny ones.
  53162. */
  53163. _this.environmentIntensity = 1.0;
  53164. /**
  53165. * This is a special control allowing the reduction of the specular highlights coming from the
  53166. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  53167. */
  53168. _this.specularIntensity = 1.0;
  53169. _this._lightingInfos = new BABYLON.Vector4(_this.directIntensity, _this.emissiveIntensity, _this.environmentIntensity, _this.specularIntensity);
  53170. /**
  53171. * Debug Control allowing disabling the bump map on this material.
  53172. */
  53173. _this.disableBumpMap = false;
  53174. /**
  53175. * Debug Control helping enforcing or dropping the darkness of shadows.
  53176. * 1.0 means the shadows have their normal darkness, 0.0 means the shadows are not visible.
  53177. */
  53178. _this.overloadedShadowIntensity = 1.0;
  53179. /**
  53180. * Debug Control helping dropping the shading effect coming from the diffuse lighting.
  53181. * 1.0 means the shade have their normal impact, 0.0 means no shading at all.
  53182. */
  53183. _this.overloadedShadeIntensity = 1.0;
  53184. _this._overloadedShadowInfos = new BABYLON.Vector4(_this.overloadedShadowIntensity, _this.overloadedShadeIntensity, 0.0, 0.0);
  53185. /**
  53186. * The camera exposure used on this material.
  53187. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  53188. * This corresponds to a photographic exposure.
  53189. */
  53190. _this.cameraExposure = 1.0;
  53191. /**
  53192. * The camera contrast used on this material.
  53193. * This property is here and not in the camera to allow controlling contrast without full screen post process.
  53194. */
  53195. _this.cameraContrast = 1.0;
  53196. /**
  53197. * Color Grading 2D Lookup Texture.
  53198. * This allows special effects like sepia, black and white to sixties rendering style.
  53199. */
  53200. _this.cameraColorGradingTexture = null;
  53201. /**
  53202. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  53203. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  53204. * These are similar to controls found in many professional imaging or colorist software. The global controls are applied to the entire image. For advanced tuning, extra controls are provided to adjust the shadow, midtone and highlight areas of the image;
  53205. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  53206. */
  53207. _this.cameraColorCurves = null;
  53208. _this._cameraInfos = new BABYLON.Vector4(1.0, 1.0, 0.0, 0.0);
  53209. _this._microsurfaceTextureLods = new BABYLON.Vector2(0.0, 0.0);
  53210. /**
  53211. * Debug Control allowing to overload the ambient color.
  53212. * This as to be use with the overloadedAmbientIntensity parameter.
  53213. */
  53214. _this.overloadedAmbient = BABYLON.Color3.White();
  53215. /**
  53216. * Debug Control indicating how much the overloaded ambient color is used against the default one.
  53217. */
  53218. _this.overloadedAmbientIntensity = 0.0;
  53219. /**
  53220. * Debug Control allowing to overload the albedo color.
  53221. * This as to be use with the overloadedAlbedoIntensity parameter.
  53222. */
  53223. _this.overloadedAlbedo = BABYLON.Color3.White();
  53224. /**
  53225. * Debug Control indicating how much the overloaded albedo color is used against the default one.
  53226. */
  53227. _this.overloadedAlbedoIntensity = 0.0;
  53228. /**
  53229. * Debug Control allowing to overload the reflectivity color.
  53230. * This as to be use with the overloadedReflectivityIntensity parameter.
  53231. */
  53232. _this.overloadedReflectivity = new BABYLON.Color3(0.3, 0.3, 0.3);
  53233. /**
  53234. * Debug Control indicating how much the overloaded reflectivity color is used against the default one.
  53235. */
  53236. _this.overloadedReflectivityIntensity = 0.0;
  53237. /**
  53238. * Debug Control allowing to overload the emissive color.
  53239. * This as to be use with the overloadedEmissiveIntensity parameter.
  53240. */
  53241. _this.overloadedEmissive = BABYLON.Color3.White();
  53242. /**
  53243. * Debug Control indicating how much the overloaded emissive color is used against the default one.
  53244. */
  53245. _this.overloadedEmissiveIntensity = 0.0;
  53246. _this._overloadedIntensity = new BABYLON.Vector4(_this.overloadedAmbientIntensity, _this.overloadedAlbedoIntensity, _this.overloadedReflectivityIntensity, _this.overloadedEmissiveIntensity);
  53247. /**
  53248. * Debug Control allowing to overload the reflection color.
  53249. * This as to be use with the overloadedReflectionIntensity parameter.
  53250. */
  53251. _this.overloadedReflection = BABYLON.Color3.White();
  53252. /**
  53253. * Debug Control indicating how much the overloaded reflection color is used against the default one.
  53254. */
  53255. _this.overloadedReflectionIntensity = 0.0;
  53256. /**
  53257. * Debug Control allowing to overload the microsurface.
  53258. * This as to be use with the overloadedMicroSurfaceIntensity parameter.
  53259. */
  53260. _this.overloadedMicroSurface = 0.0;
  53261. /**
  53262. * Debug Control indicating how much the overloaded microsurface is used against the default one.
  53263. */
  53264. _this.overloadedMicroSurfaceIntensity = 0.0;
  53265. _this._overloadedMicroSurface = new BABYLON.Vector3(_this.overloadedMicroSurface, _this.overloadedMicroSurfaceIntensity, _this.overloadedReflectionIntensity);
  53266. /**
  53267. * AKA Occlusion Texture Intensity in other nomenclature.
  53268. */
  53269. _this.ambientTextureStrength = 1.0;
  53270. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  53271. /**
  53272. * AKA Diffuse Color in other nomenclature.
  53273. */
  53274. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  53275. /**
  53276. * AKA Specular Color in other nomenclature.
  53277. */
  53278. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  53279. _this.reflectionColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  53280. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  53281. /**
  53282. * AKA Glossiness in other nomenclature.
  53283. */
  53284. _this.microSurface = 0.9;
  53285. /**
  53286. * source material index of refraction (IOR)' / 'destination material IOR.
  53287. */
  53288. _this.indexOfRefraction = 0.66;
  53289. /**
  53290. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  53291. */
  53292. _this.invertRefractionY = false;
  53293. /**
  53294. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  53295. * Materials half opaque for instance using refraction could benefit from this control.
  53296. */
  53297. _this.linkRefractionWithTransparency = false;
  53298. /**
  53299. * The emissive and albedo are linked to never be more than one (Energy conservation).
  53300. */
  53301. _this.linkEmissiveWithAlbedo = false;
  53302. _this.useLightmapAsShadowmap = false;
  53303. /**
  53304. * In this mode, the emissive informtaion will always be added to the lighting once.
  53305. * A light for instance can be thought as emissive.
  53306. */
  53307. _this.useEmissiveAsIllumination = false;
  53308. /**
  53309. * Secifies that the alpha is coming form the albedo channel alpha channel.
  53310. */
  53311. _this.useAlphaFromAlbedoTexture = false;
  53312. /**
  53313. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  53314. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  53315. */
  53316. _this.useSpecularOverAlpha = true;
  53317. /**
  53318. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  53319. */
  53320. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  53321. /**
  53322. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  53323. */
  53324. _this.useRoughnessFromMetallicTextureAlpha = true;
  53325. /**
  53326. * Specifies if the metallic texture contains the roughness information in its green channel.
  53327. */
  53328. _this.useRoughnessFromMetallicTextureGreen = false;
  53329. /**
  53330. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  53331. * The material will try to infer what glossiness each pixel should be.
  53332. */
  53333. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  53334. /**
  53335. * Allows to work with scalar in linear mode. This is definitely a matter of preferences and tools used during
  53336. * the creation of the material.
  53337. */
  53338. _this.useScalarInLinearSpace = false;
  53339. /**
  53340. * BJS is using an harcoded light falloff based on a manually sets up range.
  53341. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  53342. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  53343. */
  53344. _this.usePhysicalLightFalloff = true;
  53345. /**
  53346. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  53347. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  53348. */
  53349. _this.useRadianceOverAlpha = true;
  53350. /**
  53351. * Allows using the bump map in parallax mode.
  53352. */
  53353. _this.useParallax = false;
  53354. /**
  53355. * Allows using the bump map in parallax occlusion mode.
  53356. */
  53357. _this.useParallaxOcclusion = false;
  53358. /**
  53359. * Controls the scale bias of the parallax mode.
  53360. */
  53361. _this.parallaxScaleBias = 0.05;
  53362. /**
  53363. * If sets to true, disables all the lights affecting the material.
  53364. */
  53365. _this.disableLighting = false;
  53366. /**
  53367. * Number of Simultaneous lights allowed on the material.
  53368. */
  53369. _this.maxSimultaneousLights = 4;
  53370. /**
  53371. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  53372. */
  53373. _this.invertNormalMapX = false;
  53374. /**
  53375. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  53376. */
  53377. _this.invertNormalMapY = false;
  53378. _this._renderTargets = new BABYLON.SmartArray(16);
  53379. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  53380. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  53381. _this._tempColor = new BABYLON.Color3();
  53382. _this._defines = new PBRMaterialDefines();
  53383. _this._cachedDefines = new PBRMaterialDefines();
  53384. _this._myScene = null;
  53385. _this._myShadowGenerator = null;
  53386. _this._cachedDefines.BonesPerMesh = -1;
  53387. _this.getRenderTargetTextures = function () {
  53388. _this._renderTargets.reset();
  53389. if (_this.reflectionTexture && _this.reflectionTexture.isRenderTarget) {
  53390. _this._renderTargets.push(_this.reflectionTexture);
  53391. }
  53392. if (_this.refractionTexture && _this.refractionTexture.isRenderTarget) {
  53393. _this._renderTargets.push(_this.refractionTexture);
  53394. }
  53395. return _this._renderTargets;
  53396. };
  53397. return _this;
  53398. }
  53399. PBRMaterial.prototype.getClassName = function () {
  53400. return "PBRMaterial";
  53401. };
  53402. Object.defineProperty(PBRMaterial.prototype, "useLogarithmicDepth", {
  53403. get: function () {
  53404. return this._useLogarithmicDepth;
  53405. },
  53406. set: function (value) {
  53407. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  53408. },
  53409. enumerable: true,
  53410. configurable: true
  53411. });
  53412. PBRMaterial.prototype.needAlphaBlending = function () {
  53413. if (this.linkRefractionWithTransparency) {
  53414. return false;
  53415. }
  53416. return (this.alpha < 1.0) || (this.opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture() || this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled;
  53417. };
  53418. PBRMaterial.prototype.needAlphaTesting = function () {
  53419. if (this.linkRefractionWithTransparency) {
  53420. return false;
  53421. }
  53422. return this.albedoTexture != null && this.albedoTexture.hasAlpha;
  53423. };
  53424. PBRMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  53425. return this.albedoTexture != null && this.albedoTexture.hasAlpha && this.useAlphaFromAlbedoTexture;
  53426. };
  53427. PBRMaterial.prototype.getAlphaTestTexture = function () {
  53428. return this.albedoTexture;
  53429. };
  53430. PBRMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  53431. if (!mesh) {
  53432. return true;
  53433. }
  53434. if (this._defines.INSTANCES !== useInstances) {
  53435. return false;
  53436. }
  53437. if (mesh._materialDefines && mesh._materialDefines.isEqual(this._defines)) {
  53438. return true;
  53439. }
  53440. return false;
  53441. };
  53442. PBRMaterial.prototype.convertColorToLinearSpaceToRef = function (color, ref) {
  53443. PBRMaterial.convertColorToLinearSpaceToRef(color, ref, this.useScalarInLinearSpace);
  53444. };
  53445. PBRMaterial.convertColorToLinearSpaceToRef = function (color, ref, useScalarInLinear) {
  53446. if (!useScalarInLinear) {
  53447. color.toLinearSpaceToRef(ref);
  53448. }
  53449. else {
  53450. ref.r = color.r;
  53451. ref.g = color.g;
  53452. ref.b = color.b;
  53453. }
  53454. };
  53455. PBRMaterial.BindLights = function (scene, mesh, effect, defines, useScalarInLinearSpace, maxSimultaneousLights, usePhysicalLightFalloff) {
  53456. var lightIndex = 0;
  53457. var depthValuesAlreadySet = false;
  53458. for (var index = 0; index < scene.lights.length; index++) {
  53459. var light = scene.lights[index];
  53460. if (!light.isEnabled()) {
  53461. continue;
  53462. }
  53463. if (!light.canAffectMesh(mesh)) {
  53464. continue;
  53465. }
  53466. BABYLON.MaterialHelper.BindLightProperties(light, effect, lightIndex);
  53467. // GAMMA CORRECTION.
  53468. this.convertColorToLinearSpaceToRef(light.diffuse, PBRMaterial._scaledAlbedo, useScalarInLinearSpace);
  53469. PBRMaterial._scaledAlbedo.scaleToRef(light.intensity, PBRMaterial._scaledAlbedo);
  53470. effect.setColor4("vLightDiffuse" + lightIndex, PBRMaterial._scaledAlbedo, usePhysicalLightFalloff ? light.radius : light.range);
  53471. if (defines["SPECULARTERM"]) {
  53472. this.convertColorToLinearSpaceToRef(light.specular, PBRMaterial._scaledReflectivity, useScalarInLinearSpace);
  53473. PBRMaterial._scaledReflectivity.scaleToRef(light.intensity, PBRMaterial._scaledReflectivity);
  53474. effect.setColor3("vLightSpecular" + lightIndex, PBRMaterial._scaledReflectivity);
  53475. }
  53476. // Shadows
  53477. if (scene.shadowsEnabled) {
  53478. depthValuesAlreadySet = BABYLON.MaterialHelper.BindLightShadow(light, scene, mesh, lightIndex, effect, depthValuesAlreadySet);
  53479. }
  53480. lightIndex++;
  53481. if (lightIndex === maxSimultaneousLights)
  53482. break;
  53483. }
  53484. };
  53485. PBRMaterial.prototype.isReady = function (mesh, useInstances) {
  53486. if (this.isFrozen) {
  53487. if (this._wasPreviouslyReady) {
  53488. return true;
  53489. }
  53490. }
  53491. var scene = this.getScene();
  53492. var engine = scene.getEngine();
  53493. var needNormals = false;
  53494. var needUVs = false;
  53495. this._defines.reset();
  53496. if (scene.lightsEnabled && !this.disableLighting) {
  53497. needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, this._defines, this.maxSimultaneousLights) || needNormals;
  53498. }
  53499. if (!this.checkReadyOnEveryCall) {
  53500. if (this._renderId === scene.getRenderId()) {
  53501. if (this._checkCache(scene, mesh, useInstances)) {
  53502. return true;
  53503. }
  53504. }
  53505. }
  53506. if (scene.texturesEnabled) {
  53507. if (scene.getEngine().getCaps().textureLOD) {
  53508. this._defines.LODBASEDMICROSFURACE = true;
  53509. }
  53510. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53511. if (!this.albedoTexture.isReady()) {
  53512. return false;
  53513. }
  53514. else {
  53515. needUVs = true;
  53516. this._defines.ALBEDO = true;
  53517. }
  53518. }
  53519. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53520. if (!this.ambientTexture.isReady()) {
  53521. return false;
  53522. }
  53523. else {
  53524. needUVs = true;
  53525. this._defines.AMBIENT = true;
  53526. }
  53527. }
  53528. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53529. if (!this.opacityTexture.isReady()) {
  53530. return false;
  53531. }
  53532. else {
  53533. needUVs = true;
  53534. this._defines.OPACITY = true;
  53535. if (this.opacityTexture.getAlphaFromRGB) {
  53536. this._defines.OPACITYRGB = true;
  53537. }
  53538. }
  53539. }
  53540. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53541. if (!this.reflectionTexture.isReady()) {
  53542. return false;
  53543. }
  53544. else {
  53545. needNormals = true;
  53546. this._defines.REFLECTION = true;
  53547. if (this.reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  53548. this._defines.INVERTCUBICMAP = true;
  53549. }
  53550. this._defines.REFLECTIONMAP_3D = this.reflectionTexture.isCube;
  53551. switch (this.reflectionTexture.coordinatesMode) {
  53552. case BABYLON.Texture.CUBIC_MODE:
  53553. case BABYLON.Texture.INVCUBIC_MODE:
  53554. this._defines.REFLECTIONMAP_CUBIC = true;
  53555. break;
  53556. case BABYLON.Texture.EXPLICIT_MODE:
  53557. this._defines.REFLECTIONMAP_EXPLICIT = true;
  53558. break;
  53559. case BABYLON.Texture.PLANAR_MODE:
  53560. this._defines.REFLECTIONMAP_PLANAR = true;
  53561. break;
  53562. case BABYLON.Texture.PROJECTION_MODE:
  53563. this._defines.REFLECTIONMAP_PROJECTION = true;
  53564. break;
  53565. case BABYLON.Texture.SKYBOX_MODE:
  53566. this._defines.REFLECTIONMAP_SKYBOX = true;
  53567. break;
  53568. case BABYLON.Texture.SPHERICAL_MODE:
  53569. this._defines.REFLECTIONMAP_SPHERICAL = true;
  53570. break;
  53571. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  53572. this._defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  53573. break;
  53574. }
  53575. if (this.reflectionTexture instanceof BABYLON.HDRCubeTexture && this.reflectionTexture) {
  53576. this._defines.USESPHERICALFROMREFLECTIONMAP = true;
  53577. needNormals = true;
  53578. if (this.reflectionTexture.isPMREM) {
  53579. this._defines.USEPMREMREFLECTION = true;
  53580. }
  53581. }
  53582. }
  53583. }
  53584. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53585. if (!this.lightmapTexture.isReady()) {
  53586. return false;
  53587. }
  53588. else {
  53589. needUVs = true;
  53590. this._defines.LIGHTMAP = true;
  53591. this._defines.USELIGHTMAPASSHADOWMAP = this.useLightmapAsShadowmap;
  53592. }
  53593. }
  53594. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53595. if (!this.emissiveTexture.isReady()) {
  53596. return false;
  53597. }
  53598. else {
  53599. needUVs = true;
  53600. this._defines.EMISSIVE = true;
  53601. }
  53602. }
  53603. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53604. if (this.metallicTexture) {
  53605. if (!this.metallicTexture.isReady()) {
  53606. return false;
  53607. }
  53608. else {
  53609. needUVs = true;
  53610. this._defines.METALLICWORKFLOW = true;
  53611. this._defines.METALLICROUGHNESSMAP = true;
  53612. this._defines.METALLICROUGHNESSGSTOREINALPHA = this.useRoughnessFromMetallicTextureAlpha;
  53613. this._defines.METALLICROUGHNESSGSTOREINGREEN = !this.useRoughnessFromMetallicTextureAlpha && this.useRoughnessFromMetallicTextureGreen;
  53614. }
  53615. }
  53616. else if (this.reflectivityTexture) {
  53617. if (!this.reflectivityTexture.isReady()) {
  53618. return false;
  53619. }
  53620. else {
  53621. needUVs = true;
  53622. this._defines.REFLECTIVITY = true;
  53623. this._defines.MICROSURFACEFROMREFLECTIVITYMAP = this.useMicroSurfaceFromReflectivityMapAlpha;
  53624. this._defines.MICROSURFACEAUTOMATIC = this.useAutoMicroSurfaceFromReflectivityMap;
  53625. }
  53626. }
  53627. }
  53628. if (scene.getEngine().getCaps().standardDerivatives && this.bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53629. if (!this.bumpTexture.isReady()) {
  53630. return false;
  53631. }
  53632. else {
  53633. needUVs = true;
  53634. this._defines.BUMP = true;
  53635. if (this.useParallax && this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53636. this._defines.PARALLAX = true;
  53637. if (this.useParallaxOcclusion) {
  53638. this._defines.PARALLAXOCCLUSION = true;
  53639. }
  53640. }
  53641. if (this.invertNormalMapX) {
  53642. this._defines.INVERTNORMALMAPX = true;
  53643. }
  53644. if (this.invertNormalMapY) {
  53645. this._defines.INVERTNORMALMAPY = true;
  53646. }
  53647. if (scene._mirroredCameraPosition) {
  53648. this._defines.INVERTNORMALMAPX = !this._defines.INVERTNORMALMAPX;
  53649. this._defines.INVERTNORMALMAPY = !this._defines.INVERTNORMALMAPY;
  53650. }
  53651. }
  53652. }
  53653. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53654. if (!this.refractionTexture.isReady()) {
  53655. return false;
  53656. }
  53657. else {
  53658. needUVs = true;
  53659. this._defines.REFRACTION = true;
  53660. this._defines.REFRACTIONMAP_3D = this.refractionTexture.isCube;
  53661. if (this.linkRefractionWithTransparency) {
  53662. this._defines.LINKREFRACTIONTOTRANSPARENCY = true;
  53663. }
  53664. if (this.refractionTexture instanceof BABYLON.HDRCubeTexture) {
  53665. this._defines.REFRACTIONMAPINLINEARSPACE = true;
  53666. if (this.refractionTexture.isPMREM) {
  53667. this._defines.USEPMREMREFRACTION = true;
  53668. }
  53669. }
  53670. }
  53671. }
  53672. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  53673. if (!this.cameraColorGradingTexture.isReady()) {
  53674. return false;
  53675. }
  53676. else {
  53677. this._defines.CAMERACOLORGRADING = true;
  53678. }
  53679. }
  53680. }
  53681. // Effect
  53682. if (scene.clipPlane) {
  53683. this._defines.CLIPPLANE = true;
  53684. }
  53685. if (engine.getAlphaTesting()) {
  53686. this._defines.ALPHATEST = true;
  53687. }
  53688. if (this._shouldUseAlphaFromAlbedoTexture()) {
  53689. this._defines.ALPHAFROMALBEDO = true;
  53690. }
  53691. if (this.useEmissiveAsIllumination) {
  53692. this._defines.EMISSIVEASILLUMINATION = true;
  53693. }
  53694. if (this.linkEmissiveWithAlbedo) {
  53695. this._defines.LINKEMISSIVEWITHALBEDO = true;
  53696. }
  53697. if (this.useLogarithmicDepth) {
  53698. this._defines.LOGARITHMICDEPTH = true;
  53699. }
  53700. if (this.cameraContrast != 1) {
  53701. this._defines.CAMERACONTRAST = true;
  53702. }
  53703. if (this.cameraExposure != 1) {
  53704. this._defines.CAMERATONEMAP = true;
  53705. }
  53706. if (this.cameraColorCurves) {
  53707. this._defines.CAMERACOLORCURVES = true;
  53708. }
  53709. if (this.overloadedShadeIntensity != 1 ||
  53710. this.overloadedShadowIntensity != 1) {
  53711. this._defines.OVERLOADEDSHADOWVALUES = true;
  53712. }
  53713. if (this.overloadedMicroSurfaceIntensity > 0 ||
  53714. this.overloadedEmissiveIntensity > 0 ||
  53715. this.overloadedReflectivityIntensity > 0 ||
  53716. this.overloadedAlbedoIntensity > 0 ||
  53717. this.overloadedAmbientIntensity > 0 ||
  53718. this.overloadedReflectionIntensity > 0) {
  53719. this._defines.OVERLOADEDVALUES = true;
  53720. }
  53721. // Point size
  53722. if (this.pointsCloud || scene.forcePointsCloud) {
  53723. this._defines.POINTSIZE = true;
  53724. }
  53725. // Fog
  53726. if (scene.fogEnabled && mesh && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53727. this._defines.FOG = true;
  53728. }
  53729. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53730. // Fresnel
  53731. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled ||
  53732. this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53733. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53734. this._defines.OPACITYFRESNEL = true;
  53735. }
  53736. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53737. this._defines.EMISSIVEFRESNEL = true;
  53738. }
  53739. needNormals = true;
  53740. this._defines.FRESNEL = true;
  53741. }
  53742. }
  53743. if (this._defines.SPECULARTERM && this.useSpecularOverAlpha) {
  53744. this._defines.SPECULAROVERALPHA = true;
  53745. }
  53746. if (this.usePhysicalLightFalloff) {
  53747. this._defines.USEPHYSICALLIGHTFALLOFF = true;
  53748. }
  53749. if (this.useRadianceOverAlpha) {
  53750. this._defines.RADIANCEOVERALPHA = true;
  53751. }
  53752. if (this.metallic !== undefined || this.roughness !== undefined) {
  53753. this._defines.METALLICWORKFLOW = true;
  53754. }
  53755. // Attribs
  53756. if (mesh) {
  53757. if (needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53758. this._defines.NORMAL = true;
  53759. }
  53760. if (needUVs) {
  53761. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  53762. this._defines.UV1 = true;
  53763. }
  53764. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  53765. this._defines.UV2 = true;
  53766. }
  53767. }
  53768. if (mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  53769. this._defines.VERTEXCOLOR = true;
  53770. if (mesh.hasVertexAlpha) {
  53771. this._defines.VERTEXALPHA = true;
  53772. }
  53773. }
  53774. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  53775. this._defines.NUM_BONE_INFLUENCERS = mesh.numBoneInfluencers;
  53776. this._defines.BonesPerMesh = (mesh.skeleton.bones.length + 1);
  53777. }
  53778. // Instances
  53779. if (useInstances) {
  53780. this._defines.INSTANCES = true;
  53781. }
  53782. }
  53783. // Get correct effect
  53784. if (!this._defines.isEqual(this._cachedDefines)) {
  53785. this._defines.cloneTo(this._cachedDefines);
  53786. scene.resetCachedMaterial();
  53787. // Fallbacks
  53788. var fallbacks = new BABYLON.EffectFallbacks();
  53789. if (this._defines.REFLECTION) {
  53790. fallbacks.addFallback(0, "REFLECTION");
  53791. }
  53792. if (this._defines.REFRACTION) {
  53793. fallbacks.addFallback(0, "REFRACTION");
  53794. }
  53795. if (this._defines.REFLECTIVITY) {
  53796. fallbacks.addFallback(0, "REFLECTIVITY");
  53797. }
  53798. if (this._defines.BUMP) {
  53799. fallbacks.addFallback(0, "BUMP");
  53800. }
  53801. if (this._defines.PARALLAX) {
  53802. fallbacks.addFallback(1, "PARALLAX");
  53803. }
  53804. if (this._defines.PARALLAXOCCLUSION) {
  53805. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  53806. }
  53807. if (this._defines.SPECULAROVERALPHA) {
  53808. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  53809. }
  53810. if (this._defines.FOG) {
  53811. fallbacks.addFallback(1, "FOG");
  53812. }
  53813. if (this._defines.POINTSIZE) {
  53814. fallbacks.addFallback(0, "POINTSIZE");
  53815. }
  53816. if (this._defines.LOGARITHMICDEPTH) {
  53817. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  53818. }
  53819. BABYLON.MaterialHelper.HandleFallbacksForShadows(this._defines, fallbacks, this.maxSimultaneousLights);
  53820. if (this._defines.SPECULARTERM) {
  53821. fallbacks.addFallback(0, "SPECULARTERM");
  53822. }
  53823. if (this._defines.OPACITYFRESNEL) {
  53824. fallbacks.addFallback(1, "OPACITYFRESNEL");
  53825. }
  53826. if (this._defines.EMISSIVEFRESNEL) {
  53827. fallbacks.addFallback(2, "EMISSIVEFRESNEL");
  53828. }
  53829. if (this._defines.FRESNEL) {
  53830. fallbacks.addFallback(3, "FRESNEL");
  53831. }
  53832. if (this._defines.NUM_BONE_INFLUENCERS > 0) {
  53833. fallbacks.addCPUSkinningFallback(0, mesh);
  53834. }
  53835. //Attributes
  53836. var attribs = [BABYLON.VertexBuffer.PositionKind];
  53837. if (this._defines.NORMAL) {
  53838. attribs.push(BABYLON.VertexBuffer.NormalKind);
  53839. }
  53840. if (this._defines.UV1) {
  53841. attribs.push(BABYLON.VertexBuffer.UVKind);
  53842. }
  53843. if (this._defines.UV2) {
  53844. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  53845. }
  53846. if (this._defines.VERTEXCOLOR) {
  53847. attribs.push(BABYLON.VertexBuffer.ColorKind);
  53848. }
  53849. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, this._defines, fallbacks);
  53850. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, this._defines);
  53851. // Legacy browser patch
  53852. var join = this._defines.toString();
  53853. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  53854. "vFogInfos", "vFogColor", "pointSize",
  53855. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  53856. "mBones",
  53857. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  53858. "depthValues",
  53859. "opacityParts", "emissiveLeftColor", "emissiveRightColor",
  53860. "vLightingIntensity", "vOverloadedShadowIntensity", "vOverloadedIntensity", "vOverloadedAlbedo", "vOverloadedReflection", "vOverloadedReflectivity", "vOverloadedEmissive", "vOverloadedMicroSurface",
  53861. "logarithmicDepthConstant",
  53862. "vSphericalX", "vSphericalY", "vSphericalZ",
  53863. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  53864. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  53865. "vMicrosurfaceTextureLods",
  53866. "vCameraInfos"
  53867. ];
  53868. var samplers = ["albedoSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "reflectivitySampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  53869. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  53870. BABYLON.ColorGradingTexture.PrepareUniformsAndSamplers(uniforms, samplers);
  53871. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList(uniforms, samplers, this._defines, this.maxSimultaneousLights);
  53872. this._effect = scene.getEngine().createEffect("pbr", attribs, uniforms, samplers, join, fallbacks, this.onCompiled, this.onError, { maxSimultaneousLights: this.maxSimultaneousLights });
  53873. }
  53874. if (!this._effect.isReady()) {
  53875. return false;
  53876. }
  53877. this._renderId = scene.getRenderId();
  53878. this._wasPreviouslyReady = true;
  53879. if (mesh) {
  53880. if (!mesh._materialDefines) {
  53881. mesh._materialDefines = new PBRMaterialDefines();
  53882. }
  53883. this._defines.cloneTo(mesh._materialDefines);
  53884. }
  53885. return true;
  53886. };
  53887. PBRMaterial.prototype.unbind = function () {
  53888. if (this.reflectionTexture && this.reflectionTexture.isRenderTarget) {
  53889. this._effect.setTexture("reflection2DSampler", null);
  53890. }
  53891. if (this.refractionTexture && this.refractionTexture.isRenderTarget) {
  53892. this._effect.setTexture("refraction2DSampler", null);
  53893. }
  53894. _super.prototype.unbind.call(this);
  53895. };
  53896. PBRMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  53897. this._effect.setMatrix("world", world);
  53898. };
  53899. PBRMaterial.prototype.bind = function (world, mesh) {
  53900. this._myScene = this.getScene();
  53901. // Matrices
  53902. this.bindOnlyWorldMatrix(world);
  53903. // Bones
  53904. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  53905. if (this._myScene.getCachedMaterial() !== this) {
  53906. this._effect.setMatrix("viewProjection", this._myScene.getTransformMatrix());
  53907. if (BABYLON.StandardMaterial.FresnelEnabled) {
  53908. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  53909. this._effect.setColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  53910. }
  53911. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  53912. this._effect.setColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  53913. this._effect.setColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  53914. }
  53915. }
  53916. // Textures
  53917. if (this._myScene.texturesEnabled) {
  53918. if (this.albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  53919. this._effect.setTexture("albedoSampler", this.albedoTexture);
  53920. this._effect.setFloat2("vAlbedoInfos", this.albedoTexture.coordinatesIndex, this.albedoTexture.level);
  53921. this._effect.setMatrix("albedoMatrix", this.albedoTexture.getTextureMatrix());
  53922. }
  53923. if (this.ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  53924. this._effect.setTexture("ambientSampler", this.ambientTexture);
  53925. this._effect.setFloat3("vAmbientInfos", this.ambientTexture.coordinatesIndex, this.ambientTexture.level, this.ambientTextureStrength);
  53926. this._effect.setMatrix("ambientMatrix", this.ambientTexture.getTextureMatrix());
  53927. }
  53928. if (this.opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  53929. this._effect.setTexture("opacitySampler", this.opacityTexture);
  53930. this._effect.setFloat2("vOpacityInfos", this.opacityTexture.coordinatesIndex, this.opacityTexture.level);
  53931. this._effect.setMatrix("opacityMatrix", this.opacityTexture.getTextureMatrix());
  53932. }
  53933. if (this.reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  53934. this._microsurfaceTextureLods.x = Math.round(Math.log(this.reflectionTexture.getSize().width) * Math.LOG2E);
  53935. if (this.reflectionTexture.isCube) {
  53936. this._effect.setTexture("reflectionCubeSampler", this.reflectionTexture);
  53937. }
  53938. else {
  53939. this._effect.setTexture("reflection2DSampler", this.reflectionTexture);
  53940. }
  53941. this._effect.setMatrix("reflectionMatrix", this.reflectionTexture.getReflectionTextureMatrix());
  53942. this._effect.setFloat2("vReflectionInfos", this.reflectionTexture.level, 0);
  53943. if (this._defines.USESPHERICALFROMREFLECTIONMAP) {
  53944. this._effect.setFloat3("vSphericalX", this.reflectionTexture.sphericalPolynomial.x.x, this.reflectionTexture.sphericalPolynomial.x.y, this.reflectionTexture.sphericalPolynomial.x.z);
  53945. this._effect.setFloat3("vSphericalY", this.reflectionTexture.sphericalPolynomial.y.x, this.reflectionTexture.sphericalPolynomial.y.y, this.reflectionTexture.sphericalPolynomial.y.z);
  53946. this._effect.setFloat3("vSphericalZ", this.reflectionTexture.sphericalPolynomial.z.x, this.reflectionTexture.sphericalPolynomial.z.y, this.reflectionTexture.sphericalPolynomial.z.z);
  53947. this._effect.setFloat3("vSphericalXX", this.reflectionTexture.sphericalPolynomial.xx.x, this.reflectionTexture.sphericalPolynomial.xx.y, this.reflectionTexture.sphericalPolynomial.xx.z);
  53948. this._effect.setFloat3("vSphericalYY", this.reflectionTexture.sphericalPolynomial.yy.x, this.reflectionTexture.sphericalPolynomial.yy.y, this.reflectionTexture.sphericalPolynomial.yy.z);
  53949. this._effect.setFloat3("vSphericalZZ", this.reflectionTexture.sphericalPolynomial.zz.x, this.reflectionTexture.sphericalPolynomial.zz.y, this.reflectionTexture.sphericalPolynomial.zz.z);
  53950. this._effect.setFloat3("vSphericalXY", this.reflectionTexture.sphericalPolynomial.xy.x, this.reflectionTexture.sphericalPolynomial.xy.y, this.reflectionTexture.sphericalPolynomial.xy.z);
  53951. this._effect.setFloat3("vSphericalYZ", this.reflectionTexture.sphericalPolynomial.yz.x, this.reflectionTexture.sphericalPolynomial.yz.y, this.reflectionTexture.sphericalPolynomial.yz.z);
  53952. this._effect.setFloat3("vSphericalZX", this.reflectionTexture.sphericalPolynomial.zx.x, this.reflectionTexture.sphericalPolynomial.zx.y, this.reflectionTexture.sphericalPolynomial.zx.z);
  53953. }
  53954. }
  53955. if (this.emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  53956. this._effect.setTexture("emissiveSampler", this.emissiveTexture);
  53957. this._effect.setFloat2("vEmissiveInfos", this.emissiveTexture.coordinatesIndex, this.emissiveTexture.level);
  53958. this._effect.setMatrix("emissiveMatrix", this.emissiveTexture.getTextureMatrix());
  53959. }
  53960. if (this.lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  53961. this._effect.setTexture("lightmapSampler", this.lightmapTexture);
  53962. this._effect.setFloat2("vLightmapInfos", this.lightmapTexture.coordinatesIndex, this.lightmapTexture.level);
  53963. this._effect.setMatrix("lightmapMatrix", this.lightmapTexture.getTextureMatrix());
  53964. }
  53965. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  53966. if (this.metallicTexture) {
  53967. this._effect.setTexture("reflectivitySampler", this.metallicTexture);
  53968. this._effect.setFloat2("vReflectivityInfos", this.metallicTexture.coordinatesIndex, this.metallicTexture.level);
  53969. this._effect.setMatrix("reflectivityMatrix", this.metallicTexture.getTextureMatrix());
  53970. }
  53971. else if (this.reflectivityTexture) {
  53972. this._effect.setTexture("reflectivitySampler", this.reflectivityTexture);
  53973. this._effect.setFloat2("vReflectivityInfos", this.reflectivityTexture.coordinatesIndex, this.reflectivityTexture.level);
  53974. this._effect.setMatrix("reflectivityMatrix", this.reflectivityTexture.getTextureMatrix());
  53975. }
  53976. }
  53977. if (this.bumpTexture && this._myScene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this.disableBumpMap) {
  53978. this._effect.setTexture("bumpSampler", this.bumpTexture);
  53979. this._effect.setFloat3("vBumpInfos", this.bumpTexture.coordinatesIndex, 1.0 / this.bumpTexture.level, this.parallaxScaleBias);
  53980. this._effect.setMatrix("bumpMatrix", this.bumpTexture.getTextureMatrix());
  53981. }
  53982. if (this.refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  53983. this._microsurfaceTextureLods.y = Math.round(Math.log(this.refractionTexture.getSize().width) * Math.LOG2E);
  53984. var depth = 1.0;
  53985. if (this.refractionTexture.isCube) {
  53986. this._effect.setTexture("refractionCubeSampler", this.refractionTexture);
  53987. }
  53988. else {
  53989. this._effect.setTexture("refraction2DSampler", this.refractionTexture);
  53990. this._effect.setMatrix("refractionMatrix", this.refractionTexture.getReflectionTextureMatrix());
  53991. if (this.refractionTexture.depth) {
  53992. depth = this.refractionTexture.depth;
  53993. }
  53994. }
  53995. this._effect.setFloat4("vRefractionInfos", this.refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  53996. }
  53997. if ((this.reflectionTexture || this.refractionTexture)) {
  53998. this._effect.setFloat2("vMicrosurfaceTextureLods", this._microsurfaceTextureLods.x, this._microsurfaceTextureLods.y);
  53999. }
  54000. if (this.cameraColorGradingTexture && BABYLON.StandardMaterial.ColorGradingTextureEnabled) {
  54001. BABYLON.ColorGradingTexture.Bind(this.cameraColorGradingTexture, this._effect);
  54002. }
  54003. }
  54004. // Clip plane
  54005. BABYLON.MaterialHelper.BindClipPlane(this._effect, this._myScene);
  54006. // Point size
  54007. if (this.pointsCloud) {
  54008. this._effect.setFloat("pointSize", this.pointSize);
  54009. }
  54010. // Colors
  54011. this._myScene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  54012. if (this._defines.METALLICWORKFLOW) {
  54013. PBRMaterial._scaledReflectivity.r = this.metallic === undefined ? 1 : this.metallic;
  54014. PBRMaterial._scaledReflectivity.g = this.roughness === undefined ? 1 : this.roughness;
  54015. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, 0);
  54016. }
  54017. else {
  54018. // GAMMA CORRECTION.
  54019. this.convertColorToLinearSpaceToRef(this.reflectivityColor, PBRMaterial._scaledReflectivity);
  54020. this._effect.setColor4("vReflectivityColor", PBRMaterial._scaledReflectivity, this.microSurface);
  54021. }
  54022. this._effect.setVector3("vEyePosition", this._myScene._mirroredCameraPosition ? this._myScene._mirroredCameraPosition : this._myScene.activeCamera.position);
  54023. this._effect.setColor3("vAmbientColor", this._globalAmbientColor);
  54024. // GAMMA CORRECTION.
  54025. this.convertColorToLinearSpaceToRef(this.emissiveColor, PBRMaterial._scaledEmissive);
  54026. this._effect.setColor3("vEmissiveColor", PBRMaterial._scaledEmissive);
  54027. // GAMMA CORRECTION.
  54028. this.convertColorToLinearSpaceToRef(this.reflectionColor, PBRMaterial._scaledReflection);
  54029. this._effect.setColor3("vReflectionColor", PBRMaterial._scaledReflection);
  54030. }
  54031. if (this._myScene.getCachedMaterial() !== this || !this.isFrozen) {
  54032. // GAMMA CORRECTION.
  54033. this.convertColorToLinearSpaceToRef(this.albedoColor, PBRMaterial._scaledAlbedo);
  54034. this._effect.setColor4("vAlbedoColor", PBRMaterial._scaledAlbedo, this.alpha * mesh.visibility);
  54035. // Lights
  54036. if (this._myScene.lightsEnabled && !this.disableLighting) {
  54037. PBRMaterial.BindLights(this._myScene, mesh, this._effect, this._defines, this.useScalarInLinearSpace, this.maxSimultaneousLights, this.usePhysicalLightFalloff);
  54038. }
  54039. // View
  54040. if (this._myScene.fogEnabled && mesh.applyFog && this._myScene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this.reflectionTexture) {
  54041. this._effect.setMatrix("view", this._myScene.getViewMatrix());
  54042. }
  54043. // Fog
  54044. BABYLON.MaterialHelper.BindFogParameters(this._myScene, mesh, this._effect);
  54045. this._lightingInfos.x = this.directIntensity;
  54046. this._lightingInfos.y = this.emissiveIntensity;
  54047. this._lightingInfos.z = this.environmentIntensity;
  54048. this._lightingInfos.w = this.specularIntensity;
  54049. this._effect.setVector4("vLightingIntensity", this._lightingInfos);
  54050. this._overloadedShadowInfos.x = this.overloadedShadowIntensity;
  54051. this._overloadedShadowInfos.y = this.overloadedShadeIntensity;
  54052. this._effect.setVector4("vOverloadedShadowIntensity", this._overloadedShadowInfos);
  54053. this._cameraInfos.x = this.cameraExposure;
  54054. this._cameraInfos.y = this.cameraContrast;
  54055. this._effect.setVector4("vCameraInfos", this._cameraInfos);
  54056. if (this.cameraColorCurves) {
  54057. BABYLON.ColorCurves.Bind(this.cameraColorCurves, this._effect);
  54058. }
  54059. this._overloadedIntensity.x = this.overloadedAmbientIntensity;
  54060. this._overloadedIntensity.y = this.overloadedAlbedoIntensity;
  54061. this._overloadedIntensity.z = this.overloadedReflectivityIntensity;
  54062. this._overloadedIntensity.w = this.overloadedEmissiveIntensity;
  54063. this._effect.setVector4("vOverloadedIntensity", this._overloadedIntensity);
  54064. this._effect.setColor3("vOverloadedAmbient", this.overloadedAmbient);
  54065. this.convertColorToLinearSpaceToRef(this.overloadedAlbedo, this._tempColor);
  54066. this._effect.setColor3("vOverloadedAlbedo", this._tempColor);
  54067. this.convertColorToLinearSpaceToRef(this.overloadedReflectivity, this._tempColor);
  54068. this._effect.setColor3("vOverloadedReflectivity", this._tempColor);
  54069. this.convertColorToLinearSpaceToRef(this.overloadedEmissive, this._tempColor);
  54070. this._effect.setColor3("vOverloadedEmissive", this._tempColor);
  54071. this.convertColorToLinearSpaceToRef(this.overloadedReflection, this._tempColor);
  54072. this._effect.setColor3("vOverloadedReflection", this._tempColor);
  54073. this._overloadedMicroSurface.x = this.overloadedMicroSurface;
  54074. this._overloadedMicroSurface.y = this.overloadedMicroSurfaceIntensity;
  54075. this._overloadedMicroSurface.z = this.overloadedReflectionIntensity;
  54076. this._effect.setVector3("vOverloadedMicroSurface", this._overloadedMicroSurface);
  54077. // Log. depth
  54078. BABYLON.MaterialHelper.BindLogDepth(this._defines, this._effect, this._myScene);
  54079. }
  54080. _super.prototype.bind.call(this, world, mesh);
  54081. this._myScene = null;
  54082. };
  54083. PBRMaterial.prototype.getAnimatables = function () {
  54084. var results = [];
  54085. if (this.albedoTexture && this.albedoTexture.animations && this.albedoTexture.animations.length > 0) {
  54086. results.push(this.albedoTexture);
  54087. }
  54088. if (this.ambientTexture && this.ambientTexture.animations && this.ambientTexture.animations.length > 0) {
  54089. results.push(this.ambientTexture);
  54090. }
  54091. if (this.opacityTexture && this.opacityTexture.animations && this.opacityTexture.animations.length > 0) {
  54092. results.push(this.opacityTexture);
  54093. }
  54094. if (this.reflectionTexture && this.reflectionTexture.animations && this.reflectionTexture.animations.length > 0) {
  54095. results.push(this.reflectionTexture);
  54096. }
  54097. if (this.emissiveTexture && this.emissiveTexture.animations && this.emissiveTexture.animations.length > 0) {
  54098. results.push(this.emissiveTexture);
  54099. }
  54100. if (this.metallicTexture && this.metallicTexture.animations && this.metallicTexture.animations.length > 0) {
  54101. results.push(this.metallicTexture);
  54102. }
  54103. else if (this.reflectivityTexture && this.reflectivityTexture.animations && this.reflectivityTexture.animations.length > 0) {
  54104. results.push(this.reflectivityTexture);
  54105. }
  54106. if (this.bumpTexture && this.bumpTexture.animations && this.bumpTexture.animations.length > 0) {
  54107. results.push(this.bumpTexture);
  54108. }
  54109. if (this.lightmapTexture && this.lightmapTexture.animations && this.lightmapTexture.animations.length > 0) {
  54110. results.push(this.lightmapTexture);
  54111. }
  54112. if (this.refractionTexture && this.refractionTexture.animations && this.refractionTexture.animations.length > 0) {
  54113. results.push(this.refractionTexture);
  54114. }
  54115. if (this.cameraColorGradingTexture && this.cameraColorGradingTexture.animations && this.cameraColorGradingTexture.animations.length > 0) {
  54116. results.push(this.cameraColorGradingTexture);
  54117. }
  54118. return results;
  54119. };
  54120. PBRMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  54121. if (forceDisposeTextures) {
  54122. if (this.albedoTexture) {
  54123. this.albedoTexture.dispose();
  54124. }
  54125. if (this.ambientTexture) {
  54126. this.ambientTexture.dispose();
  54127. }
  54128. if (this.opacityTexture) {
  54129. this.opacityTexture.dispose();
  54130. }
  54131. if (this.reflectionTexture) {
  54132. this.reflectionTexture.dispose();
  54133. }
  54134. if (this.emissiveTexture) {
  54135. this.emissiveTexture.dispose();
  54136. }
  54137. if (this.metallicTexture) {
  54138. this.metallicTexture.dispose();
  54139. }
  54140. if (this.reflectivityTexture) {
  54141. this.reflectivityTexture.dispose();
  54142. }
  54143. if (this.bumpTexture) {
  54144. this.bumpTexture.dispose();
  54145. }
  54146. if (this.lightmapTexture) {
  54147. this.lightmapTexture.dispose();
  54148. }
  54149. if (this.refractionTexture) {
  54150. this.refractionTexture.dispose();
  54151. }
  54152. if (this.cameraColorGradingTexture) {
  54153. this.cameraColorGradingTexture.dispose();
  54154. }
  54155. }
  54156. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  54157. };
  54158. PBRMaterial.prototype.clone = function (name) {
  54159. var _this = this;
  54160. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  54161. };
  54162. PBRMaterial.prototype.serialize = function () {
  54163. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  54164. serializationObject.customType = "BABYLON.PBRMaterial";
  54165. return serializationObject;
  54166. };
  54167. // Statics
  54168. PBRMaterial.Parse = function (source, scene, rootUrl) {
  54169. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  54170. };
  54171. return PBRMaterial;
  54172. }(BABYLON.Material));
  54173. PBRMaterial._scaledAlbedo = new BABYLON.Color3();
  54174. PBRMaterial._scaledReflectivity = new BABYLON.Color3();
  54175. PBRMaterial._scaledEmissive = new BABYLON.Color3();
  54176. PBRMaterial._scaledReflection = new BABYLON.Color3();
  54177. __decorate([
  54178. BABYLON.serialize()
  54179. ], PBRMaterial.prototype, "directIntensity", void 0);
  54180. __decorate([
  54181. BABYLON.serialize()
  54182. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  54183. __decorate([
  54184. BABYLON.serialize()
  54185. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  54186. __decorate([
  54187. BABYLON.serialize()
  54188. ], PBRMaterial.prototype, "specularIntensity", void 0);
  54189. __decorate([
  54190. BABYLON.serialize()
  54191. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  54192. __decorate([
  54193. BABYLON.serialize()
  54194. ], PBRMaterial.prototype, "overloadedShadowIntensity", void 0);
  54195. __decorate([
  54196. BABYLON.serialize()
  54197. ], PBRMaterial.prototype, "overloadedShadeIntensity", void 0);
  54198. __decorate([
  54199. BABYLON.serialize()
  54200. ], PBRMaterial.prototype, "cameraExposure", void 0);
  54201. __decorate([
  54202. BABYLON.serialize()
  54203. ], PBRMaterial.prototype, "cameraContrast", void 0);
  54204. __decorate([
  54205. BABYLON.serializeAsTexture()
  54206. ], PBRMaterial.prototype, "cameraColorGradingTexture", void 0);
  54207. __decorate([
  54208. BABYLON.serializeAsColorCurves()
  54209. ], PBRMaterial.prototype, "cameraColorCurves", void 0);
  54210. __decorate([
  54211. BABYLON.serializeAsColor3()
  54212. ], PBRMaterial.prototype, "overloadedAmbient", void 0);
  54213. __decorate([
  54214. BABYLON.serialize()
  54215. ], PBRMaterial.prototype, "overloadedAmbientIntensity", void 0);
  54216. __decorate([
  54217. BABYLON.serializeAsColor3()
  54218. ], PBRMaterial.prototype, "overloadedAlbedo", void 0);
  54219. __decorate([
  54220. BABYLON.serialize()
  54221. ], PBRMaterial.prototype, "overloadedAlbedoIntensity", void 0);
  54222. __decorate([
  54223. BABYLON.serializeAsColor3()
  54224. ], PBRMaterial.prototype, "overloadedReflectivity", void 0);
  54225. __decorate([
  54226. BABYLON.serialize()
  54227. ], PBRMaterial.prototype, "overloadedReflectivityIntensity", void 0);
  54228. __decorate([
  54229. BABYLON.serializeAsColor3()
  54230. ], PBRMaterial.prototype, "overloadedEmissive", void 0);
  54231. __decorate([
  54232. BABYLON.serialize()
  54233. ], PBRMaterial.prototype, "overloadedEmissiveIntensity", void 0);
  54234. __decorate([
  54235. BABYLON.serializeAsColor3()
  54236. ], PBRMaterial.prototype, "overloadedReflection", void 0);
  54237. __decorate([
  54238. BABYLON.serialize()
  54239. ], PBRMaterial.prototype, "overloadedReflectionIntensity", void 0);
  54240. __decorate([
  54241. BABYLON.serialize()
  54242. ], PBRMaterial.prototype, "overloadedMicroSurface", void 0);
  54243. __decorate([
  54244. BABYLON.serialize()
  54245. ], PBRMaterial.prototype, "overloadedMicroSurfaceIntensity", void 0);
  54246. __decorate([
  54247. BABYLON.serializeAsTexture()
  54248. ], PBRMaterial.prototype, "albedoTexture", void 0);
  54249. __decorate([
  54250. BABYLON.serializeAsTexture()
  54251. ], PBRMaterial.prototype, "ambientTexture", void 0);
  54252. __decorate([
  54253. BABYLON.serialize()
  54254. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  54255. __decorate([
  54256. BABYLON.serializeAsTexture()
  54257. ], PBRMaterial.prototype, "opacityTexture", void 0);
  54258. __decorate([
  54259. BABYLON.serializeAsTexture()
  54260. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  54261. __decorate([
  54262. BABYLON.serializeAsTexture()
  54263. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  54264. __decorate([
  54265. BABYLON.serializeAsTexture()
  54266. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  54267. __decorate([
  54268. BABYLON.serializeAsTexture()
  54269. ], PBRMaterial.prototype, "metallicTexture", void 0);
  54270. __decorate([
  54271. BABYLON.serialize()
  54272. ], PBRMaterial.prototype, "metallic", void 0);
  54273. __decorate([
  54274. BABYLON.serialize()
  54275. ], PBRMaterial.prototype, "roughness", void 0);
  54276. __decorate([
  54277. BABYLON.serializeAsTexture()
  54278. ], PBRMaterial.prototype, "bumpTexture", void 0);
  54279. __decorate([
  54280. BABYLON.serializeAsTexture()
  54281. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  54282. __decorate([
  54283. BABYLON.serializeAsTexture()
  54284. ], PBRMaterial.prototype, "refractionTexture", void 0);
  54285. __decorate([
  54286. BABYLON.serializeAsColor3("ambient")
  54287. ], PBRMaterial.prototype, "ambientColor", void 0);
  54288. __decorate([
  54289. BABYLON.serializeAsColor3("albedo")
  54290. ], PBRMaterial.prototype, "albedoColor", void 0);
  54291. __decorate([
  54292. BABYLON.serializeAsColor3("reflectivity")
  54293. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  54294. __decorate([
  54295. BABYLON.serializeAsColor3("reflection")
  54296. ], PBRMaterial.prototype, "reflectionColor", void 0);
  54297. __decorate([
  54298. BABYLON.serializeAsColor3("emissive")
  54299. ], PBRMaterial.prototype, "emissiveColor", void 0);
  54300. __decorate([
  54301. BABYLON.serialize()
  54302. ], PBRMaterial.prototype, "microSurface", void 0);
  54303. __decorate([
  54304. BABYLON.serialize()
  54305. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  54306. __decorate([
  54307. BABYLON.serialize()
  54308. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  54309. __decorate([
  54310. BABYLON.serializeAsFresnelParameters()
  54311. ], PBRMaterial.prototype, "opacityFresnelParameters", void 0);
  54312. __decorate([
  54313. BABYLON.serializeAsFresnelParameters()
  54314. ], PBRMaterial.prototype, "emissiveFresnelParameters", void 0);
  54315. __decorate([
  54316. BABYLON.serialize()
  54317. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  54318. __decorate([
  54319. BABYLON.serialize()
  54320. ], PBRMaterial.prototype, "linkEmissiveWithAlbedo", void 0);
  54321. __decorate([
  54322. BABYLON.serialize()
  54323. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  54324. __decorate([
  54325. BABYLON.serialize()
  54326. ], PBRMaterial.prototype, "useEmissiveAsIllumination", void 0);
  54327. __decorate([
  54328. BABYLON.serialize()
  54329. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  54330. __decorate([
  54331. BABYLON.serialize()
  54332. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  54333. __decorate([
  54334. BABYLON.serialize()
  54335. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  54336. __decorate([
  54337. BABYLON.serialize()
  54338. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  54339. __decorate([
  54340. BABYLON.serialize()
  54341. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  54342. __decorate([
  54343. BABYLON.serialize()
  54344. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  54345. __decorate([
  54346. BABYLON.serialize()
  54347. ], PBRMaterial.prototype, "useScalarInLinearSpace", void 0);
  54348. __decorate([
  54349. BABYLON.serialize()
  54350. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  54351. __decorate([
  54352. BABYLON.serialize()
  54353. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  54354. __decorate([
  54355. BABYLON.serialize()
  54356. ], PBRMaterial.prototype, "useParallax", void 0);
  54357. __decorate([
  54358. BABYLON.serialize()
  54359. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  54360. __decorate([
  54361. BABYLON.serialize()
  54362. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  54363. __decorate([
  54364. BABYLON.serialize()
  54365. ], PBRMaterial.prototype, "disableLighting", void 0);
  54366. __decorate([
  54367. BABYLON.serialize()
  54368. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  54369. __decorate([
  54370. BABYLON.serialize()
  54371. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  54372. __decorate([
  54373. BABYLON.serialize()
  54374. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  54375. __decorate([
  54376. BABYLON.serialize()
  54377. ], PBRMaterial.prototype, "useLogarithmicDepth", null);
  54378. BABYLON.PBRMaterial = PBRMaterial;
  54379. })(BABYLON || (BABYLON = {}));
  54380. //# sourceMappingURL=babylon.pbrMaterial.js.map
  54381. var BABYLON;
  54382. (function (BABYLON) {
  54383. var DebugLayer = (function () {
  54384. function DebugLayer(scene) {
  54385. this._scene = scene;
  54386. }
  54387. /** Creates the inspector window. */
  54388. DebugLayer.prototype._createInspector = function (popup) {
  54389. if (!this._inspector) {
  54390. this._inspector = new INSPECTOR.Inspector(this._scene, popup);
  54391. } // else nothing to do,; instance is already existing
  54392. };
  54393. DebugLayer.prototype.isVisible = function () {
  54394. return false;
  54395. };
  54396. DebugLayer.prototype.hide = function () {
  54397. if (this._inspector) {
  54398. this._inspector.dispose();
  54399. this._inspector = null;
  54400. }
  54401. };
  54402. DebugLayer.prototype.show = function (popup) {
  54403. if (typeof INSPECTOR == 'undefined') {
  54404. // Load inspector and add it to the DOM
  54405. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, popup));
  54406. }
  54407. else {
  54408. // Otherwise creates the inspector
  54409. this._createInspector(popup);
  54410. }
  54411. };
  54412. return DebugLayer;
  54413. }());
  54414. DebugLayer.InspectorURL = 'http://www.babylonjs.com/babylon.inspector.bundle.js';
  54415. BABYLON.DebugLayer = DebugLayer;
  54416. })(BABYLON || (BABYLON = {}));
  54417. //# sourceMappingURL=babylon.debugLayer.js.map
  54418. var BABYLON;
  54419. (function (BABYLON) {
  54420. var StandardRenderingPipeline = (function (_super) {
  54421. __extends(StandardRenderingPipeline, _super);
  54422. /**
  54423. * @constructor
  54424. * @param {string} name - The rendering pipeline name
  54425. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  54426. * @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)
  54427. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  54428. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  54429. */
  54430. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  54431. if (originalPostProcess === void 0) { originalPostProcess = null; }
  54432. var _this = _super.call(this, scene.getEngine(), name) || this;
  54433. _this.downSampleX4PostProcess = null;
  54434. _this.brightPassPostProcess = null;
  54435. _this.gaussianBlurHPostProcesses = [];
  54436. _this.gaussianBlurVPostProcesses = [];
  54437. _this.textureAdderPostProcess = null;
  54438. _this.textureAdderFinalPostProcess = null;
  54439. _this.lensFlarePostProcess = null;
  54440. _this.lensFlareComposePostProcess = null;
  54441. _this.depthOfFieldPostProcess = null;
  54442. // Values
  54443. _this.brightThreshold = 1.0;
  54444. _this.blurWidth = 2.0;
  54445. _this.gaussianCoefficient = 0.25;
  54446. _this.gaussianMean = 1.0;
  54447. _this.gaussianStandardDeviation = 1.0;
  54448. _this.exposure = 1.0;
  54449. _this.lensTexture = null;
  54450. _this.lensColorTexture = null;
  54451. _this.lensFlareStrength = 20.0;
  54452. _this.lensFlareGhostDispersal = 1.4;
  54453. _this.lensFlareHaloWidth = 0.7;
  54454. _this.lensFlareDistortionStrength = 16.0;
  54455. _this.lensStarTexture = null;
  54456. _this.lensFlareDirtTexture = null;
  54457. _this.depthOfFieldDistance = 10.0;
  54458. // IAnimatable
  54459. _this.animations = [];
  54460. _this._depthRenderer = null;
  54461. // Getters and setters
  54462. _this._depthOfFieldEnabled = true;
  54463. _this._lensFlareEnabled = true;
  54464. // Initialize
  54465. _this._scene = scene;
  54466. // Create pass post-processe
  54467. if (!originalPostProcess) {
  54468. _this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_FLOAT);
  54469. }
  54470. else {
  54471. _this.originalPostProcess = originalPostProcess;
  54472. }
  54473. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  54474. // Create down sample X4 post-process
  54475. _this._createDownSampleX4PostProcess(scene, ratio / 2);
  54476. // Create bright pass post-process
  54477. _this._createBrightPassPostProcess(scene, ratio / 2);
  54478. // Create gaussian blur post-processes (down sampling blurs)
  54479. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 0);
  54480. _this._createGaussianBlurPostProcesses(scene, ratio / 4, 1);
  54481. _this._createGaussianBlurPostProcesses(scene, ratio / 8, 2);
  54482. _this._createGaussianBlurPostProcesses(scene, ratio / 16, 3);
  54483. // Create texture adder post-process
  54484. _this._createTextureAdderPostProcess(scene, ratio);
  54485. // Create depth-of-field source post-process
  54486. _this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54487. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  54488. // Create lens flare post-process
  54489. _this._createLensFlarePostProcess(scene, ratio);
  54490. // Create gaussian blur used by depth-of-field
  54491. _this._createGaussianBlurPostProcesses(scene, ratio / 2, 5);
  54492. // Create depth-of-field post-process
  54493. _this._createDepthOfFieldPostProcess(scene, ratio);
  54494. // Finish
  54495. scene.postProcessRenderPipelineManager.addPipeline(_this);
  54496. if (cameras !== null) {
  54497. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  54498. }
  54499. // Deactivate
  54500. _this.LensFlareEnabled = false;
  54501. _this.DepthOfFieldEnabled = false;
  54502. return _this;
  54503. }
  54504. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  54505. get: function () {
  54506. return this._depthOfFieldEnabled;
  54507. },
  54508. set: function (enabled) {
  54509. var blurIndex = this.gaussianBlurHPostProcesses.length - 1;
  54510. if (enabled && !this._depthOfFieldEnabled) {
  54511. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54512. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54513. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54514. this._depthRenderer = this._scene.enableDepthRenderer();
  54515. }
  54516. else if (!enabled && this._depthOfFieldEnabled) {
  54517. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54518. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54519. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRDepthOfField", this._scene.cameras);
  54520. }
  54521. this._depthOfFieldEnabled = enabled;
  54522. },
  54523. enumerable: true,
  54524. configurable: true
  54525. });
  54526. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  54527. get: function () {
  54528. return this._lensFlareEnabled;
  54529. },
  54530. set: function (enabled) {
  54531. var blurIndex = this.gaussianBlurHPostProcesses.length - 2;
  54532. if (enabled && !this._lensFlareEnabled) {
  54533. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54534. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54535. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54536. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54537. this._scene.postProcessRenderPipelineManager.enableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54538. }
  54539. else if (!enabled && this._lensFlareEnabled) {
  54540. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlare", this._scene.cameras);
  54541. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareShift", this._scene.cameras);
  54542. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurH" + blurIndex, this._scene.cameras);
  54543. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRGaussianBlurV" + blurIndex, this._scene.cameras);
  54544. this._scene.postProcessRenderPipelineManager.disableEffectInPipeline(this._name, "HDRLensFlareCompose", this._scene.cameras);
  54545. }
  54546. this._lensFlareEnabled = enabled;
  54547. },
  54548. enumerable: true,
  54549. configurable: true
  54550. });
  54551. // Down Sample X4 Post-Processs
  54552. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  54553. var _this = this;
  54554. var downSampleX4Offsets = new Array(32);
  54555. this.downSampleX4PostProcess = new BABYLON.PostProcess("HDRDownSampleX4", "standard", ["dsOffsets"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DOWN_SAMPLE_X4", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54556. this.downSampleX4PostProcess.onApply = function (effect) {
  54557. var id = 0;
  54558. for (var i = -2; i < 2; i++) {
  54559. for (var j = -2; j < 2; j++) {
  54560. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  54561. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  54562. id += 2;
  54563. }
  54564. }
  54565. effect.setArray2("dsOffsets", downSampleX4Offsets);
  54566. };
  54567. // Add to pipeline
  54568. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  54569. };
  54570. // Brightpass Post-Process
  54571. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  54572. var _this = this;
  54573. var brightOffsets = new Array(8);
  54574. this.brightPassPostProcess = new BABYLON.PostProcess("HDRBrightPass", "standard", ["dsOffsets", "brightThreshold"], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define BRIGHT_PASS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54575. this.brightPassPostProcess.onApply = function (effect) {
  54576. var sU = (1.0 / _this.brightPassPostProcess.width);
  54577. var sV = (1.0 / _this.brightPassPostProcess.height);
  54578. brightOffsets[0] = -0.5 * sU;
  54579. brightOffsets[1] = 0.5 * sV;
  54580. brightOffsets[2] = 0.5 * sU;
  54581. brightOffsets[3] = 0.5 * sV;
  54582. brightOffsets[4] = -0.5 * sU;
  54583. brightOffsets[5] = -0.5 * sV;
  54584. brightOffsets[6] = 0.5 * sU;
  54585. brightOffsets[7] = -0.5 * sV;
  54586. effect.setArray2("dsOffsets", brightOffsets);
  54587. effect.setFloat("brightThreshold", _this.brightThreshold);
  54588. };
  54589. // Add to pipeline
  54590. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  54591. };
  54592. // Create gaussian blur H&V post-processes
  54593. StandardRenderingPipeline.prototype._createGaussianBlurPostProcesses = function (scene, ratio, indice) {
  54594. var _this = this;
  54595. var blurOffsets = new Array(9);
  54596. var blurWeights = new Array(9);
  54597. var uniforms = ["blurOffsets", "blurWeights", "blurWidth"];
  54598. var callback = function (height) {
  54599. return function (effect) {
  54600. // Weights
  54601. var x = 0.0;
  54602. for (var i = 0; i < 9; i++) {
  54603. x = (i - 4.0) / 4.0;
  54604. blurWeights[i] =
  54605. _this.gaussianCoefficient
  54606. * (1.0 / Math.sqrt(2.0 * Math.PI * _this.gaussianStandardDeviation))
  54607. * Math.exp((-((x - _this.gaussianMean) * (x - _this.gaussianMean))) / (2.0 * _this.gaussianStandardDeviation * _this.gaussianStandardDeviation));
  54608. }
  54609. var lastOutputDimensions = {
  54610. width: scene.getEngine().getRenderWidth(),
  54611. height: scene.getEngine().getRenderHeight()
  54612. };
  54613. for (var i = 0; i < 9; i++) {
  54614. var value = (i - 4.0) * (1.0 / (height === true ? lastOutputDimensions.height : lastOutputDimensions.width));
  54615. blurOffsets[i] = value;
  54616. }
  54617. effect.setArray("blurOffsets", blurOffsets);
  54618. effect.setArray("blurWeights", blurWeights);
  54619. effect.setFloat("blurWidth", _this.blurWidth);
  54620. };
  54621. };
  54622. // Create horizontal gaussian blur post-processes
  54623. var gaussianBlurHPostProcess = new BABYLON.PostProcess("HDRGaussianBlurH" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_H", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54624. gaussianBlurHPostProcess.onApply = callback(false);
  54625. // Create vertical gaussian blur post-process
  54626. var gaussianBlurVPostProcess = new BABYLON.PostProcess("HDRGaussianBlurV" + ratio, "standard", uniforms, [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define GAUSSIAN_BLUR_V", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54627. gaussianBlurVPostProcess.onApply = callback(true);
  54628. // Add to pipeline
  54629. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurH" + indice, function () { return gaussianBlurHPostProcess; }, true));
  54630. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRGaussianBlurV" + indice, function () { return gaussianBlurVPostProcess; }, true));
  54631. // Finish
  54632. this.gaussianBlurHPostProcesses.push(gaussianBlurHPostProcess);
  54633. this.gaussianBlurVPostProcesses.push(gaussianBlurVPostProcess);
  54634. };
  54635. // Create texture adder post-process
  54636. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  54637. var _this = this;
  54638. var lastGaussianBlurPostProcess = this.gaussianBlurVPostProcesses[3];
  54639. this.textureAdderPostProcess = new BABYLON.PostProcess("HDRTextureAdder", "standard", ["exposure"], ["otherSampler", "lensSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define TEXTURE_ADDER", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54640. this.textureAdderPostProcess.onApply = function (effect) {
  54641. effect.setTextureFromPostProcess("otherSampler", _this.originalPostProcess);
  54642. effect.setTexture("lensSampler", _this.lensTexture);
  54643. effect.setFloat("exposure", _this.exposure);
  54644. };
  54645. // Add to pipeline
  54646. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  54647. };
  54648. // Create lens flare post-process
  54649. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  54650. var _this = this;
  54651. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), true, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54652. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, false));
  54653. this._createGaussianBlurPostProcesses(scene, ratio / 4, 4);
  54654. this.lensFlareComposePostProcess = new BABYLON.PostProcess("HDRLensFlareCompose", "standard", ["lensStarMatrix"], ["otherSampler", "lensDirtSampler", "lensStarSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE_COMPOSE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54655. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, false));
  54656. var resolution = new BABYLON.Vector2(0, 0);
  54657. // Lens flare
  54658. this.lensFlarePostProcess.onApply = function (effect) {
  54659. effect.setTextureFromPostProcess("textureSampler", _this.gaussianBlurHPostProcesses[0]);
  54660. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  54661. effect.setFloat("strength", _this.lensFlareStrength);
  54662. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  54663. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  54664. // Shift
  54665. resolution.x = _this.lensFlarePostProcess.width;
  54666. resolution.y = _this.lensFlarePostProcess.height;
  54667. effect.setVector2("resolution", resolution);
  54668. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  54669. };
  54670. // Compose
  54671. var scaleBias1 = BABYLON.Matrix.FromValues(2.0, 0.0, -1.0, 0.0, 0.0, 2.0, -1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54672. var scaleBias2 = BABYLON.Matrix.FromValues(0.5, 0.0, 0.5, 0.0, 0.0, 0.5, 0.5, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54673. this.lensFlareComposePostProcess.onApply = function (effect) {
  54674. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54675. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  54676. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  54677. // Lens start rotation matrix
  54678. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  54679. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  54680. var camRot = BABYLON.Vector3.Dot(camerax.toVector3(), new BABYLON.Vector3(1.0, 0.0, 0.0)) + BABYLON.Vector3.Dot(cameraz.toVector3(), new BABYLON.Vector3(0.0, 0.0, 1.0));
  54681. camRot *= 4.0;
  54682. var starRotation = BABYLON.Matrix.FromValues(Math.cos(camRot) * 0.5, -Math.sin(camRot), 0.0, 0.0, Math.sin(camRot), Math.cos(camRot) * 0.5, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  54683. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  54684. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  54685. };
  54686. };
  54687. // Create depth-of-field post-process
  54688. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  54689. var _this = this;
  54690. this.depthOfFieldPostProcess = new BABYLON.PostProcess("HDRDepthOfField", "standard", ["distance"], ["otherSampler", "depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define DEPTH_OF_FIELD", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54691. this.depthOfFieldPostProcess.onApply = function (effect) {
  54692. effect.setTextureFromPostProcess("otherSampler", _this.textureAdderFinalPostProcess);
  54693. effect.setTexture("depthSampler", _this._depthRenderer.getDepthMap());
  54694. effect.setFloat("distance", _this.depthOfFieldDistance);
  54695. };
  54696. // Add to pipeline
  54697. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  54698. };
  54699. // Dispose
  54700. StandardRenderingPipeline.prototype.dispose = function () {
  54701. for (var i = 0; i < this._scene.cameras.length; i++) {
  54702. var camera = this._scene.cameras[i];
  54703. this.originalPostProcess.dispose(camera);
  54704. this.downSampleX4PostProcess.dispose(camera);
  54705. this.brightPassPostProcess.dispose(camera);
  54706. this.textureAdderPostProcess.dispose(camera);
  54707. for (var j = 0; j < this.gaussianBlurHPostProcesses.length; j++) {
  54708. this.gaussianBlurHPostProcesses[j].dispose(camera);
  54709. }
  54710. for (var j = 0; j < this.gaussianBlurVPostProcesses.length; j++) {
  54711. this.gaussianBlurVPostProcesses[j].dispose(camera);
  54712. }
  54713. this.textureAdderFinalPostProcess.dispose(camera);
  54714. this.lensFlarePostProcess.dispose(camera);
  54715. this.lensFlareComposePostProcess.dispose(camera);
  54716. this.depthOfFieldPostProcess.dispose(camera);
  54717. }
  54718. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  54719. _super.prototype.dispose.call(this);
  54720. };
  54721. return StandardRenderingPipeline;
  54722. }(BABYLON.PostProcessRenderPipeline));
  54723. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  54724. })(BABYLON || (BABYLON = {}));
  54725. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  54726. 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..maxSimultaneousLights]\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#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition> \n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#include<colorCurves>\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#include<bumpFragment>\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\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+uvOffset).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+uvOffset);\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#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\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+uvOffset);\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+uvOffset).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\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#include<logDepthFragment>\n#include<fogFragment>\n#ifdef CAMERACOLORGRADING\ncolor=colorGrades(color);\n#endif\n#ifdef CAMERACOLORCURVES\ncolor.rgb=applyColorCurves(color.rgb);\n#endif\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>[0..maxSimultaneousLights]\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>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\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}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\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{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive);\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\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 DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\nbaseColor.a=abs(offset-baseColor.a);\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\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}","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}","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}","pbrPixelShader":"#ifdef BUMP\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vCameraInfos;\n#ifdef OVERLOADEDVALUES\nuniform vec4 vOverloadedIntensity;\nuniform vec3 vOverloadedAmbient;\nuniform vec3 vOverloadedAlbedo;\nuniform vec3 vOverloadedReflectivity;\nuniform vec3 vOverloadedEmissive;\nuniform vec3 vOverloadedReflection;\nuniform vec3 vOverloadedMicroSurface;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nuniform vec4 vOverloadedShadowIntensity;\n#endif\n#if defined(REFLECTION) || defined(REFRACTION)\nuniform vec2 vMicrosurfaceTextureLods;\n#endif\nuniform vec4 vReflectivityColor;\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<lightFragmentDeclaration>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\nvarying vec2 vAlbedoUV;\nuniform sampler2D albedoSampler;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform sampler2D ambientSampler;\nuniform vec3 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(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform sampler2D reflectivitySampler;\n#endif\n\n#include<fresnelFunction>\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\nuniform mat4 refractionMatrix;\n#endif\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#endif\n#ifdef CAMERACOLORGRADING\n#include<colorGradingDefinition>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurvesDefinition>\n#endif\n\n#include<pbrShadowFunctions>\n#include<pbrFunctions>\n#ifdef CAMERACOLORGRADING\n#include<colorGrading>\n#endif\n#ifdef CAMERACOLORCURVES\n#include<colorCurves>\n#endif\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<helperFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(1.0,1.0,1.0);\n#endif\n#include<bumpFragment>\n\nvec4 surfaceAlbedo=vec4(1.,1.,1.,1.);\nvec3 surfaceAlbedoContribution=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nsurfaceAlbedo=texture2D(albedoSampler,vAlbedoUV+uvOffset);\nsurfaceAlbedo=vec4(toLinearSpace(surfaceAlbedo.rgb),surfaceAlbedo.a);\n#ifndef LINKREFRACTIONTOTRANSPARENCY\n#ifdef ALPHATEST\nif (surfaceAlbedo.a<0.4)\ndiscard;\n#endif\n#endif\n#ifdef ALPHAFROMALBEDO\nalpha*=surfaceAlbedo.a;\n#endif\nsurfaceAlbedo.rgb*=vAlbedoInfos.y;\n#else\n\nsurfaceAlbedo.rgb=surfaceAlbedoContribution;\nsurfaceAlbedoContribution=vec3(1.,1.,1.);\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo.rgb*=vColor.rgb;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceAlbedo.rgb=mix(surfaceAlbedo.rgb,vOverloadedAlbedo,vOverloadedIntensity.y);\n#endif\n\nvec3 ambientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nambientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\nambientColor=vec3(1.,1.,1.)-((vec3(1.,1.,1.)-ambientColor)*vAmbientInfos.z);\n#ifdef OVERLOADEDVALUES\nambientColor.rgb=mix(ambientColor.rgb,vOverloadedAmbient,vOverloadedIntensity.x);\n#endif\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor.rgb=mix(surfaceReflectivityColor.rgb,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor=surfaceReflectivityColorMap.rgb;\nsurfaceReflectivityColor=toLinearSpace(surfaceReflectivityColor);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface=surfaceReflectivityColorMap.a;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#endif\n#endif\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef METALLICROUGHNESSMAP\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#ifdef METALLICROUGHNESSGSTOREINALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef METALLICROUGHNESSGSTOREINGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n\nvec3 baseColor=surfaceAlbedo.rgb;\n\nsurfaceAlbedo.rgb*=(1.0-metallicRoughness.r);\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#ifdef OVERLOADEDVALUES\nsurfaceReflectivityColor=mix(surfaceReflectivityColor,vOverloadedReflectivity,vOverloadedIntensity.z);\n#endif\nmicroSurface=1.0-metallicRoughness.g;\n#endif\n#ifdef OVERLOADEDVALUES\nmicroSurface=mix(microSurface,vOverloadedMicroSurface.x,vOverloadedMicroSurface.y);\n#endif\n\nfloat NdotV=max(0.00000000001,dot(normalW,viewDirectionW));\n\nmicroSurface=clamp(microSurface,0.,1.)*0.98;\n\nfloat roughness=clamp(1.-microSurface,0.000001,1.0);\n\nvec3 lightDiffuseContribution=vec3(0.,0.,0.);\n#ifdef OVERLOADEDSHADOWVALUES\nvec3 shadowedOnlyLightDiffuseContribution=vec3(1.,1.,1.);\n#endif\n#ifdef SPECULARTERM\nvec3 lightSpecularContribution=vec3(0.,0.,0.);\n#endif\nfloat notShadowLevel=1.; \n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nfloat NdotL=-1.;\nlightingInfo info;\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\n\n\nfloat reflectance90=clamp(reflectance*25.0,0.0,1.0);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n#include<pbrLightFunctionsCall>[0..maxSimultaneousLights]\n#ifdef SPECULARTERM\nlightSpecularContribution*=vLightingIntensity.w;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\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 surfaceRefractionColor=vec3(0.,0.,0.);\n\n#ifdef LODBASEDMICROSFURACE\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#endif\n#ifdef REFRACTION\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\nfloat lodRefraction=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.y,alphaG);\n#else\nfloat lodRefraction=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.y,alphaG);\n#endif\n#else\nfloat biasRefraction=(vMicrosurfaceTextureLods.y+2.)*(1.0-microSurface);\n#endif\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0)\n{\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFRACTION\n\nif ((vMicrosurfaceTextureLods.y-lodRefraction)>4.0)\n{\n\nfloat scaleRefraction=1.-exp2(lodRefraction)/exp2(vMicrosurfaceTextureLods.y); \nfloat maxRefraction=max(max(abs(refractionVector.x),abs(refractionVector.y)),abs(refractionVector.z));\nif (abs(refractionVector.x) != maxRefraction) refractionVector.x*=scaleRefraction;\nif (abs(refractionVector.y) != maxRefraction) refractionVector.y*=scaleRefraction;\nif (abs(refractionVector.z) != maxRefraction) refractionVector.z*=scaleRefraction;\n}\n#endif\nsurfaceRefractionColor=textureCubeLodEXT(refractionCubeSampler,refractionVector,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=textureCube(refractionCubeSampler,refractionVector,biasRefraction).rgb*vRefractionInfos.x;\n#endif\n}\n#ifndef REFRACTIONMAPINLINEARSPACE\nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\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;\n#ifdef LODBASEDMICROSFURACE\nsurfaceRefractionColor=texture2DLodEXT(refraction2DSampler,refractionCoords,lodRefraction).rgb*vRefractionInfos.x;\n#else\nsurfaceRefractionColor=texture2D(refraction2DSampler,refractionCoords,biasRefraction).rgb*vRefractionInfos.x;\n#endif \nsurfaceRefractionColor=toLinearSpace(surfaceRefractionColor.rgb);\n#endif\n#endif\n\nvec3 environmentRadiance=vReflectionColor.rgb;\nvec3 environmentIrradiance=vReflectionColor.rgb;\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\nfloat lodReflection=getMipMapIndexFromAverageSlopeWithPMREM(vMicrosurfaceTextureLods.x,alphaG);\n#else\nfloat lodReflection=getMipMapIndexFromAverageSlope(vMicrosurfaceTextureLods.x,alphaG);\n#endif\n#else\nfloat biasReflection=(vMicrosurfaceTextureLods.x+2.)*(1.0-microSurface);\n#endif\n#ifdef REFLECTIONMAP_3D\n#ifdef LODBASEDMICROSFURACE\n#ifdef USEPMREMREFLECTION\n\nif ((vMicrosurfaceTextureLods.y-lodReflection)>4.0)\n{\n\nfloat scaleReflection=1.-exp2(lodReflection)/exp2(vMicrosurfaceTextureLods.x); \nfloat maxReflection=max(max(abs(vReflectionUVW.x),abs(vReflectionUVW.y)),abs(vReflectionUVW.z));\nif (abs(vReflectionUVW.x) != maxReflection) vReflectionUVW.x*=scaleReflection;\nif (abs(vReflectionUVW.y) != maxReflection) vReflectionUVW.y*=scaleReflection;\nif (abs(vReflectionUVW.z) != maxReflection) vReflectionUVW.z*=scaleReflection;\n}\n#endif\nenvironmentRadiance=textureCubeLodEXT(reflectionCubeSampler,vReflectionUVW,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=textureCube(reflectionCubeSampler,vReflectionUVW,biasReflection).rgb*vReflectionInfos.x;\n#endif\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#ifndef REFLECTIONMAP_SKYBOX\nvec3 normalEnvironmentSpace=(reflectionMatrix*vec4(normalW,1)).xyz;\nenvironmentIrradiance=EnvironmentIrradiance(normalEnvironmentSpace);\n#endif\n#else\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=textureCube(reflectionCubeSampler,normalW,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\nenvironmentIrradiance*=0.2; \n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\n#ifdef LODBASEDMICROSFURACE\nenvironmentRadiance=texture2DLodEXT(reflection2DSampler,coords,lodReflection).rgb*vReflectionInfos.x;\n#else\nenvironmentRadiance=texture2D(reflection2DSampler,coords,biasReflection).rgb*vReflectionInfos.x;\n#endif\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\nenvironmentIrradiance=texture2D(reflection2DSampler,coords,20.).rgb*vReflectionInfos.x;\nenvironmentIrradiance=toLinearSpace(environmentIrradiance.rgb);\n#endif\n#endif\n#ifdef OVERLOADEDVALUES\nenvironmentIrradiance=mix(environmentIrradiance,vOverloadedReflection,vOverloadedMicroSurface.z);\nenvironmentRadiance=mix(environmentRadiance,vOverloadedReflection,vOverloadedMicroSurface.z);\n#endif\nenvironmentRadiance*=vLightingIntensity.z;\nenvironmentIrradiance*=vLightingIntensity.z;\n\nvec3 specularEnvironmentReflectance=FresnelSchlickEnvironmentGGX(clamp(NdotV,0.,1.),specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n\nvec3 refractance=vec3(0.0,0.0,0.0);\n#ifdef REFRACTION\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedoContribution.rgb*surfaceAlbedo.rgb;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedoContribution*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nsurfaceRefractionColor*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=surfaceRefractionColor*transmission;\n#endif\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\nrefractance*=vLightingIntensity.z;\nenvironmentRadiance*=specularEnvironmentReflectance;\n\nvec3 surfaceEmissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nsurfaceEmissiveColor=toLinearSpace(emissiveColorTex.rgb)*surfaceEmissiveColor*vEmissiveInfos.y;\n#endif\n#ifdef OVERLOADEDVALUES\nsurfaceEmissiveColor=mix(surfaceEmissiveColor,vOverloadedEmissive,vOverloadedIntensity.w);\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nsurfaceEmissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\n#ifdef LINKEMISSIVEWITHALBEDO\nvec3 finalDiffuse=max((lightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max((shadowedOnlyLightDiffuseContribution+surfaceEmissiveColor)*surfaceAlbedoContribution+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#else\nvec3 finalDiffuse=max(lightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#ifdef OVERLOADEDSHADOWVALUES\nshadowedOnlyLightDiffuseContribution=max(shadowedOnlyLightDiffuseContribution*surfaceAlbedoContribution+surfaceEmissiveColor+vAmbientColor,0.0)*surfaceAlbedo.rgb;\n#endif\n#endif\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nfinalDiffuse=mix(finalDiffuse,shadowedOnlyLightDiffuseContribution,(1.0-vOverloadedShadowIntensity.y));\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=lightSpecularContribution*surfaceReflectivityColor;\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+getLuminance(finalSpecular),0.,1.);\n#endif\n#ifdef RADIANCEOVERALPHA\nalpha=clamp(alpha+getLuminance(environmentRadiance),0.,1.);\n#endif\n\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+surfaceEmissiveColor*vLightingIntensity.y+refractance,alpha);\n#else\nvec4 finalColor=vec4(finalDiffuse*ambientColor*vLightingIntensity.x+surfaceAlbedo.rgb*environmentIrradiance+finalSpecular*vLightingIntensity.x+environmentRadiance+refractance,alpha);\n#endif\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\nfinalColor=max(finalColor,0.0);\n#ifdef CAMERATONEMAP\nfinalColor.rgb=toneMaps(finalColor.rgb);\n#endif\nfinalColor.rgb=toGammaSpace(finalColor.rgb);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef CAMERACONTRAST\nfinalColor=contrasts(finalColor);\n#endif\nfinalColor.rgb=clamp(finalColor.rgb,0.,1.);\n#ifdef CAMERACOLORGRADING\nfinalColor=colorGrades(finalColor);\n#endif\n#ifdef CAMERACOLORCURVES\nfinalColor.rgb=applyColorCurves(finalColor.rgb);\n#endif\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ngl_FragColor=finalColor;\n}","pbrVertexShader":"precision highp float;\n\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 ALBEDO\nvarying vec2 vAlbedoUV;\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nvarying vec2 vAmbientUV;\nuniform mat4 ambientMatrix;\nuniform vec3 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(REFLECTIVITY) || defined(METALLICWORKFLOW) \nvarying vec2 vReflectivityUV;\nuniform vec2 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef BUMP\nvarying vec2 vBumpUV;\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\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>[0..maxSimultaneousLights]\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 ALBEDO\nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*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(REFLECTIVITY) || defined(METALLICWORKFLOW) \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*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\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\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":"#ifndef FULLFLOAT\nvec4 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}\n#endif\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;\n#ifndef FULLFLOAT\ngl_FragColor=vec4(packHalf(moment1),packHalf(moment2));\n#else\ngl_FragColor=vec4(moment1,moment2,1.0,1.0);\n#endif\n#else\n#ifndef FULLFLOAT\ngl_FragColor=pack(depth);\n#else\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#endif\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":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\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;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\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#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvoid main()\n{\nfloat texelsize=1.0/outSize;\nfloat compareDepth=texture2D(depthSampler,vUV).r;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=texture2D(depthSampler,samplePos).r;\nfloat weight=(1.0/(0.0001+abs(compareDepth-sampleDepth)));\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n}\n#endif\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","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\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(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\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(GAUSSIAN_BLUR_H) || defined(GAUSSIAN_BLUR_V)\nuniform float blurOffsets[9];\nuniform float blurWeights[9];\nuniform float blurWidth;\nvoid main(void)\n{\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]*blurWidth,0.0))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(blurOffsets[i]*blurWidth,0.0))*blurWeights[i]);\n#else\ncolor+=(texture2D(textureSampler,vUV+vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\ncolor+=(texture2D(textureSampler,vUV-vec2(0.0,blurOffsets[i]*blurWidth))*blurWeights[i]);\n#endif\n}\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\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;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\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)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\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}"};
  54727. 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":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\nmat3 TBN=cotangent_frame(normalW*vBumpInfos.y,-viewDirectionW,vBumpUV);\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\nnormalW=perturbNormal(viewDirectionW,TBN,vBumpUV+uvOffset);\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;\n#ifdef INVERTNORMALMAPX\nmap.x=1.0-map.x;\n#endif\n#ifdef INVERTNORMALMAPY\nmap.y=1.0-map.y;\n#endif\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","colorCurves":"const vec3 HDTVRec709_RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvec3 applyColorCurves(vec3 original) {\nvec3 result=original;\n\n\n\nfloat luma=dot(result.rgb,HDTVRec709_RGBLuminanceCoefficients);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0,0.0),vec2(1.0,1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma,luma,luma),result.rgb,colorCurve.a);\nreturn result;\n}","colorCurvesDefinition":"uniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\nuniform vec4 vCameraColorCurveNegative;","colorGrading":"vec4 colorGrades(vec4 color) \n{ \n\nfloat sliceContinuous=color.z*vCameraColorGradingInfos.z;\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger; \n\nvec2 sliceUV=color.xy*vCameraColorGradingScaleOffset.xy+vCameraColorGradingScaleOffset.zw;\n\n\nsliceUV.x+=sliceInteger*vCameraColorGradingInfos.w;\nvec4 slice0Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nsliceUV.x+=vCameraColorGradingInfos.w;\nvec4 slice1Color=texture2D(cameraColorGrading2DSampler,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\ncolor.rgb=mix(color.rgb,result,vCameraColorGradingInfos.x);\nreturn color;\n}","colorGradingDefinition":"uniform sampler2D cameraColorGrading2DSampler;\nuniform vec4 vCameraColorGradingInfos;\nuniform vec4 vCameraColorGradingScaleOffset;","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","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX;\nuniform vec3 vSphericalYY;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 EnvironmentIrradiance(vec3 normal)\n{\n\n\n\nvec3 result =\nvSphericalX*normal.x +\nvSphericalY*normal.y +\nvSphericalZ*normal.z +\nvSphericalXX*normal.x*normal.x +\nvSphericalYY*normal.y*normal.y +\nvSphericalZZ*normal.z*normal.z +\nvSphericalYZ*normal.y*normal.z +\nvSphericalZX*normal.z*normal.x +\nvSphericalXY*normal.x*normal.y;\nreturn result.rgb;\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#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\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#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\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\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","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kPi=3.1415926535897932384626433832795;\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat Square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,vec3(0.2126,0.7152,0.0722)),0.,1.);\n}\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=Square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat getMipMapIndexFromAverageSlope(float maxMipLevel,float alpha)\n{\n\n\n\n\n\n\n\nfloat mip=kRougnhessToAlphaOffset+maxMipLevel+(maxMipLevel*kRougnhessToAlphaScale*log2(alpha));\nreturn clamp(mip,0.,maxMipLevel);\n}\nfloat getMipMapIndexFromAverageSlopeWithPMREM(float maxMipLevel,float alphaG)\n{\nfloat specularPower=clamp(2./alphaG-2.,0.000001,2048.);\n\nreturn clamp(- 0.5*log2(specularPower)+5.5,0.,maxMipLevel);\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=Square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(kPi*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 FresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 specularColor,vec3 reflectance90)\n{\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nvec3 fresnel=fresnelSchlickGGX(VdotH,specularColor,reflectance90);\nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nreturn fresnel*specTerm*kPi; \n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat diffuseFresnelTerm =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn diffuseFresnelTerm*NdotL;\n\n\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nfloat kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn vec3(pow(color.r,2.2),pow(color.g,2.2),pow(color.b,2.2));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn vec3(pow(color.r,1.0/2.2),pow(color.g,1.0/2.2),pow(color.b,1.0/2.2));\n}\n#ifdef CAMERATONEMAP\nvec3 toneMaps(vec3 color)\n{\ncolor=max(color,0.0);\n\ncolor.rgb=color.rgb*vCameraInfos.x;\nfloat tuning=1.5; \n\n\nvec3 tonemapped=1.0-exp2(-color.rgb*tuning); \ncolor.rgb=mix(color.rgb,tonemapped,1.0);\nreturn color;\n}\n#endif\n#ifdef CAMERACONTRAST\nvec4 contrasts(vec4 color)\n{\ncolor=clamp(color,0.0,1.0);\nvec3 resultHighContrast=color.rgb*color.rgb*(3.0-2.0*color.rgb);\nfloat contrast=vCameraInfos.y;\nif (contrast<1.0)\n{\n\ncolor.rgb=mix(vec3(0.5,0.5,0.5),color.rgb,contrast);\n}\nelse\n{\n\ncolor.rgb=mix(color.rgb,resultHighContrast,contrast-1.0);\n}\nreturn color;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.0001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float lightAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat cosHalfAngle=cos(lightAngle*0.5);\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=lightAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=max(0.00000000001,dot(vNormal,lightDirection));\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW-lightDirection.xyz);\nNdotL=max(0.00000000001,dot(vNormal,-lightDirection.xyz));\nfloat VdotH=clamp(dot(viewDirectionW,H),0.00000000001,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance90,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=max(0.00000000001,dot(vNormal,H));\nNdotL=max(0.00000000001,NdotL);\nfloat VdotH=clamp(0.00000000001,1.0,dot(viewDirectionW,H));\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,specularColor,reflectance90);\nresult.specular=specTerm;\n#endif\nreturn result;\n}","pbrLightFunctionsCall":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifndef SPECULARTERM\nvec3 vLightSpecular{X}=vec3(0.0);\n#endif\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,vLightData{X},vLightDirection{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightGround{X},roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,vLightData{X},vLightDiffuse{X}.rgb,vLightSpecular{X},vLightDiffuse{X}.a,roughness,NdotV,specularEnvironmentR90,NdotL);\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWVSM{X}\nnotShadowLevel=computeShadowWithVSM(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\n#ifdef SHADOWPCF{X}\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowWithPCFCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#else\nnotShadowLevel=computeShadowWithPCF(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.y,shadowsInfo{X}.z,shadowsInfo{X}.x);\n#endif\n#else\n#if defined(POINTLIGHT{X})\nnotShadowLevel=computeShadowCube(vLightData{X}.xyz,shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#else\nnotShadowLevel=computeShadow(vPositionFromLight{X},shadowSampler{X},shadowsInfo{X}.x,shadowsInfo{X}.z);\n#endif\n#endif\n#endif\n#else\nnotShadowLevel=1.;\n#endif\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\nlightDiffuseContribution+=lightmapColor*notShadowLevel;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nlightSpecularContribution+=info.specular*notShadowLevel*lightmapColor;\n#endif\n#endif\n#else\nlightDiffuseContribution+=info.diffuse*notShadowLevel;\n#ifdef OVERLOADEDSHADOWVALUES\nif (NdotL<0.000000000011)\n{\nnotShadowLevel=1.;\n}\nshadowedOnlyLightDiffuseContribution*=notShadowLevel;\n#endif\n#ifdef SPECULARTERM\nlightSpecularContribution+=info.specular*notShadowLevel;\n#endif\n#endif\n#endif","pbrShadowFunctions":"\n#ifdef SHADOWS\n#ifndef SHADOWFULLFLOAT\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#endif\nuniform vec2 depthValues;\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float bias)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y =-directionToLight.y;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\nif (depth>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\nif (depth.z>shadow)\n{\n#ifdef OVERLOADEDSHADOWVALUES\nreturn mix(1.0,darkness,vOverloadedShadowIntensity.x);\n#else\nreturn darkness;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,visibility+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,visibility+darkness);\n#endif\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\n#ifdef OVERLOADEDSHADOWVALUES\nreturn min(1.0,mix(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness,vOverloadedShadowIntensity.x));\n#else\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n#endif\n}\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\n#ifndef SHADOWFULLFLOAT\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#endif\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;\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight))+bias;\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\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}\n#ifndef SHADOWFULLFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv))+bias;\n#else\nfloat shadow=texture2D(shadowSampler,uv).x+bias;\n#endif\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;\n#ifndef SHADOWFULLFLOAT\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;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<biasedDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<biasedDepth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\n#ifndef SHADOWFULLFLOAT\n\nfloat unpackHalf(vec2 color)\n{\nreturn color.x+(color.y/255.0);\n}\n#endif\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);\n#ifndef SHADOWFULLFLOAT\nvec2 moments=vec2(unpackHalf(texel.xy),unpackHalf(texel.zw));\n#else\nvec2 moments=texel.xy;\n#endif\nreturn min(1.0,1.0-ChebychevInequality(moments,depth.z,bias)+darkness);\n}\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\n#endif\n#endif","shadowsVertexDeclaration":"#ifdef SHADOWS\n#if defined(SPOTLIGHT{X}) || defined(DIRLIGHT{X})\nuniform mat4 lightMatrix{X};\nvarying vec4 vPositionFromLight{X};\n#endif\n#endif\n"};
  54728. BABYLON.CollisionWorker="var BABYLON;!function(t){var e=function(t,e,o,i){return!(t.x>o.x+i)&&(!(o.x-i>e.x)&&(!(t.y>o.y+i)&&(!(o.y-i>e.y)&&(!(t.z>o.z+i)&&!(o.z-i>e.z)))))},o=function(){var t={root:0,found:!1};return function(e,o,i,s){t.root=0,t.found=!1;var r=o*o-4*e*i;if(r<0)return t;var n=Math.sqrt(r),c=(-o-n)/(2*e),h=(-o+n)/(2*e);if(c>h){var a=h;h=c,c=a}return c>0&&c<s?(t.root=c,t.found=!0,t):h>0&&h<s?(t.root=h,t.found=!0,t):t}}(),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!(n<0)&&(s.subtractToRef(e,this._tempVector3),t.Vector3.CrossToRef(this._tempVector2,this._tempVector3,this._tempVector4),n=t.Vector3.Dot(this._tempVector4,r),!(n<0)&&(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)&&!!e(s,r,this.basePointWorld,this.velocityWorldLength+c)},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||V<0)return;h<0&&(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 f=this.velocity.lengthSquared(),m=f;this.basePoint.subtractToRef(s,this._tempVector);var T=2*t.Vector3.Dot(this.velocity,this._tempVector),b=this._tempVector.lengthSquared()-1,y=o(m,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(m,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(m,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(m=g*-f+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(m,T,b,p),y.found){var D=(v*y.root-R)/g;D>=0&&D<=1&&(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),m=g*-f+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(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(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),m=g*-f+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(m,T,b,p),y.found&&(D=(v*y.root-R)/g,D>=0&&D<=1&&(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;c<s;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;c<a;++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;s<r;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;t<s;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;t<a;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=\"\";var o;!function(e){e[e.INIT=0]=\"INIT\",e[e.UPDATE=1]=\"UPDATE\",e[e.COLLIDE=2]=\"COLLIDE\"}(o=e.WorkerTaskType||(e.WorkerTaskType={}));var i;!function(e){e[e.SUCCESS=0]=\"SUCCESS\",e[e.UNKNOWN_ERROR=1]=\"UNKNOWN_ERROR\"}(i=e.WorkerReplyType||(e.WorkerReplyType={}));var 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}();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()||[])}},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,r){void 0===r&&(r=1.401298e-45);var n=t-i;return-r<=n&&n<=r},t.ToHex=function(t){var i=t.toString(16);return t<=15?(\"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,r){return void 0===i&&(i=0),void 0===r&&(r=1),Math.min(r,Math.max(i,t))},t}();t.MathTools=i;var r=function(){function r(t,i,r){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),this.r=t,this.g=i,this.b=r}return r.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\"}\"},r.prototype.getClassName=function(){return\"Color3\"},r.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.r,t[i+1]=this.g,t[i+2]=this.b,this},r.prototype.toColor4=function(t){return void 0===t&&(t=1),new n(this.r,this.g,this.b,t)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.toLuminance=function(){return.3*this.r+.59*this.g+.11*this.b},r.prototype.multiply=function(t){return new r(this.r*t.r,this.g*t.g,this.b*t.b)},r.prototype.multiplyToRef=function(t,i){return i.r=this.r*t.r,i.g=this.g*t.g,i.b=this.b*t.b,this},r.prototype.equals=function(t){return t&&this.r===t.r&&this.g===t.g&&this.b===t.b},r.prototype.equalsFloats=function(t,i,r){return this.r===t&&this.g===i&&this.b===r},r.prototype.scale=function(t){return new r(this.r*t,this.g*t,this.b*t)},r.prototype.scaleToRef=function(t,i){return i.r=this.r*t,i.g=this.g*t,i.b=this.b*t,this},r.prototype.add=function(t){return new r(this.r+t.r,this.g+t.g,this.b+t.b)},r.prototype.addToRef=function(t,i){return i.r=this.r+t.r,i.g=this.g+t.g,i.b=this.b+t.b,this},r.prototype.subtract=function(t){return new r(this.r-t.r,this.g-t.g,this.b-t.b)},r.prototype.subtractToRef=function(t,i){return i.r=this.r-t.r,i.g=this.g-t.g,i.b=this.b-t.b,this},r.prototype.clone=function(){return new r(this.r,this.g,this.b)},r.prototype.copyFrom=function(t){return this.r=t.r,this.g=t.g,this.b=t.b,this},r.prototype.copyFromFloats=function(t,i,r){return this.r=t,this.g=i,this.b=r,this},r.prototype.toHexString=function(){var t=255*this.r|0,r=255*this.g|0,n=255*this.b|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)},r.prototype.toLinearSpace=function(){var t=new r;return this.toLinearSpaceToRef(t),t},r.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},r.prototype.toGammaSpace=function(){var t=new r;return this.toGammaSpaceToRef(t),t},r.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},r.FromHexString=function(t){if(\"#\"!==t.substring(0,1)||7!==t.length)return new r(0,0,0);var i=parseInt(t.substring(1,3),16),n=parseInt(t.substring(3,5),16),o=parseInt(t.substring(5,7),16);return r.FromInts(i,n,o)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1],t[i+2])},r.FromInts=function(t,i,n){return new r(t/255,i/255,n/255)},r.Lerp=function(t,i,n){var o=t.r+(i.r-t.r)*n,e=t.g+(i.g-t.g)*n,s=t.b+(i.b-t.b)*n;return new r(o,e,s)},r.Red=function(){return new r(1,0,0)},r.Green=function(){return new r(0,1,0)},r.Blue=function(){return new r(0,0,1)},r.Black=function(){return new r(0,0,0)},r.White=function(){return new r(1,1,1)},r.Purple=function(){return new r(.5,0,.5)},r.Magenta=function(){return new r(1,0,1)},r.Yellow=function(){return new r(1,1,0)},r.Gray=function(){return new r(.5,.5,.5)},r.Random=function(){return new r(Math.random(),Math.random(),Math.random())},r}();t.Color3=r;var n=function(){function t(t,i,r,n){this.r=t,this.g=i,this.b=r,this.a=n}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.multiply=function(i){return new t(this.r*i.r,this.g*i.g,this.b*i.b,this.a*i.a)},t.prototype.multiplyToRef=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,i},t.prototype.toString=function(){return\"{R: \"+this.r+\" G:\"+this.g+\" B:\"+this.b+\" A:\"+this.a+\"}\"},t.prototype.getClassName=function(){return\"Color4\"},t.prototype.getHashCode=function(){var t=this.r||0;return t=397*t^(this.g||0),t=397*t^(this.b||0),t=397*t^(this.a||0)},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,r=255*this.g|0,n=255*this.b|0,o=255*this.a|0;return\"#\"+i.ToHex(t)+i.ToHex(r)+i.ToHex(n)+i.ToHex(o)},t.FromHexString=function(i){if(\"#\"!==i.substring(0,1)||9!==i.length)return new t(0,0,0,0);var r=parseInt(i.substring(1,3),16),n=parseInt(i.substring(3,5),16),o=parseInt(i.substring(5,7),16),e=parseInt(i.substring(7,9),16);return t.FromInts(r,n,o,e)},t.Lerp=function(i,r,n){var o=new t(0,0,0,0);return t.LerpToRef(i,r,n,o),o},t.LerpToRef=function(t,i,r,n){n.r=t.r+(i.r-t.r)*r,n.g=t.g+(i.g-t.g)*r,n.b=t.b+(i.b-t.b)*r,n.a=t.a+(i.a-t.a)*r},t.FromArray=function(i,r){return void 0===r&&(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.FromInts=function(i,r,n,o){return new t(i/255,r/255,n/255,o/255)},t.CheckColors4=function(t,i){if(t.length===3*i){for(var r=[],n=0;n<t.length;n+=3){var o=n/3*4;r[o]=t[n],r[o+1]=t[n+1],r[o+2]=t[n+2],r[o+3]=1}return r}return t},t}();t.Color4=n;var o=function(){function r(t,i){this.x=t,this.y=i}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\"}\"},r.prototype.getClassName=function(){return\"Vector2\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0)},r.prototype.toArray=function(t,i){return void 0===i&&(i=0),t[i]=this.x,t[i+1]=this.y,this},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this},r.prototype.copyFromFloats=function(t,i){return this.x=t,this.y=i,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.addToRef=function(t,i){return i.x=this.x+t.x,i.y=this.y+t.y,this},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this},r.prototype.addVector3=function(t){return new r(this.x+t.x,this.y+t.y)},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y)},r.prototype.subtractToRef=function(t,i){return i.x=this.x-t.x,i.y=this.y-t.y,this},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y)},r.prototype.multiplyToRef=function(t,i){return i.x=this.x*t.x,i.y=this.y*t.y,this},r.prototype.multiplyByFloats=function(t,i){return new r(this.x*t,this.y*i)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y)},r.prototype.divideToRef=function(t,i){return i.x=this.x/t.x,i.y=this.y/t.y,this},r.prototype.negate=function(){return new r((-this.x),(-this.y))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t)},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y},r.prototype.normalize=function(){var t=this.length();if(0===t)return this;var i=1/t;return this.x*=i,this.y*=i,this},r.prototype.clone=function(){return new r(this.x,this.y)},r.Zero=function(){return new r(0,0)},r.FromArray=function(t,i){return void 0===i&&(i=0),new r(t[i],t[i+1])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h);return new r(a,u)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;return e=e>n.y?n.y:e,e=e<i.y?i.y:e,new r(o,e)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y;return new r(c,p)},r.Lerp=function(t,i,n){var o=t.x+(i.x-t.x)*n,e=t.y+(i.y-t.y)*n;return new r(o,e)},r.Dot=function(t,i){return t.x*i.x+t.y*i.y},r.Normalize=function(t){var i=t.clone();return i.normalize(),i},r.Minimize=function(t,i){var n=t.x<i.x?t.x:i.x,o=t.y<i.y?t.y:i.y;return new r(n,o)},r.Maximize=function(t,i){var n=t.x>i.x?t.x:i.x,o=t.y>i.y?t.y:i.y;return new r(n,o)},r.Transform=function(t,i){var n=r.Zero();return r.TransformToRef(t,i,n),n},r.TransformToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+i.m[12],o=t.x*i.m[1]+t.y*i.m[5]+i.m[13];r.x=n,r.y=o},r.PointInTriangle=function(t,i,r,n){var o=.5*(-r.y*n.x+i.y*(-r.x+n.x)+i.x*(r.y-n.y)+r.x*n.y),e=o<0?-1:1,s=(i.y*n.x-i.x*n.y+(n.y-i.y)*t.x+(i.x-n.x)*t.y)*e,h=(i.x*r.y-i.y*r.x+(i.y-r.y)*t.x+(r.x-i.x)*t.y)*e;return s>0&&h>0&&s+h<2*o*e},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y;return r*r+n*n},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.DistanceOfPointFromSegment=function(t,i,n){var o=r.DistanceSquared(i,n);if(0===o)return r.Distance(t,i);var e=n.subtract(i),s=Math.max(0,Math.min(1,r.Dot(t.subtract(i),e)/o)),h=i.add(e.multiplyByFloats(s,s));return r.Distance(t,h)},r}();t.Vector2=o;var e=function(){function r(t,i,r){this.x=t,this.y=i,this.z=r}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\"}\"},r.prototype.getClassName=function(){return\"Vector3\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.toQuaternion=function(){var t=new a(0,0,0,1),i=Math.cos(.5*(this.x+this.z)),r=Math.sin(.5*(this.x+this.z)),n=Math.cos(.5*(this.z-this.x)),o=Math.sin(.5*(this.z-this.x)),e=Math.cos(.5*this.y),s=Math.sin(.5*this.y);return t.x=n*s,t.y=-o*s,t.z=r*e,t.w=i*e,t},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z)},r.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},r.prototype.subtractFromFloats=function(t,i,n){return new r(this.x-t,this.y-i,this.z-n)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n){return n.x=this.x-t,n.y=this.y-i,n.z=this.z-r,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t)},r.prototype.scaleToRef=function(t,i){i.x=this.x*t,i.y=this.y*t,i.z=this.z*t},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)},r.prototype.equalsToFloats=function(t,i,r){return this.x===t&&this.y===i&&this.z===r},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z)},r.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},r.prototype.multiplyByFloats=function(t,i,n){return new r(this.x*t,this.y*i,this.z*n)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z},r.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},r.prototype.clone=function(){return new r(this.x,this.y,this.z)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this},r.prototype.copyFromFloats=function(t,i,r){return this.x=t,this.y=i,this.z=r,this},r.GetClipFactor=function(t,i,n,o){var e=r.Dot(t,n)-o,s=r.Dot(i,n)-o,h=e/(e-s);return h},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromFloatArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2]},r.FromFloatsToRef=function(t,i,r,n){n.x=t,n.y=i,n.z=r},r.Zero=function(){return new r(0,0,0)},r.Up=function(){return new r(0,1,0)},r.Forward=function(){return new r(0,0,1)},r.Right=function(){return new r(1,0,0)},r.Left=function(){return new r((-1),0,0)},r.TransformCoordinates=function(t,i){var n=r.Zero();return r.TransformCoordinatesToRef(t,i,n),n},r.TransformCoordinatesToRef=function(t,i,r){var n=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],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10]+i.m[14],s=t.x*i.m[3]+t.y*i.m[7]+t.z*i.m[11]+i.m[15];r.x=n/s,r.y=o/s,r.z=e/s},r.TransformCoordinatesFromFloatsToRef=function(t,i,r,n,o){var e=t*n.m[0]+i*n.m[4]+r*n.m[8]+n.m[12],s=t*n.m[1]+i*n.m[5]+r*n.m[9]+n.m[13],h=t*n.m[2]+i*n.m[6]+r*n.m[10]+n.m[14],a=t*n.m[3]+i*n.m[7]+r*n.m[11]+n.m[15];o.x=e/a,o.y=s/a,o.z=h/a},r.TransformNormal=function(t,i){var n=r.Zero();return r.TransformNormalToRef(t,i,n),n},r.TransformNormalToRef=function(t,i,r){var n=t.x*i.m[0]+t.y*i.m[4]+t.z*i.m[8],o=t.x*i.m[1]+t.y*i.m[5]+t.z*i.m[9],e=t.x*i.m[2]+t.y*i.m[6]+t.z*i.m[10];r.x=n,r.y=o,r.z=e},r.TransformNormalFromFloatsToRef=function(t,i,r,n,o){o.x=t*n.m[0]+i*n.m[4]+r*n.m[8],o.y=t*n.m[1]+i*n.m[5]+r*n.m[9],o.z=t*n.m[2]+i*n.m[6]+r*n.m[10]},r.CatmullRom=function(t,i,n,o,e){var s=e*e,h=e*s,a=.5*(2*i.x+(-t.x+n.x)*e+(2*t.x-5*i.x+4*n.x-o.x)*s+(-t.x+3*i.x-3*n.x+o.x)*h),u=.5*(2*i.y+(-t.y+n.y)*e+(2*t.y-5*i.y+4*n.y-o.y)*s+(-t.y+3*i.y-3*n.y+o.y)*h),m=.5*(2*i.z+(-t.z+n.z)*e+(2*t.z-5*i.z+4*n.z-o.z)*s+(-t.z+3*i.z-3*n.z+o.z)*h);return new r(a,u,m)},r.Clamp=function(t,i,n){var o=t.x;o=o>n.x?n.x:o,o=o<i.x?i.x:o;var e=t.y;e=e>n.y?n.y:e,e=e<i.y?i.y:e;var s=t.z;return s=s>n.z?n.z:s,s=s<i.z?i.z:s,new r(o,e,s)},r.Hermite=function(t,i,n,o,e){var s=e*e,h=e*s,a=2*h-3*s+1,u=-2*h+3*s,m=h-2*s+e,y=h-s,c=t.x*a+n.x*u+i.x*m+o.x*y,p=t.y*a+n.y*u+i.y*m+o.y*y,f=t.z*a+n.z*u+i.z*m+o.z*y;return new r(c,p,f)},r.Lerp=function(t,i,n){var o=new r(0,0,0);return r.LerpToRef(t,i,n,o),o},r.LerpToRef=function(t,i,r,n){n.x=t.x+(i.x-t.x)*r,n.y=t.y+(i.y-t.y)*r,n.z=t.z+(i.z-t.z)*r},r.Dot=function(t,i){return t.x*i.x+t.y*i.y+t.z*i.z},r.Cross=function(t,i){var n=r.Zero();return r.CrossToRef(t,i,n),n},r.CrossToRef=function(t,i,r){A.Vector3[0].x=t.y*i.z-t.z*i.y,A.Vector3[0].y=t.z*i.x-t.x*i.z,A.Vector3[0].z=t.x*i.y-t.y*i.x,r.copyFrom(A.Vector3[0])},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Project=function(t,i,n,o){var e=o.width,s=o.height,h=o.x,a=o.y,m=r._viewportMatrixCache?r._viewportMatrixCache:r._viewportMatrixCache=new u;u.FromValuesToRef(e/2,0,0,0,0,-s/2,0,0,0,0,1,0,h+e/2,s/2+a,0,1,m);var y=r._matrixCache?r._matrixCache:r._matrixCache=new u;return i.multiplyToRef(n,y),y.multiplyToRef(m,y),r.TransformCoordinates(t,y)},r.UnprojectFromTransform=function(t,n,o,e,s){var h=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,h),h.invert(),t.x=t.x/n*2-1,t.y=-(t.y/o*2-1);var a=r.TransformCoordinates(t,h),m=t.x*h.m[3]+t.y*h.m[7]+t.z*h.m[11]+h.m[15];return i.WithinEpsilon(m,1)&&(a=a.scale(1/m)),a},r.Unproject=function(t,n,o,e,s,h){var a=r._matrixCache?r._matrixCache:r._matrixCache=new u;e.multiplyToRef(s,a),a.multiplyToRef(h,a),a.invert();var m=new r(t.x/n*2-1,(-(t.y/o*2-1)),2*t.z-1),y=r.TransformCoordinates(m,a),c=m.x*a.m[3]+m.y*a.m[7]+m.z*a.m[11]+a.m[15];return i.WithinEpsilon(c,1)&&(y=y.scale(1/c)),y},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z;return r*r+n*n+o*o},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r.RotationFromAxis=function(t,i,n){var o=r.Zero();return r.RotationFromAxisToRef(t,i,n,o),o},r.RotationFromAxisToRef=function(n,o,e,s){var h=n.normalize(),a=e.normalize(),u=f.X,m=f.Y,y=0,c=0,p=0,x=0,l=0,z=0,w=0,v=-1,d=0,g=A.Vector3[0],R=0,T=A.Vector3[1];i.WithinEpsilon(a.z,0,t.Epsilon)?z=1:i.WithinEpsilon(a.x,0,t.Epsilon)?x=1:(w=a.z/a.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),T.x=x,T.y=l,T.z=z,T.normalize(),r.CrossToRef(h,T,g),g.normalize(),r.Dot(a,g)<0&&(v=1),R=r.Dot(h,T),R=Math.min(1,Math.max(-1,R)),p=Math.acos(R)*v,r.Dot(T,u)<0&&(p=Math.PI+p,T=T.scaleInPlace(-1),d++);var _=A.Vector3[2],M=A.Vector3[3];x=0,l=0,z=0,v=-1,i.WithinEpsilon(a.z,0,t.Epsilon)?x=1:(w=T.z/T.x,x=-w*Math.sqrt(1/(1+w*w)),z=Math.sqrt(1/(1+w*w))),_.x=x,_.y=l,_.z=z,_.normalize(),r.CrossToRef(_,T,M),M.normalize(),r.CrossToRef(a,_,g),g.normalize(),r.Dot(T,g)<0&&(v=1),R=r.Dot(a,_),R=Math.min(1,Math.max(-1,R)),c=Math.acos(R)*v,r.Dot(M,m)<0&&(c=Math.PI+c,d++),v=-1,r.CrossToRef(u,T,g),g.normalize(),r.Dot(g,m)<0&&(v=1),R=r.Dot(T,u),R=Math.min(1,Math.max(-1,R)),y=-Math.acos(R)*v,R<0&&d<2&&(y=Math.PI+y),s.x=c,s.y=y,s.z=p},r}();t.Vector3=e;var s=function(){function r(t,i,r,n){this.x=t,this.y=i,this.z=r,this.w=n}return r.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},r.prototype.getClassName=function(){return\"Vector4\"},r.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},r.prototype.asArray=function(){var t=[];return this.toArray(t,0),t},r.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},r.prototype.addInPlace=function(t){return this.x+=t.x,this.y+=t.y,this.z+=t.z,this.w+=t.w,this},r.prototype.add=function(t){return new r(this.x+t.x,this.y+t.y,this.z+t.z,this.w+t.w)},r.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},r.prototype.subtractInPlace=function(t){return this.x-=t.x,this.y-=t.y,this.z-=t.z,this.w-=t.w,this},r.prototype.subtract=function(t){return new r(this.x-t.x,this.y-t.y,this.z-t.z,this.w-t.w)},r.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},r.prototype.subtractFromFloats=function(t,i,n,o){return new r(this.x-t,this.y-i,this.z-n,this.w-o)},r.prototype.subtractFromFloatsToRef=function(t,i,r,n,o){return o.x=this.x-t,o.y=this.y-i,o.z=this.z-r,o.w=this.w-n,this},r.prototype.negate=function(){return new r((-this.x),(-this.y),(-this.z),(-this.w))},r.prototype.scaleInPlace=function(t){return this.x*=t,this.y*=t,this.z*=t,this.w*=t,this},r.prototype.scale=function(t){return new r(this.x*t,this.y*t,this.z*t,this.w*t)},r.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},r.prototype.equals=function(t){return t&&this.x===t.x&&this.y===t.y&&this.z===t.z&&this.w===t.w},r.prototype.equalsWithEpsilon=function(r,n){return void 0===n&&(n=t.Epsilon),r&&i.WithinEpsilon(this.x,r.x,n)&&i.WithinEpsilon(this.y,r.y,n)&&i.WithinEpsilon(this.z,r.z,n)&&i.WithinEpsilon(this.w,r.w,n)},r.prototype.equalsToFloats=function(t,i,r,n){return this.x===t&&this.y===i&&this.z===r&&this.w===n},r.prototype.multiplyInPlace=function(t){return this.x*=t.x,this.y*=t.y,this.z*=t.z,this.w*=t.w,this},r.prototype.multiply=function(t){return new r(this.x*t.x,this.y*t.y,this.z*t.z,this.w*t.w)},r.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},r.prototype.multiplyByFloats=function(t,i,n,o){return new r(this.x*t,this.y*i,this.z*n,this.w*o)},r.prototype.divide=function(t){return new r(this.x/t.x,this.y/t.y,this.z/t.z,this.w/t.w)},r.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},r.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},r.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},r.prototype.length=function(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)},r.prototype.lengthSquared=function(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w},r.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},r.prototype.toVector3=function(){return new e(this.x,this.y,this.z)},r.prototype.clone=function(){return new r(this.x,this.y,this.z,this.w)},r.prototype.copyFrom=function(t){return this.x=t.x,this.y=t.y,this.z=t.z,this.w=t.w,this},r.prototype.copyFromFloats=function(t,i,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,this},r.FromArray=function(t,i){return i||(i=0),new r(t[i],t[i+1],t[i+2],t[i+3])},r.FromArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatArrayToRef=function(t,i,r){r.x=t[i],r.y=t[i+1],r.z=t[i+2],r.w=t[i+3]},r.FromFloatsToRef=function(t,i,r,n,o){o.x=t,o.y=i,o.z=r,o.w=n},r.Zero=function(){return new r(0,0,0,0)},r.Normalize=function(t){var i=r.Zero();return r.NormalizeToRef(t,i),i},r.NormalizeToRef=function(t,i){i.copyFrom(t),i.normalize()},r.Minimize=function(t,i){var r=t.clone();return r.MinimizeInPlace(i),r},r.Maximize=function(t,i){var r=t.clone();return r.MaximizeInPlace(i),r},r.Distance=function(t,i){return Math.sqrt(r.DistanceSquared(t,i))},r.DistanceSquared=function(t,i){var r=t.x-i.x,n=t.y-i.y,o=t.z-i.z,e=t.w-i.w;return r*r+n*n+o*o+e*e},r.Center=function(t,i){var r=t.add(i);return r.scaleInPlace(.5),r},r}();t.Vector4=s;var h=function(){function t(t,i){this.width=t,this.height=i}return t.prototype.toString=function(){return\"{W: \"+this.width+\", H: \"+this.height+\"}\"},t.prototype.getClassName=function(){return\"Size\"},t.prototype.getHashCode=function(){var t=this.width||0;return t=397*t^(this.height||0)},t.prototype.copyFrom=function(t){this.width=t.width,this.height=t.height},t.prototype.copyFromFloats=function(t,i){this.width=t,this.height=i},t.prototype.multiplyByFloats=function(i,r){return new t(this.width*i,this.height*r)},t.prototype.clone=function(){return new t(this.width,this.height)},t.prototype.equals=function(t){return!!t&&(this.width===t.width&&this.height===t.height)},Object.defineProperty(t.prototype,\"surface\",{get:function(){return this.width*this.height},enumerable:!0,configurable:!0}),t.Zero=function(){return new t(0,0)},t.prototype.add=function(i){var r=new t(this.width+i.width,this.height+i.height);return r},t.prototype.substract=function(i){var r=new t(this.width-i.width,this.height-i.height);return r},t.Lerp=function(i,r,n){var o=i.width+(r.width-i.width)*n,e=i.height+(r.height-i.height)*n;return new t(o,e)},t}();t.Size=h;var a=function(){function t(t,i,r,n){void 0===t&&(t=0),void 0===i&&(i=0),void 0===r&&(r=0),void 0===n&&(n=1),this.x=t,this.y=i,this.z=r,this.w=n}return t.prototype.toString=function(){return\"{X: \"+this.x+\" Y:\"+this.y+\" Z:\"+this.z+\" W:\"+this.w+\"}\"},t.prototype.getClassName=function(){return\"Quaternion\"},t.prototype.getHashCode=function(){var t=this.x||0;return t=397*t^(this.y||0),t=397*t^(this.z||0),t=397*t^(this.w||0)},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,r,n){return this.x=t,this.y=i,this.z=r,this.w=n,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 r=new t(0,0,0,1);return this.multiplyToRef(i,r),r},t.prototype.multiplyToRef=function(t,i){var r=this.x*t.w+this.y*t.z-this.z*t.y+this.w*t.x,n=-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,e=-this.x*t.x-this.y*t.y-this.z*t.z+this.w*t.w;return i.copyFromFloats(r,n,o,e),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=e.Zero();return this.toEulerAnglesToRef(i,t),i},t.prototype.toEulerAnglesToRef=function(t,i){void 0===i&&(i=\"YZX\");var r=this.z,n=this.x,o=this.y,e=this.w,s=e*e,h=r*r,a=n*n,u=o*o,m=o*r-n*e,y=.4999999;return m<-y?(t.y=2*Math.atan2(o,e),t.x=Math.PI/2,t.z=0):m>y?(t.y=2*Math.atan2(o,e),t.x=-Math.PI/2,t.z=0):(t.z=Math.atan2(2*(n*o+r*e),-h-a+u+s),t.x=Math.asin(-2*(r*o-n*e)),t.y=Math.atan2(2*(r*n+o*e),h-a-u+s)),this},t.prototype.toRotationMatrix=function(t){var i=this.x*this.x,r=this.y*this.y,n=this.z*this.z,o=this.x*this.y,e=this.z*this.w,s=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*(r+n),t.m[1]=2*(o+e),t.m[2]=2*(s-h),t.m[3]=0,t.m[4]=2*(o-e),t.m[5]=1-2*(n+i),t.m[6]=2*(a+u),t.m[7]=0,t.m[8]=2*(s+h),t.m[9]=2*(a-u),t.m[10]=1-2*(r+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 r=new t;return t.FromRotationMatrixToRef(i,r),r},t.FromRotationMatrixToRef=function(t,i){var r,n=t.m,o=n[0],e=n[4],s=n[8],h=n[1],a=n[5],u=n[9],m=n[2],y=n[6],c=n[10],p=o+a+c;p>0?(r=.5/Math.sqrt(p+1),i.w=.25/r,i.x=(y-u)*r,i.y=(s-m)*r,i.z=(h-e)*r):o>a&&o>c?(r=2*Math.sqrt(1+o-a-c),i.w=(y-u)/r,i.x=.25*r,i.y=(e+h)/r,i.z=(s+m)/r):a>c?(r=2*Math.sqrt(1+a-o-c),i.w=(s-m)/r,i.x=(e+h)/r,i.y=.25*r,i.z=(u+y)/r):(r=2*Math.sqrt(1+c-o-a),i.w=(h-e)/r,i.x=(s+m)/r,i.y=(u+y)/r,i.z=.25*r)},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,r){return t.RotationAxisToRef(i,r,new t)},t.RotationAxisToRef=function(t,i,r){var n=Math.sin(i/2);return t.normalize(),r.w=Math.cos(i/2),r.x=t.x*n,r.y=t.y*n,r.z=t.z*n,r},t.FromArray=function(i,r){return r||(r=0),new t(i[r],i[r+1],i[r+2],i[r+3])},t.RotationYawPitchRoll=function(i,r,n){var o=new t;return t.RotationYawPitchRollToRef(i,r,n,o),o},t.RotationYawPitchRollToRef=function(t,i,r,n){var o=.5*r,e=.5*i,s=.5*t,h=Math.sin(o),a=Math.cos(o),u=Math.sin(e),m=Math.cos(e),y=Math.sin(s),c=Math.cos(s);n.x=c*u*a+y*m*h,n.y=y*m*a-c*u*h,n.z=c*m*h-y*u*a,n.w=c*m*a+y*u*h},t.RotationAlphaBetaGamma=function(i,r,n){var o=new t;return t.RotationAlphaBetaGammaToRef(i,r,n,o),o},t.RotationAlphaBetaGammaToRef=function(t,i,r,n){var o=.5*(r+t),e=.5*(r-t),s=.5*i;n.x=Math.cos(e)*Math.sin(s),n.y=Math.sin(e)*Math.sin(s),n.z=Math.sin(o)*Math.cos(s),n.w=Math.cos(o)*Math.cos(s)},t.Slerp=function(i,r,n){var o=t.Identity();return t.SlerpToRef(i,r,n,o),o},t.SlerpToRef=function(t,i,r,n){var o,e,s=r,h=t.x*i.x+t.y*i.y+t.z*i.z+t.w*i.w,a=!1;if(h<0&&(a=!0,h=-h),h>.999999)e=1-s,o=a?-s:s;else{var u=Math.acos(h),m=1/Math.sin(u);e=Math.sin((1-s)*u)*m,o=a?-Math.sin(s*u)*m:Math.sin(s*u)*m}n.x=e*t.x+o*i.x,n.y=e*t.y+o*i.y,n.z=e*t.z+o*i.z,n.w=e*t.w+o*i.w},t}();t.Quaternion=a;var u=function(){function r(){this.m=new Float32Array(16)}return r.prototype.isIdentity=function(){return 1===this.m[0]&&1===this.m[5]&&1===this.m[10]&&1===this.m[15]&&(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])},r.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],r=this.m[9]*this.m[14]-this.m[10]*this.m[13],n=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],e=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]*r)-this.m[1]*(this.m[4]*t-this.m[6]*n+this.m[7]*o)+this.m[2]*(this.m[4]*i-this.m[5]*n+this.m[7]*e)-this.m[3]*(this.m[4]*r-this.m[5]*o+this.m[6]*e)},r.prototype.toArray=function(){return this.m},r.prototype.asArray=function(){return this.toArray()},r.prototype.invert=function(){return this.invertToRef(this),this},r.prototype.reset=function(){for(var t=0;t<16;t++)this.m[t]=0;return this},r.prototype.add=function(t){var i=new r;return this.addToRef(t,i),i},r.prototype.addToRef=function(t,i){for(var r=0;r<16;r++)i.m[r]=this.m[r]+t.m[r];return this},r.prototype.addToSelf=function(t){for(var i=0;i<16;i++)this.m[i]+=t.m[i];return this},r.prototype.invertToRef=function(t){var i=this.m[0],r=this.m[1],n=this.m[2],o=this.m[3],e=this.m[4],s=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],x=this.m[14],l=this.m[15],z=y*l-c*x,w=m*l-c*f,v=m*x-y*f,d=u*l-c*p,g=u*x-y*p,R=u*f-m*p,T=s*z-h*w+a*v,_=-(e*z-h*d+a*g),M=e*w-s*d+a*R,A=-(e*v-s*g+h*R),F=1/(i*T+r*_+n*M+o*A),b=h*l-a*x,L=s*l-a*f,C=s*x-h*f,P=e*l-a*p,Z=e*x-h*p,S=e*f-s*p,I=h*c-a*y,H=s*c-a*m,V=s*y-h*m,q=e*c-a*u,D=e*y-h*u,N=e*m-s*u;return t.m[0]=T*F,t.m[4]=_*F,t.m[8]=M*F,t.m[12]=A*F,t.m[1]=-(r*z-n*w+o*v)*F,t.m[5]=(i*z-n*d+o*g)*F,t.m[9]=-(i*w-r*d+o*R)*F,t.m[13]=(i*v-r*g+n*R)*F,t.m[2]=(r*b-n*L+o*C)*F,t.m[6]=-(i*b-n*P+o*Z)*F,t.m[10]=(i*L-r*P+o*S)*F,t.m[14]=-(i*C-r*Z+n*S)*F,t.m[3]=-(r*I-n*H+o*V)*F,t.m[7]=(i*I-n*q+o*D)*F,t.m[11]=-(i*H-r*q+o*N)*F,t.m[15]=(i*V-r*D+n*N)*F,this},r.prototype.setTranslation=function(t){return this.m[12]=t.x,this.m[13]=t.y,this.m[14]=t.z,this},r.prototype.getTranslation=function(){return new e(this.m[12],this.m[13],this.m[14])},r.prototype.multiply=function(t){\nvar i=new r;return this.multiplyToRef(t,i),i},r.prototype.copyFrom=function(t){for(var i=0;i<16;i++)this.m[i]=t.m[i];return this},r.prototype.copyToArray=function(t,i){void 0===i&&(i=0);for(var r=0;r<16;r++)t[i+r]=this.m[r];return this},r.prototype.multiplyToRef=function(t,i){return this.multiplyToArray(t,i.m,0),this},r.prototype.multiplyToArray=function(t,i,r){var n=this.m[0],o=this.m[1],e=this.m[2],s=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],x=this.m[12],l=this.m[13],z=this.m[14],w=this.m[15],v=t.m[0],d=t.m[1],g=t.m[2],R=t.m[3],T=t.m[4],_=t.m[5],M=t.m[6],A=t.m[7],F=t.m[8],b=t.m[9],L=t.m[10],C=t.m[11],P=t.m[12],Z=t.m[13],S=t.m[14],I=t.m[15];return i[r]=n*v+o*T+e*F+s*P,i[r+1]=n*d+o*_+e*b+s*Z,i[r+2]=n*g+o*M+e*L+s*S,i[r+3]=n*R+o*A+e*C+s*I,i[r+4]=h*v+a*T+u*F+m*P,i[r+5]=h*d+a*_+u*b+m*Z,i[r+6]=h*g+a*M+u*L+m*S,i[r+7]=h*R+a*A+u*C+m*I,i[r+8]=y*v+c*T+p*F+f*P,i[r+9]=y*d+c*_+p*b+f*Z,i[r+10]=y*g+c*M+p*L+f*S,i[r+11]=y*R+c*A+p*C+f*I,i[r+12]=x*v+l*T+z*F+w*P,i[r+13]=x*d+l*_+z*b+w*Z,i[r+14]=x*g+l*M+z*L+w*S,i[r+15]=x*R+l*A+z*C+w*I,this},r.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]},r.prototype.clone=function(){return r.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])},r.prototype.getClassName=function(){return\"Matrix\"},r.prototype.getHashCode=function(){for(var t=this.m[0]||0,i=1;i<16;i++)t=397*t^(this.m[i]||0);return t},r.prototype.decompose=function(t,n,o){o.x=this.m[12],o.y=this.m[13],o.z=this.m[14];var e=i.Sign(this.m[0]*this.m[1]*this.m[2]*this.m[3])<0?-1:1,s=i.Sign(this.m[4]*this.m[5]*this.m[6]*this.m[7])<0?-1:1,h=i.Sign(this.m[8]*this.m[9]*this.m[10]*this.m[11])<0?-1:1;return t.x=e*Math.sqrt(this.m[0]*this.m[0]+this.m[1]*this.m[1]+this.m[2]*this.m[2]),t.y=s*Math.sqrt(this.m[4]*this.m[4]+this.m[5]*this.m[5]+this.m[6]*this.m[6]),t.z=h*Math.sqrt(this.m[8]*this.m[8]+this.m[9]*this.m[9]+this.m[10]*this.m[10]),0===t.x||0===t.y||0===t.z?(n.x=0,n.y=0,n.z=0,n.w=1,!1):(r.FromValuesToRef(this.m[0]/t.x,this.m[1]/t.x,this.m[2]/t.x,0,this.m[4]/t.y,this.m[5]/t.y,this.m[6]/t.y,0,this.m[8]/t.z,this.m[9]/t.z,this.m[10]/t.z,0,0,0,0,1,A.Matrix[0]),a.FromRotationMatrixToRef(A.Matrix[0],n),!0)},r.prototype.getRotationMatrix=function(){var t=r.Identity();return this.getRotationMatrixToRef(t),t},r.prototype.getRotationMatrixToRef=function(t){var i=this.m,n=i[0]*i[1]*i[2]*i[3]<0?-1:1,o=i[4]*i[5]*i[6]*i[7]<0?-1:1,e=i[8]*i[9]*i[10]*i[11]<0?-1:1,s=n*Math.sqrt(i[0]*i[0]+i[1]*i[1]+i[2]*i[2]),h=o*Math.sqrt(i[4]*i[4]+i[5]*i[5]+i[6]*i[6]),a=e*Math.sqrt(i[8]*i[8]+i[9]*i[9]+i[10]*i[10]);r.FromValuesToRef(i[0]/s,i[1]/s,i[2]/s,0,i[4]/h,i[5]/h,i[6]/h,0,i[8]/a,i[9]/a,i[10]/a,0,0,0,0,1,t)},r.FromArray=function(t,i){var n=new r;return i||(i=0),r.FromArrayToRef(t,i,n),n},r.FromArrayToRef=function(t,i,r){for(var n=0;n<16;n++)r.m[n]=t[n+i]},r.FromFloat32ArrayToRefScaled=function(t,i,r,n){for(var o=0;o<16;o++)n.m[o]=t[o+i]*r},r.FromValuesToRef=function(t,i,r,n,o,e,s,h,a,u,m,y,c,p,f,x,l){l.m[0]=t,l.m[1]=i,l.m[2]=r,l.m[3]=n,l.m[4]=o,l.m[5]=e,l.m[6]=s,l.m[7]=h,l.m[8]=a,l.m[9]=u,l.m[10]=m,l.m[11]=y,l.m[12]=c,l.m[13]=p,l.m[14]=f,l.m[15]=x},r.prototype.getRow=function(t){if(t<0||t>3)return null;var i=4*t;return new s(this.m[i+0],this.m[i+1],this.m[i+2],this.m[i+3])},r.prototype.setRow=function(t,i){if(t<0||t>3)return this;var r=4*t;return this.m[r+0]=i.x,this.m[r+1]=i.y,this.m[r+2]=i.z,this.m[r+3]=i.w,this},r.FromValues=function(t,i,n,o,e,s,h,a,u,m,y,c,p,f,x,l){var z=new r;return z.m[0]=t,z.m[1]=i,z.m[2]=n,z.m[3]=o,z.m[4]=e,z.m[5]=s,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]=x,z.m[15]=l,z},r.Compose=function(t,i,n){var o=r.FromValues(t.x,0,0,0,0,t.y,0,0,0,0,t.z,0,0,0,0,1),e=r.Identity();return i.toRotationMatrix(e),o=o.multiply(e),o.setTranslation(n),o},r.Identity=function(){return r.FromValues(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1)},r.IdentityToRef=function(t){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1,t)},r.Zero=function(){return r.FromValues(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)},r.RotationX=function(t){var i=new r;return r.RotationXToRef(t,i),i},r.Invert=function(t){var i=new r;return t.invertToRef(i),i},r.RotationXToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[0]=1,i.m[15]=1,i.m[5]=n,i.m[10]=n,i.m[9]=-r,i.m[6]=r,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},r.RotationY=function(t){var i=new r;return r.RotationYToRef(t,i),i},r.RotationYToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[5]=1,i.m[15]=1,i.m[0]=n,i.m[2]=-r,i.m[8]=r,i.m[10]=n,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},r.RotationZ=function(t){var i=new r;return r.RotationZToRef(t,i),i},r.RotationZToRef=function(t,i){var r=Math.sin(t),n=Math.cos(t);i.m[10]=1,i.m[15]=1,i.m[0]=n,i.m[1]=r,i.m[4]=-r,i.m[5]=n,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},r.RotationAxis=function(t,i){var n=r.Zero();return r.RotationAxisToRef(t,i,n),n},r.RotationAxisToRef=function(t,i,r){var n=Math.sin(-i),o=Math.cos(-i),e=1-o;t.normalize(),r.m[0]=t.x*t.x*e+o,r.m[1]=t.x*t.y*e-t.z*n,r.m[2]=t.x*t.z*e+t.y*n,r.m[3]=0,r.m[4]=t.y*t.x*e+t.z*n,r.m[5]=t.y*t.y*e+o,r.m[6]=t.y*t.z*e-t.x*n,r.m[7]=0,r.m[8]=t.z*t.x*e-t.y*n,r.m[9]=t.z*t.y*e+t.x*n,r.m[10]=t.z*t.z*e+o,r.m[11]=0,r.m[15]=1},r.RotationYawPitchRoll=function(t,i,n){var o=new r;return r.RotationYawPitchRollToRef(t,i,n,o),o},r.RotationYawPitchRollToRef=function(t,i,r,n){a.RotationYawPitchRollToRef(t,i,r,this._tempQuaternion),this._tempQuaternion.toRotationMatrix(n)},r.Scaling=function(t,i,n){var o=r.Zero();return r.ScalingToRef(t,i,n,o),o},r.ScalingToRef=function(t,i,r,n){n.m[0]=t,n.m[1]=0,n.m[2]=0,n.m[3]=0,n.m[4]=0,n.m[5]=i,n.m[6]=0,n.m[7]=0,n.m[8]=0,n.m[9]=0,n.m[10]=r,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.Translation=function(t,i,n){var o=r.Identity();return r.TranslationToRef(t,i,n,o),o},r.TranslationToRef=function(t,i,n,o){r.FromValuesToRef(1,0,0,0,0,1,0,0,0,0,1,0,t,i,n,1,o)},r.Lerp=function(t,i,n){for(var o=r.Zero(),e=0;e<16;e++)o.m[e]=t.m[e]*(1-n)+i.m[e]*n;return o},r.DecomposeLerp=function(t,i,n){var o=new e(0,0,0),s=new a,h=new e(0,0,0);t.decompose(o,s,h);var u=new e(0,0,0),m=new a,y=new e(0,0,0);i.decompose(u,m,y);var c=e.Lerp(o,u,n),p=a.Slerp(s,m,n),f=e.Lerp(h,y,n);return r.Compose(c,p,f)},r.LookAtLH=function(t,i,n){var o=r.Zero();return r.LookAtLHToRef(t,i,n,o),o},r.LookAtLHToRef=function(t,i,n,o){i.subtractToRef(t,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.LookAtRH=function(t,i,n){var o=r.Zero();return r.LookAtRHToRef(t,i,n,o),o},r.LookAtRHToRef=function(t,i,n,o){t.subtractToRef(i,this._zAxis),this._zAxis.normalize(),e.CrossToRef(n,this._zAxis,this._xAxis),0===this._xAxis.lengthSquared()?this._xAxis.x=1:this._xAxis.normalize(),e.CrossToRef(this._zAxis,this._xAxis,this._yAxis),this._yAxis.normalize();var s=-e.Dot(this._xAxis,t),h=-e.Dot(this._yAxis,t),a=-e.Dot(this._zAxis,t);return r.FromValuesToRef(this._xAxis.x,this._yAxis.x,this._zAxis.x,0,this._xAxis.y,this._yAxis.y,this._zAxis.y,0,this._xAxis.z,this._yAxis.z,this._zAxis.z,0,s,h,a,1,o)},r.OrthoLH=function(t,i,n,o){var e=r.Zero();return r.OrthoLHToRef(t,i,n,o,e),e},r.OrthoLHToRef=function(i,r,n,o,e){var s=n,h=o,a=2/i,u=2/r,m=2/(h-s),y=-(h+s)/(h-s);t.Matrix.FromValuesToRef(a,0,0,0,0,u,0,0,0,0,m,0,0,0,y,1,e)},r.OrthoOffCenterLH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterLHToRef=function(i,r,n,o,e,s,h){var a=e,u=s,m=2/(r-i),y=2/(o-n),c=2/(u-a),p=-(u+a)/(u-a),f=(i+r)/(i-r),x=(o+n)/(n-o);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,0,f,x,p,1,h)},r.OrthoOffCenterRH=function(t,i,n,o,e,s){var h=r.Zero();return r.OrthoOffCenterRHToRef(t,i,n,o,e,s,h),h},r.OrthoOffCenterRHToRef=function(t,i,n,o,e,s,h){r.OrthoOffCenterLHToRef(t,i,n,o,e,s,h),h.m[10]*=-1},r.PerspectiveLH=function(i,n,o,e){var s=r.Zero(),h=o,a=e,u=2*h/i,m=2*h/n,y=(a+h)/(a-h),c=-2*a*h/(a-h);return t.Matrix.FromValuesToRef(u,0,0,0,0,m,0,0,0,0,y,1,0,0,c,0,s),s},r.PerspectiveFovLH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovLHToRef(t,i,n,o,e),e},r.PerspectiveFovLHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,1,0,0,p,0,e)},r.PerspectiveFovRH=function(t,i,n,o){var e=r.Zero();return r.PerspectiveFovRHToRef(t,i,n,o,e),e},r.PerspectiveFovRHToRef=function(i,r,n,o,e,s){void 0===s&&(s=!0);var h=n,a=o,u=1/Math.tan(.5*i),m=s?u/r:u,y=s?u:u*r,c=-(a+h)/(a-h),p=-2*a*h/(a-h);t.Matrix.FromValuesToRef(m,0,0,0,0,y,0,0,0,0,c,-1,0,0,p,0,e)},r.PerspectiveFovWebVRToRef=function(t,i,r,n,o){void 0===o&&(o=!0);var e=Math.tan(t.upDegrees*Math.PI/180),s=Math.tan(t.downDegrees*Math.PI/180),h=Math.tan(t.leftDegrees*Math.PI/180),a=Math.tan(t.rightDegrees*Math.PI/180),u=2/(h+a),m=2/(e+s);n.m[0]=u,n.m[1]=n.m[2]=n.m[3]=n.m[4]=0,n.m[5]=m,n.m[6]=n.m[7]=0,n.m[8]=(h-a)*u*.5,n.m[9]=-((e-s)*m*.5),n.m[10]=-(i+r)/(r-i),n.m[11]=1,n.m[12]=n.m[13]=n.m[15]=0,n.m[14]=-(2*r*i)/(r-i)},r.GetFinalMatrix=function(t,i,n,o,e,s){var h=t.width,a=t.height,u=t.x,m=t.y,y=r.FromValues(h/2,0,0,0,0,-a/2,0,0,0,0,s-e,0,u+h/2,a/2+m,e,1);return i.multiply(n).multiply(o).multiply(y)},r.GetAsMatrix2x2=function(t){return new Float32Array([t.m[0],t.m[1],t.m[4],t.m[5]])},r.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]])},r.Transpose=function(t){var i=new r;return i.m[0]=t.m[0],i.m[1]=t.m[4],i.m[2]=t.m[8],i.m[3]=t.m[12],i.m[4]=t.m[1],i.m[5]=t.m[5],i.m[6]=t.m[9],i.m[7]=t.m[13],i.m[8]=t.m[2],i.m[9]=t.m[6],i.m[10]=t.m[10],i.m[11]=t.m[14],i.m[12]=t.m[3],i.m[13]=t.m[7],i.m[14]=t.m[11],i.m[15]=t.m[15],i},r.Reflection=function(t){var i=new r;return r.ReflectionToRef(t,i),i},r.ReflectionToRef=function(t,i){t.normalize();var r=t.normal.x,n=t.normal.y,o=t.normal.z,e=-2*r,s=-2*n,h=-2*o;i.m[0]=e*r+1,i.m[1]=s*r,i.m[2]=h*r,i.m[3]=0,i.m[4]=e*n,i.m[5]=s*n+1,i.m[6]=h*n,i.m[7]=0,i.m[8]=e*o,i.m[9]=s*o,i.m[10]=h*o+1,i.m[11]=0,i.m[12]=e*t.d,i.m[13]=s*t.d,i.m[14]=h*t.d,i.m[15]=1},r.FromXYZAxesToRef=function(t,i,r,n){n.m[0]=t.x,n.m[1]=t.y,n.m[2]=t.z,n.m[3]=0,n.m[4]=i.x,n.m[5]=i.y,n.m[6]=i.z,n.m[7]=0,n.m[8]=r.x,n.m[9]=r.y,n.m[10]=r.z,n.m[11]=0,n.m[12]=0,n.m[13]=0,n.m[14]=0,n.m[15]=1},r.FromQuaternionToRef=function(t,i){var r=t.x*t.x,n=t.y*t.y,o=t.z*t.z,e=t.x*t.y,s=t.z*t.w,h=t.z*t.x,a=t.y*t.w,u=t.y*t.z,m=t.x*t.w;i.m[0]=1-2*(n+o),i.m[1]=2*(e+s),i.m[2]=2*(h-a),i.m[3]=0,i.m[4]=2*(e-s),i.m[5]=1-2*(o+r),i.m[6]=2*(u+m),i.m[7]=0,i.m[8]=2*(h+a),i.m[9]=2*(u-m),i.m[10]=1-2*(n+r),i.m[11]=0,i.m[12]=0,i.m[13]=0,i.m[14]=0,i.m[15]=1},r}();u._tempQuaternion=new a,u._xAxis=e.Zero(),u._yAxis=e.Zero(),u._zAxis=e.Zero(),t.Matrix=u;var m=function(){function t(t,i,r,n){this.normal=new e(t,i,r),this.d=n}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.getClassName=function(){return\"Plane\"},t.prototype.getHashCode=function(){var t=this.normal.getHashCode();return t=397*t^(this.d||0)},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 r=u.Transpose(i),n=this.normal.x,o=this.normal.y,e=this.normal.z,s=this.d,h=n*r.m[0]+o*r.m[1]+e*r.m[2]+s*r.m[3],a=n*r.m[4]+o*r.m[5]+e*r.m[6]+s*r.m[7],m=n*r.m[8]+o*r.m[9]+e*r.m[10]+s*r.m[11],y=n*r.m[12]+o*r.m[13]+e*r.m[14]+s*r.m[15];return new t(h,a,m,y)},t.prototype.dotCoordinate=function(t){return this.normal.x*t.x+this.normal.y*t.y+this.normal.z*t.z+this.d},t.prototype.copyFromPoints=function(t,i,r){var n,o=i.x-t.x,e=i.y-t.y,s=i.z-t.z,h=r.x-t.x,a=r.y-t.y,u=r.z-t.z,m=e*u-s*a,y=s*h-o*u,c=o*a-e*h,p=Math.sqrt(m*m+y*y+c*c);return n=0!==p?1/p:0,this.normal.x=m*n,this.normal.y=y*n,this.normal.z=c*n,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 r=e.Dot(this.normal,t);return r<=i},t.prototype.signedDistanceTo=function(t){return e.Dot(t,this.normal)+this.d},t.FromArray=function(i){return new t(i[0],i[1],i[2],i[3])},t.FromPoints=function(i,r,n){var o=new t(0,0,0,0);return o.copyFromPoints(i,r,n),o},t.FromPositionAndNormal=function(i,r){var n=new t(0,0,0,0);return r.normalize(),n.normal=r,n.d=-(r.x*i.x+r.y*i.y+r.z*i.z),n},t.SignedDistanceToPlaneFromPositionAndNormal=function(t,i,r){var n=-(i.x*t.x+i.y*t.y+i.z*t.z);return e.Dot(r,i)+n},t}();t.Plane=m;var y=function(){function t(t,i,r,n){this.x=t,this.y=i,this.width=r,this.height=n}return t.prototype.toGlobal=function(i,r){return new t(this.x*i,this.y*r,this.width*i,this.height*r)},t}();t.Viewport=y;var c=function(){function t(){}return t.GetPlanes=function(i){for(var r=[],n=0;n<6;n++)r.push(new m(0,0,0,0));return t.GetPlanesToRef(i,r),r},t.GetPlanesToRef=function(t,i){i[0].normal.x=t.m[3]+t.m[2],i[0].normal.y=t.m[7]+t.m[6],i[0].normal.z=t.m[11]+t.m[10],i[0].d=t.m[15]+t.m[14],i[0].normalize(),i[1].normal.x=t.m[3]-t.m[2],i[1].normal.y=t.m[7]-t.m[6],i[1].normal.z=t.m[11]-t.m[10],i[1].d=t.m[15]-t.m[14],i[1].normalize(),i[2].normal.x=t.m[3]+t.m[0],i[2].normal.y=t.m[7]+t.m[4],i[2].normal.z=t.m[11]+t.m[8],i[2].d=t.m[15]+t.m[12],i[2].normalize(),i[3].normal.x=t.m[3]-t.m[0],i[3].normal.y=t.m[7]-t.m[4],i[3].normal.z=t.m[11]-t.m[8],i[3].d=t.m[15]-t.m[12],i[3].normalize(),i[4].normal.x=t.m[3]-t.m[1],i[4].normal.y=t.m[7]-t.m[5],i[4].normal.z=t.m[11]-t.m[9],i[4].d=t.m[15]-t.m[13],i[4].normalize(),i[5].normal.x=t.m[3]+t.m[1],i[5].normal.y=t.m[7]+t.m[5],i[5].normal.z=t.m[11]+t.m[9],i[5].d=t.m[15]+t.m[13],i[5].normalize()},t}();t.Frustum=c;var p;!function(t){t[t.LOCAL=0]=\"LOCAL\",t[t.WORLD=1]=\"WORLD\"}(p=t.Space||(t.Space={}));var f=function(){function t(){}return t}();f.X=new e(1,0,0),f.Y=new e(0,1,0),f.Z=new e(0,0,1),t.Axis=f;var x=function(){function t(){}return t.interpolate=function(t,i,r,n,o){for(var e=1-3*n+3*i,s=3*n-6*i,h=3*i,a=t,u=0;u<5;u++){var m=a*a,y=m*a,c=e*y+s*m+h*a,p=1/(3*e*m+2*s*a+h);a-=(c-t)*p,a=Math.min(1,Math.max(0,a))}return 3*Math.pow(1-a,2)*a*r+3*(1-a)*Math.pow(a,2)*o+Math.pow(a,3)},t}();t.BezierCurve=x;var l;!function(t){t[t.CW=0]=\"CW\",t[t.CCW=1]=\"CCW\"}(l=t.Orientation||(t.Orientation={}));var z=function(){function t(t){var i=this;this.degrees=function(){return 180*i._radians/Math.PI},this.radians=function(){return i._radians},this._radians=t,this._radians<0&&(this._radians+=2*Math.PI)}return t.BetweenTwoPoints=function(i,r){var n=r.subtract(i),o=Math.atan2(n.y,n.x);return new t(o)},t.FromRadians=function(i){return new t(i)},t.FromDegrees=function(i){return new t(i*Math.PI/180)},t}();t.Angle=z;var w=function(){function t(t,i,r){this.startPoint=t,this.midPoint=i,this.endPoint=r;var n=Math.pow(i.x,2)+Math.pow(i.y,2),e=(Math.pow(t.x,2)+Math.pow(t.y,2)-n)/2,s=(n-Math.pow(r.x,2)-Math.pow(r.y,2))/2,h=(t.x-i.x)*(i.y-r.y)-(i.x-r.x)*(t.y-i.y);this.centerPoint=new o((e*(i.y-r.y)-s*(t.y-i.y))/h,((t.x-i.x)*s-(i.x-r.x)*e)/h),this.radius=this.centerPoint.subtract(this.startPoint).length(),this.startAngle=z.BetweenTwoPoints(this.centerPoint,this.startPoint);var a=this.startAngle.degrees(),u=z.BetweenTwoPoints(this.centerPoint,this.midPoint).degrees(),m=z.BetweenTwoPoints(this.centerPoint,this.endPoint).degrees();u-a>180&&(u-=360),u-a<-180&&(u+=360),m-u>180&&(m-=360),m-u<-180&&(m+=360),this.orientation=u-a<0?l.CW:l.CCW,this.angle=z.FromDegrees(this.orientation===l.CW?a-m:m-a)}return t}();t.Arc2=w;var v=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 r=new o(t,i),n=this._points[this._points.length-1];return this._points.push(r),this._length+=r.subtract(n).length(),this},t.prototype.addArcTo=function(t,i,r,n,e){if(void 0===e&&(e=36),closed)return this;var s=this._points[this._points.length-1],h=new o(t,i),a=new o(r,n),u=new w(s,h,a),m=u.angle.radians()/e;u.orientation===l.CW&&(m*=-1);for(var y=u.startAngle.radians()+m,c=0;c<e;c++){var p=Math.cos(y)*u.radius+u.centerPoint.x,f=Math.sin(y)*u.radius+u.centerPoint.y;this.addLineTo(p,f),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],r=this._points[0];t+=r.subtract(i).length()}return t},t.prototype.getPoints=function(){return this._points},t.prototype.getPointAtLengthPosition=function(t){if(t<0||t>1)return o.Zero();for(var i=t*this.length(),r=0,n=0;n<this._points.length;n++){var e=(n+1)%this._points.length,s=this._points[n],h=this._points[e],a=h.subtract(s),u=a.length()+r;if(i>=r&&i<=u){var m=a.normalize(),y=i-r;return new o(s.x+m.x*y,s.y+m.y*y)}r=u}return o.Zero()},t.StartingAt=function(i,r){return new t(i,r)},t}();t.Path2=v;var d=function(){function r(t,i,r){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 n=0;n<t.length;n++)this._curve[n]=t[n].clone();this._raw=r||!1,this._compute(i)}return r.prototype.getCurve=function(){return this._curve},r.prototype.getTangents=function(){return this._tangents},r.prototype.getNormals=function(){return this._normals},r.prototype.getBinormals=function(){return this._binormals},r.prototype.getDistances=function(){return this._distances},r.prototype.update=function(t,i){for(var r=0;r<t.length;r++)this._curve[r].x=t[r].x,this._curve[r].y=t[r].y,this._curve[r].z=t[r].z;return this._compute(i),this},r.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 r=this._tangents[0],n=this._normalVector(this._curve[0],r,t);this._normals[0]=n,this._raw||this._normals[0].normalize(),this._binormals[0]=e.Cross(r,this._normals[0]),this._raw||this._binormals[0].normalize(),this._distances[0]=0;for(var o,s,h,a,u=1;u<i;u++)o=this._getLastNonNullVector(u),u<i-1&&(s=this._getFirstNonNullVector(u),this._tangents[u]=o.add(s),this._tangents[u].normalize()),this._distances[u]=this._distances[u-1]+o.length(),h=this._tangents[u],a=this._binormals[u-1],this._normals[u]=e.Cross(a,h),this._raw||this._normals[u].normalize(),this._binormals[u]=e.Cross(h,this._normals[u]),this._raw||this._binormals[u].normalize()},r.prototype._getFirstNonNullVector=function(t){for(var i=1,r=this._curve[t+i].subtract(this._curve[t]);0===r.length()&&t+i+1<this._curve.length;)i++,r=this._curve[t+i].subtract(this._curve[t]);return r},r.prototype._getLastNonNullVector=function(t){for(var i=1,r=this._curve[t].subtract(this._curve[t-i]);0===r.length()&&t>i+1;)i++,r=this._curve[t].subtract(this._curve[t-i]);return r},r.prototype._normalVector=function(r,n,o){var s,h=n.length();if(0===h&&(h=1),void 0===o||null===o){var a;i.WithinEpsilon(Math.abs(n.y)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.x)/h,1,t.Epsilon)?i.WithinEpsilon(Math.abs(n.z)/h,1,t.Epsilon)||(a=new e(0,0,1)):a=new e(1,0,0):a=new e(0,(-1),0),s=e.Cross(n,a)}else s=e.Cross(n,o),e.CrossToRef(s,n,s);return s.normalize(),s},r}();t.Path3D=d;var g=function(){function t(t){this._length=0,this._points=t,this._length=this._computeLength(t)}return t.CreateQuadraticBezier=function(i,r,n,o){o=o>2?o:3;for(var s=new Array,h=function(t,i,r,n){var o=(1-t)*(1-t)*i+2*t*(1-t)*r+t*t*n;return o},a=0;a<=o;a++)s.push(new e(h(a/o,i.x,r.x,n.x),h(a/o,i.y,r.y,n.y),h(a/o,i.z,r.z,n.z)));return new t(s)},t.CreateCubicBezier=function(i,r,n,o,s){s=s>3?s:4;for(var h=new Array,a=function(t,i,r,n,o){var e=(1-t)*(1-t)*(1-t)*i+3*t*(1-t)*(1-t)*r+3*t*t*(1-t)*n+t*t*t*o;return e},u=0;u<=s;u++)h.push(new e(a(u/s,i.x,r.x,n.x,o.x),a(u/s,i.y,r.y,n.y,o.y),a(u/s,i.z,r.z,n.z,o.z)));return new t(h)},t.CreateHermiteSpline=function(i,r,n,o,s){for(var h=new Array,a=1/s,u=0;u<=s;u++)h.push(e.Hermite(i,r,n,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 r=this._points[this._points.length-1],n=this._points.slice(),o=i.getPoints(),e=1;e<o.length;e++)n.push(o[e].subtract(o[0]).add(r));var s=new t(n);return s},t.prototype._computeLength=function(t){for(var i=0,r=1;r<t.length;r++)i+=t[r].subtract(t[r-1]).length();return i},t}();t.Curve3=g;var R=function(){function t(){this.L00=e.Zero(),this.L1_1=e.Zero(),this.L10=e.Zero(),this.L11=e.Zero(),this.L2_2=e.Zero(),this.L2_1=e.Zero(),this.L20=e.Zero(),this.L21=e.Zero(),this.L22=e.Zero()}return t.prototype.addLight=function(t,i,r){var n=new e(i.r,i.g,i.b),o=n.scale(r);this.L00=this.L00.add(o.scale(.282095)),this.L1_1=this.L1_1.add(o.scale(.488603*t.y)),this.L10=this.L10.add(o.scale(.488603*t.z)),this.L11=this.L11.add(o.scale(.488603*t.x)),this.L2_2=this.L2_2.add(o.scale(1.092548*t.x*t.y)),this.L2_1=this.L2_1.add(o.scale(1.092548*t.y*t.z)),this.L21=this.L21.add(o.scale(1.092548*t.x*t.z)),this.L20=this.L20.add(o.scale(.315392*(3*t.z*t.z-1))),this.L22=this.L22.add(o.scale(.546274*(t.x*t.x-t.y*t.y)))},t.prototype.scale=function(t){this.L00=this.L00.scale(t),this.L1_1=this.L1_1.scale(t),this.L10=this.L10.scale(t),this.L11=this.L11.scale(t),this.L2_2=this.L2_2.scale(t),this.L2_1=this.L2_1.scale(t),this.L20=this.L20.scale(t),this.L21=this.L21.scale(t),this.L22=this.L22.scale(t)},t}();t.SphericalHarmonics=R;var T=function(){function t(){this.x=e.Zero(),this.y=e.Zero(),this.z=e.Zero(),this.xx=e.Zero(),this.yy=e.Zero(),this.zz=e.Zero(),this.xy=e.Zero(),this.yz=e.Zero(),this.zx=e.Zero()}return t.prototype.addAmbient=function(t){var i=new e(t.r,t.g,t.b);this.xx=this.xx.add(i),this.yy=this.yy.add(i),this.zz=this.zz.add(i)},t.getSphericalPolynomialFromHarmonics=function(i){var r=new t;return r.x=i.L11.scale(1.02333),r.y=i.L1_1.scale(1.02333),r.z=i.L10.scale(1.02333),r.xx=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).add(i.L22.scale(.429043)),r.yy=i.L00.scale(.886277).subtract(i.L20.scale(.247708)).subtract(i.L22.scale(.429043)),r.zz=i.L00.scale(.886277).add(i.L20.scale(.495417)),r.yz=i.L2_1.scale(.858086),r.zx=i.L21.scale(.858086),r.xy=i.L2_2.scale(.858086),r},t}();t.SphericalPolynomial=T;var _=function(){function t(t,i){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),this.position=t,this.normal=i}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone())},t}();t.PositionNormalVertex=_;var M=function(){function t(t,i,r){void 0===t&&(t=e.Zero()),void 0===i&&(i=e.Up()),void 0===r&&(r=o.Zero()),this.position=t,this.normal=i,this.uv=r}return t.prototype.clone=function(){return new t(this.position.clone(),this.normal.clone(),this.uv.clone())},t}();t.PositionNormalTextureVertex=M;var A=function(){function t(){}return t}();A.Color3=[r.Black(),r.Black(),r.Black()],A.Vector2=[o.Zero(),o.Zero(),o.Zero()],A.Vector3=[e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero(),e.Zero()],A.Vector4=[s.Zero(),s.Zero(),s.Zero()],A.Quaternion=[new a(0,0,0,0)],A.Matrix=[u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero(),u.Zero()],t.Tmp=A}(BABYLON||(BABYLON={}));";
  54729. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  54730. module.exports = BABYLON;
  54731. };