babylon.max.js 3.4 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143
  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 () {
  8. var extendStatics = Object.setPrototypeOf ||
  9. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  10. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  11. return function (d, b) {
  12. extendStatics(d, b);
  13. function __() { this.constructor = d; }
  14. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  15. };
  16. })();
  17. var BABYLON;
  18. (function (BABYLON) {
  19. BABYLON.ToGammaSpace = 1 / 2.2;
  20. BABYLON.ToLinearSpace = 2.2;
  21. BABYLON.Epsilon = 0.001;
  22. var Color3 = (function () {
  23. /**
  24. * Creates a new Color3 object from red, green, blue values, all between 0 and 1.
  25. */
  26. function Color3(r, g, b) {
  27. if (r === void 0) { r = 0; }
  28. if (g === void 0) { g = 0; }
  29. if (b === void 0) { b = 0; }
  30. this.r = r;
  31. this.g = g;
  32. this.b = b;
  33. }
  34. /**
  35. * Returns a string with the Color3 current values.
  36. */
  37. Color3.prototype.toString = function () {
  38. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  39. };
  40. /**
  41. * Returns the string "Color3".
  42. */
  43. Color3.prototype.getClassName = function () {
  44. return "Color3";
  45. };
  46. /**
  47. * Returns the Color3 hash code.
  48. */
  49. Color3.prototype.getHashCode = function () {
  50. var hash = this.r || 0;
  51. hash = (hash * 397) ^ (this.g || 0);
  52. hash = (hash * 397) ^ (this.b || 0);
  53. return hash;
  54. };
  55. // Operators
  56. /**
  57. * Stores in the passed array from the passed starting index the red, green, blue values as successive elements.
  58. * Returns the Color3.
  59. */
  60. Color3.prototype.toArray = function (array, index) {
  61. if (index === undefined) {
  62. index = 0;
  63. }
  64. array[index] = this.r;
  65. array[index + 1] = this.g;
  66. array[index + 2] = this.b;
  67. return this;
  68. };
  69. /**
  70. * Returns a new Color4 object from the current Color3 and the passed alpha.
  71. */
  72. Color3.prototype.toColor4 = function (alpha) {
  73. if (alpha === void 0) { alpha = 1; }
  74. return new Color4(this.r, this.g, this.b, alpha);
  75. };
  76. /**
  77. * Returns a new array populated with 3 numeric elements : red, green and blue values.
  78. */
  79. Color3.prototype.asArray = function () {
  80. var result = [];
  81. this.toArray(result, 0);
  82. return result;
  83. };
  84. /**
  85. * Returns the luminance value (float).
  86. */
  87. Color3.prototype.toLuminance = function () {
  88. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  89. };
  90. /**
  91. * Multiply each Color3 rgb values by the passed Color3 rgb values in a new Color3 object.
  92. * Returns this new object.
  93. */
  94. Color3.prototype.multiply = function (otherColor) {
  95. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  96. };
  97. /**
  98. * Multiply the rgb values of the Color3 and the passed Color3 and stores the result in the object "result".
  99. * Returns the current Color3.
  100. */
  101. Color3.prototype.multiplyToRef = function (otherColor, result) {
  102. result.r = this.r * otherColor.r;
  103. result.g = this.g * otherColor.g;
  104. result.b = this.b * otherColor.b;
  105. return this;
  106. };
  107. /**
  108. * Boolean : True if the rgb values are equal to the passed ones.
  109. */
  110. Color3.prototype.equals = function (otherColor) {
  111. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  112. };
  113. /**
  114. * Boolean : True if the rgb values are equal to the passed ones.
  115. */
  116. Color3.prototype.equalsFloats = function (r, g, b) {
  117. return this.r === r && this.g === g && this.b === b;
  118. };
  119. /**
  120. * Multiplies in place each rgb value by scale.
  121. * Returns the updated Color3.
  122. */
  123. Color3.prototype.scale = function (scale) {
  124. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  125. };
  126. /**
  127. * Multiplies the rgb values by scale and stores the result into "result".
  128. * Returns the unmodified current Color3.
  129. */
  130. Color3.prototype.scaleToRef = function (scale, result) {
  131. result.r = this.r * scale;
  132. result.g = this.g * scale;
  133. result.b = this.b * scale;
  134. return this;
  135. };
  136. /**
  137. * Returns a new Color3 set with the added values of the current Color3 and of the passed one.
  138. */
  139. Color3.prototype.add = function (otherColor) {
  140. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  141. };
  142. /**
  143. * Stores the result of the addition of the current Color3 and passed one rgb values into "result".
  144. * Returns the unmodified current Color3.
  145. */
  146. Color3.prototype.addToRef = function (otherColor, result) {
  147. result.r = this.r + otherColor.r;
  148. result.g = this.g + otherColor.g;
  149. result.b = this.b + otherColor.b;
  150. return this;
  151. };
  152. /**
  153. * Returns a new Color3 set with the subtracted values of the passed one from the current Color3 .
  154. */
  155. Color3.prototype.subtract = function (otherColor) {
  156. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  157. };
  158. /**
  159. * Stores the result of the subtraction of passed one from the current Color3 rgb values into "result".
  160. * Returns the unmodified current Color3.
  161. */
  162. Color3.prototype.subtractToRef = function (otherColor, result) {
  163. result.r = this.r - otherColor.r;
  164. result.g = this.g - otherColor.g;
  165. result.b = this.b - otherColor.b;
  166. return this;
  167. };
  168. /**
  169. * Returns a new Color3 copied the current one.
  170. */
  171. Color3.prototype.clone = function () {
  172. return new Color3(this.r, this.g, this.b);
  173. };
  174. /**
  175. * Copies the rgb values from the source in the current Color3.
  176. * Returns the updated Color3.
  177. */
  178. Color3.prototype.copyFrom = function (source) {
  179. this.r = source.r;
  180. this.g = source.g;
  181. this.b = source.b;
  182. return this;
  183. };
  184. /**
  185. * Updates the Color3 rgb values from the passed floats.
  186. * Returns the Color3.
  187. */
  188. Color3.prototype.copyFromFloats = function (r, g, b) {
  189. this.r = r;
  190. this.g = g;
  191. this.b = b;
  192. return this;
  193. };
  194. /**
  195. * Updates the Color3 rgb values from the passed floats.
  196. * Returns the Color3.
  197. */
  198. Color3.prototype.set = function (r, g, b) {
  199. return this.copyFromFloats(r, g, b);
  200. };
  201. /**
  202. * Returns the Color3 hexadecimal code as a string.
  203. */
  204. Color3.prototype.toHexString = function () {
  205. var intR = (this.r * 255) | 0;
  206. var intG = (this.g * 255) | 0;
  207. var intB = (this.b * 255) | 0;
  208. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  209. };
  210. /**
  211. * Returns a new Color3 converted to linear space.
  212. */
  213. Color3.prototype.toLinearSpace = function () {
  214. var convertedColor = new Color3();
  215. this.toLinearSpaceToRef(convertedColor);
  216. return convertedColor;
  217. };
  218. /**
  219. * Converts the Color3 values to linear space and stores the result in "convertedColor".
  220. * Returns the unmodified Color3.
  221. */
  222. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  223. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  224. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  225. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  226. return this;
  227. };
  228. /**
  229. * Returns a new Color3 converted to gamma space.
  230. */
  231. Color3.prototype.toGammaSpace = function () {
  232. var convertedColor = new Color3();
  233. this.toGammaSpaceToRef(convertedColor);
  234. return convertedColor;
  235. };
  236. /**
  237. * Converts the Color3 values to gamma space and stores the result in "convertedColor".
  238. * Returns the unmodified Color3.
  239. */
  240. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  241. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  242. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  243. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  244. return this;
  245. };
  246. // Statics
  247. /**
  248. * Creates a new Color3 from the string containing valid hexadecimal values.
  249. */
  250. Color3.FromHexString = function (hex) {
  251. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  252. //Tools.Warn("Color3.FromHexString must be called with a string like #FFFFFF");
  253. return new Color3(0, 0, 0);
  254. }
  255. var r = parseInt(hex.substring(1, 3), 16);
  256. var g = parseInt(hex.substring(3, 5), 16);
  257. var b = parseInt(hex.substring(5, 7), 16);
  258. return Color3.FromInts(r, g, b);
  259. };
  260. /**
  261. * Creates a new Vector3 from the startind index of the passed array.
  262. */
  263. Color3.FromArray = function (array, offset) {
  264. if (offset === void 0) { offset = 0; }
  265. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  266. };
  267. /**
  268. * Creates a new Color3 from integer values ( < 256).
  269. */
  270. Color3.FromInts = function (r, g, b) {
  271. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  272. };
  273. /**
  274. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3.
  275. */
  276. Color3.Lerp = function (start, end, amount) {
  277. var r = start.r + ((end.r - start.r) * amount);
  278. var g = start.g + ((end.g - start.g) * amount);
  279. var b = start.b + ((end.b - start.b) * amount);
  280. return new Color3(r, g, b);
  281. };
  282. Color3.Red = function () { return new Color3(1, 0, 0); };
  283. Color3.Green = function () { return new Color3(0, 1, 0); };
  284. Color3.Blue = function () { return new Color3(0, 0, 1); };
  285. Color3.Black = function () { return new Color3(0, 0, 0); };
  286. Color3.White = function () { return new Color3(1, 1, 1); };
  287. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  288. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  289. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  290. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  291. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  292. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  293. return Color3;
  294. }());
  295. BABYLON.Color3 = Color3;
  296. var Color4 = (function () {
  297. /**
  298. * Creates a new Color4 object from the passed float values ( < 1) : red, green, blue, alpha.
  299. */
  300. function Color4(r, g, b, a) {
  301. if (r === void 0) { r = 0; }
  302. if (g === void 0) { g = 0; }
  303. if (b === void 0) { b = 0; }
  304. if (a === void 0) { a = 1; }
  305. this.r = r;
  306. this.g = g;
  307. this.b = b;
  308. this.a = a;
  309. }
  310. // Operators
  311. /**
  312. * Adds in place the passed Color4 values to the current Color4.
  313. * Returns the updated Color4.
  314. */
  315. Color4.prototype.addInPlace = function (right) {
  316. this.r += right.r;
  317. this.g += right.g;
  318. this.b += right.b;
  319. this.a += right.a;
  320. return this;
  321. };
  322. /**
  323. * Returns a new array populated with 4 numeric elements : red, green, blue, alpha values.
  324. */
  325. Color4.prototype.asArray = function () {
  326. var result = [];
  327. this.toArray(result, 0);
  328. return result;
  329. };
  330. /**
  331. * Stores from the starting index in the passed array the Color4 successive values.
  332. * Returns the Color4.
  333. */
  334. Color4.prototype.toArray = function (array, index) {
  335. if (index === undefined) {
  336. index = 0;
  337. }
  338. array[index] = this.r;
  339. array[index + 1] = this.g;
  340. array[index + 2] = this.b;
  341. array[index + 3] = this.a;
  342. return this;
  343. };
  344. /**
  345. * Returns a new Color4 set with the added values of the current Color4 and of the passed one.
  346. */
  347. Color4.prototype.add = function (right) {
  348. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  349. };
  350. /**
  351. * Returns a new Color4 set with the subtracted values of the passed one from the current Color4.
  352. */
  353. Color4.prototype.subtract = function (right) {
  354. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  355. };
  356. /**
  357. * Subtracts the passed ones from the current Color4 values and stores the results in "result".
  358. * Returns the Color4.
  359. */
  360. Color4.prototype.subtractToRef = function (right, result) {
  361. result.r = this.r - right.r;
  362. result.g = this.g - right.g;
  363. result.b = this.b - right.b;
  364. result.a = this.a - right.a;
  365. return this;
  366. };
  367. /**
  368. * Creates a new Color4 with the current Color4 values multiplied by scale.
  369. */
  370. Color4.prototype.scale = function (scale) {
  371. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  372. };
  373. /**
  374. * Multiplies the current Color4 values by scale and stores the result in "result".
  375. * Returns the Color4.
  376. */
  377. Color4.prototype.scaleToRef = function (scale, result) {
  378. result.r = this.r * scale;
  379. result.g = this.g * scale;
  380. result.b = this.b * scale;
  381. result.a = this.a * scale;
  382. return this;
  383. };
  384. /**
  385. * Multipy an RGBA Color4 value by another and return a new Color4 object
  386. * @param color The Color4 (RGBA) value to multiply by
  387. * @returns A new Color4.
  388. */
  389. Color4.prototype.multiply = function (color) {
  390. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  391. };
  392. /**
  393. * Multipy an RGBA Color4 value by another and push the result in a reference value
  394. * @param color The Color4 (RGBA) value to multiply by
  395. * @param result The Color4 (RGBA) to fill the result in
  396. * @returns the result Color4.
  397. */
  398. Color4.prototype.multiplyToRef = function (color, result) {
  399. result.r = this.r * color.r;
  400. result.g = this.g * color.g;
  401. result.b = this.b * color.b;
  402. result.a = this.a * color.a;
  403. return result;
  404. };
  405. /**
  406. * Returns a string with the Color4 values.
  407. */
  408. Color4.prototype.toString = function () {
  409. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  410. };
  411. /**
  412. * Returns the string "Color4"
  413. */
  414. Color4.prototype.getClassName = function () {
  415. return "Color4";
  416. };
  417. /**
  418. * Return the Color4 hash code as a number.
  419. */
  420. Color4.prototype.getHashCode = function () {
  421. var hash = this.r || 0;
  422. hash = (hash * 397) ^ (this.g || 0);
  423. hash = (hash * 397) ^ (this.b || 0);
  424. hash = (hash * 397) ^ (this.a || 0);
  425. return hash;
  426. };
  427. /**
  428. * Creates a new Color4 copied from the current one.
  429. */
  430. Color4.prototype.clone = function () {
  431. return new Color4(this.r, this.g, this.b, this.a);
  432. };
  433. /**
  434. * Copies the passed Color4 values into the current one.
  435. * Returns the updated Color4.
  436. */
  437. Color4.prototype.copyFrom = function (source) {
  438. this.r = source.r;
  439. this.g = source.g;
  440. this.b = source.b;
  441. this.a = source.a;
  442. return this;
  443. };
  444. /**
  445. * Copies the passed float values into the current one.
  446. * Returns the updated Color4.
  447. */
  448. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  449. this.r = r;
  450. this.g = g;
  451. this.b = b;
  452. this.a = a;
  453. return this;
  454. };
  455. /**
  456. * Copies the passed float values into the current one.
  457. * Returns the updated Color4.
  458. */
  459. Color4.prototype.set = function (r, g, b, a) {
  460. return this.copyFromFloats(r, g, b, a);
  461. };
  462. /**
  463. * Returns a string containing the hexadecimal Color4 code.
  464. */
  465. Color4.prototype.toHexString = function () {
  466. var intR = (this.r * 255) | 0;
  467. var intG = (this.g * 255) | 0;
  468. var intB = (this.b * 255) | 0;
  469. var intA = (this.a * 255) | 0;
  470. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  471. };
  472. /**
  473. * Returns a new Color4 converted to linear space.
  474. */
  475. Color4.prototype.toLinearSpace = function () {
  476. var convertedColor = new Color4();
  477. this.toLinearSpaceToRef(convertedColor);
  478. return convertedColor;
  479. };
  480. /**
  481. * Converts the Color4 values to linear space and stores the result in "convertedColor".
  482. * Returns the unmodified Color4.
  483. */
  484. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  485. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  486. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  487. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  488. convertedColor.a = this.a;
  489. return this;
  490. };
  491. /**
  492. * Returns a new Color4 converted to gamma space.
  493. */
  494. Color4.prototype.toGammaSpace = function () {
  495. var convertedColor = new Color4();
  496. this.toGammaSpaceToRef(convertedColor);
  497. return convertedColor;
  498. };
  499. /**
  500. * Converts the Color4 values to gamma space and stores the result in "convertedColor".
  501. * Returns the unmodified Color4.
  502. */
  503. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  504. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  505. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  506. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  507. convertedColor.a = this.a;
  508. return this;
  509. };
  510. // Statics
  511. /**
  512. * Creates a new Color4 from the valid hexadecimal value contained in the passed string.
  513. */
  514. Color4.FromHexString = function (hex) {
  515. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  516. //Tools.Warn("Color4.FromHexString must be called with a string like #FFFFFFFF");
  517. return new Color4(0.0, 0.0, 0.0, 0.0);
  518. }
  519. var r = parseInt(hex.substring(1, 3), 16);
  520. var g = parseInt(hex.substring(3, 5), 16);
  521. var b = parseInt(hex.substring(5, 7), 16);
  522. var a = parseInt(hex.substring(7, 9), 16);
  523. return Color4.FromInts(r, g, b, a);
  524. };
  525. /**
  526. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  527. */
  528. Color4.Lerp = function (left, right, amount) {
  529. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  530. Color4.LerpToRef(left, right, amount, result);
  531. return result;
  532. };
  533. /**
  534. * Set the passed "result" with the linearly interpolated values of "amount" between the left Color4 and the right Color4.
  535. */
  536. Color4.LerpToRef = function (left, right, amount, result) {
  537. result.r = left.r + (right.r - left.r) * amount;
  538. result.g = left.g + (right.g - left.g) * amount;
  539. result.b = left.b + (right.b - left.b) * amount;
  540. result.a = left.a + (right.a - left.a) * amount;
  541. };
  542. /**
  543. * Creates a new Color4 from the starting index element of the passed array.
  544. */
  545. Color4.FromArray = function (array, offset) {
  546. if (offset === void 0) { offset = 0; }
  547. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  548. };
  549. /**
  550. * Creates a new Color4 from the passed integers ( < 256 ).
  551. */
  552. Color4.FromInts = function (r, g, b, a) {
  553. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  554. };
  555. Color4.CheckColors4 = function (colors, count) {
  556. // Check if color3 was used
  557. if (colors.length === count * 3) {
  558. var colors4 = [];
  559. for (var index = 0; index < colors.length; index += 3) {
  560. var newIndex = (index / 3) * 4;
  561. colors4[newIndex] = colors[index];
  562. colors4[newIndex + 1] = colors[index + 1];
  563. colors4[newIndex + 2] = colors[index + 2];
  564. colors4[newIndex + 3] = 1.0;
  565. }
  566. return colors4;
  567. }
  568. return colors;
  569. };
  570. return Color4;
  571. }());
  572. BABYLON.Color4 = Color4;
  573. var Vector2 = (function () {
  574. /**
  575. * Creates a new Vector2 from the passed x and y coordinates.
  576. */
  577. function Vector2(x, y) {
  578. this.x = x;
  579. this.y = y;
  580. }
  581. /**
  582. * Returns a string with the Vector2 coordinates.
  583. */
  584. Vector2.prototype.toString = function () {
  585. return "{X: " + this.x + " Y:" + this.y + "}";
  586. };
  587. /**
  588. * Returns the string "Vector2"
  589. */
  590. Vector2.prototype.getClassName = function () {
  591. return "Vector2";
  592. };
  593. /**
  594. * Returns the Vector2 hash code as a number.
  595. */
  596. Vector2.prototype.getHashCode = function () {
  597. var hash = this.x || 0;
  598. hash = (hash * 397) ^ (this.y || 0);
  599. return hash;
  600. };
  601. // Operators
  602. /**
  603. * Sets the Vector2 coordinates in the passed array or Float32Array from the passed index.
  604. * Returns the Vector2.
  605. */
  606. Vector2.prototype.toArray = function (array, index) {
  607. if (index === void 0) { index = 0; }
  608. array[index] = this.x;
  609. array[index + 1] = this.y;
  610. return this;
  611. };
  612. /**
  613. * Returns a new array with 2 elements : the Vector2 coordinates.
  614. */
  615. Vector2.prototype.asArray = function () {
  616. var result = [];
  617. this.toArray(result, 0);
  618. return result;
  619. };
  620. /**
  621. * Sets the Vector2 coordinates with the passed Vector2 coordinates.
  622. * Returns the updated Vector2.
  623. */
  624. Vector2.prototype.copyFrom = function (source) {
  625. this.x = source.x;
  626. this.y = source.y;
  627. return this;
  628. };
  629. /**
  630. * Sets the Vector2 coordinates with the passed floats.
  631. * Returns the updated Vector2.
  632. */
  633. Vector2.prototype.copyFromFloats = function (x, y) {
  634. this.x = x;
  635. this.y = y;
  636. return this;
  637. };
  638. /**
  639. * Sets the Vector2 coordinates with the passed floats.
  640. * Returns the updated Vector2.
  641. */
  642. Vector2.prototype.set = function (x, y) {
  643. return this.copyFromFloats(x, y);
  644. };
  645. /**
  646. * Returns a new Vector2 set with the addition of the current Vector2 and the passed one coordinates.
  647. */
  648. Vector2.prototype.add = function (otherVector) {
  649. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  650. };
  651. /**
  652. * Sets the "result" coordinates with the addition of the current Vector2 and the passed one coordinates.
  653. * Returns the Vector2.
  654. */
  655. Vector2.prototype.addToRef = function (otherVector, result) {
  656. result.x = this.x + otherVector.x;
  657. result.y = this.y + otherVector.y;
  658. return this;
  659. };
  660. /**
  661. * Set the Vector2 coordinates by adding the passed Vector2 coordinates.
  662. * Returns the updated Vector2.
  663. */
  664. Vector2.prototype.addInPlace = function (otherVector) {
  665. this.x += otherVector.x;
  666. this.y += otherVector.y;
  667. return this;
  668. };
  669. /**
  670. * Returns a new Vector2 by adding the current Vector2 coordinates to the passed Vector3 x, y coordinates.
  671. */
  672. Vector2.prototype.addVector3 = function (otherVector) {
  673. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  674. };
  675. /**
  676. * Returns a new Vector2 set with the subtracted coordinates of the passed one from the current Vector2.
  677. */
  678. Vector2.prototype.subtract = function (otherVector) {
  679. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  680. };
  681. /**
  682. * Sets the "result" coordinates with the subtraction of the passed one from the current Vector2 coordinates.
  683. * Returns the Vector2.
  684. */
  685. Vector2.prototype.subtractToRef = function (otherVector, result) {
  686. result.x = this.x - otherVector.x;
  687. result.y = this.y - otherVector.y;
  688. return this;
  689. };
  690. /**
  691. * Sets the current Vector2 coordinates by subtracting from it the passed one coordinates.
  692. * Returns the updated Vector2.
  693. */
  694. Vector2.prototype.subtractInPlace = function (otherVector) {
  695. this.x -= otherVector.x;
  696. this.y -= otherVector.y;
  697. return this;
  698. };
  699. /**
  700. * Multiplies in place the current Vector2 coordinates by the passed ones.
  701. * Returns the updated Vector2.
  702. */
  703. Vector2.prototype.multiplyInPlace = function (otherVector) {
  704. this.x *= otherVector.x;
  705. this.y *= otherVector.y;
  706. return this;
  707. };
  708. /**
  709. * Returns a new Vector2 set with the multiplication of the current Vector2 and the passed one coordinates.
  710. */
  711. Vector2.prototype.multiply = function (otherVector) {
  712. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  713. };
  714. /**
  715. * Sets "result" coordinates with the multiplication of the current Vector2 and the passed one coordinates.
  716. * Returns the Vector2.
  717. */
  718. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  719. result.x = this.x * otherVector.x;
  720. result.y = this.y * otherVector.y;
  721. return this;
  722. };
  723. /**
  724. * Returns a new Vector2 set with the Vector2 coordinates multiplied by the passed floats.
  725. */
  726. Vector2.prototype.multiplyByFloats = function (x, y) {
  727. return new Vector2(this.x * x, this.y * y);
  728. };
  729. /**
  730. * Returns a new Vector2 set with the Vector2 coordinates divided by the passed one coordinates.
  731. */
  732. Vector2.prototype.divide = function (otherVector) {
  733. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  734. };
  735. /**
  736. * Sets the "result" coordinates with the Vector2 divided by the passed one coordinates.
  737. * Returns the Vector2.
  738. */
  739. Vector2.prototype.divideToRef = function (otherVector, result) {
  740. result.x = this.x / otherVector.x;
  741. result.y = this.y / otherVector.y;
  742. return this;
  743. };
  744. /**
  745. * Returns a new Vector2 with current Vector2 negated coordinates.
  746. */
  747. Vector2.prototype.negate = function () {
  748. return new Vector2(-this.x, -this.y);
  749. };
  750. /**
  751. * Multiply the Vector2 coordinates by scale.
  752. * Returns the updated Vector2.
  753. */
  754. Vector2.prototype.scaleInPlace = function (scale) {
  755. this.x *= scale;
  756. this.y *= scale;
  757. return this;
  758. };
  759. /**
  760. * Returns a new Vector2 scaled by "scale" from the current Vector2.
  761. */
  762. Vector2.prototype.scale = function (scale) {
  763. return new Vector2(this.x * scale, this.y * scale);
  764. };
  765. /**
  766. * Boolean : True if the passed vector coordinates strictly equal the current Vector2 ones.
  767. */
  768. Vector2.prototype.equals = function (otherVector) {
  769. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  770. };
  771. /**
  772. * Boolean : True if the passed vector coordinates are close to the current ones by a distance of epsilon.
  773. */
  774. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  775. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  776. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  777. };
  778. // Properties
  779. /**
  780. * Returns the vector length (float).
  781. */
  782. Vector2.prototype.length = function () {
  783. return Math.sqrt(this.x * this.x + this.y * this.y);
  784. };
  785. /**
  786. * Returns the vector squared length (float);
  787. */
  788. Vector2.prototype.lengthSquared = function () {
  789. return (this.x * this.x + this.y * this.y);
  790. };
  791. // Methods
  792. /**
  793. * Normalize the vector.
  794. * Returns the updated Vector2.
  795. */
  796. Vector2.prototype.normalize = function () {
  797. var len = this.length();
  798. if (len === 0)
  799. return this;
  800. var num = 1.0 / len;
  801. this.x *= num;
  802. this.y *= num;
  803. return this;
  804. };
  805. /**
  806. * Returns a new Vector2 copied from the Vector2.
  807. */
  808. Vector2.prototype.clone = function () {
  809. return new Vector2(this.x, this.y);
  810. };
  811. // Statics
  812. /**
  813. * Returns a new Vector2(0, 0)
  814. */
  815. Vector2.Zero = function () {
  816. return new Vector2(0, 0);
  817. };
  818. /**
  819. * Returns a new Vector2(1, 1)
  820. */
  821. Vector2.One = function () {
  822. return new Vector2(1, 1);
  823. };
  824. /**
  825. * Returns a new Vector2 set from the passed index element of the passed array.
  826. */
  827. Vector2.FromArray = function (array, offset) {
  828. if (offset === void 0) { offset = 0; }
  829. return new Vector2(array[offset], array[offset + 1]);
  830. };
  831. /**
  832. * Sets "result" from the passed index element of the passed array.
  833. */
  834. Vector2.FromArrayToRef = function (array, offset, result) {
  835. result.x = array[offset];
  836. result.y = array[offset + 1];
  837. };
  838. /**
  839. * Retuns a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the passed four Vector2.
  840. */
  841. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  842. var squared = amount * amount;
  843. var cubed = amount * squared;
  844. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  845. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  846. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  847. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  848. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  849. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  850. return new Vector2(x, y);
  851. };
  852. /**
  853. * Returns a new Vector2 set with same the coordinates than "value" ones if the vector "value" is in the square defined by "min" and "max".
  854. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  855. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate.
  856. */
  857. Vector2.Clamp = function (value, min, max) {
  858. var x = value.x;
  859. x = (x > max.x) ? max.x : x;
  860. x = (x < min.x) ? min.x : x;
  861. var y = value.y;
  862. y = (y > max.y) ? max.y : y;
  863. y = (y < min.y) ? min.y : y;
  864. return new Vector2(x, y);
  865. };
  866. /**
  867. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2".
  868. */
  869. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  870. var squared = amount * amount;
  871. var cubed = amount * squared;
  872. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  873. var part2 = (-2.0 * cubed) + (3.0 * squared);
  874. var part3 = (cubed - (2.0 * squared)) + amount;
  875. var part4 = cubed - squared;
  876. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  877. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  878. return new Vector2(x, y);
  879. };
  880. /**
  881. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  882. */
  883. Vector2.Lerp = function (start, end, amount) {
  884. var x = start.x + ((end.x - start.x) * amount);
  885. var y = start.y + ((end.y - start.y) * amount);
  886. return new Vector2(x, y);
  887. };
  888. /**
  889. * Returns the dot product (float) of the vector "left" and the vector "right".
  890. */
  891. Vector2.Dot = function (left, right) {
  892. return left.x * right.x + left.y * right.y;
  893. };
  894. /**
  895. * Returns a new Vector2 equal to the normalized passed vector.
  896. */
  897. Vector2.Normalize = function (vector) {
  898. var newVector = vector.clone();
  899. newVector.normalize();
  900. return newVector;
  901. };
  902. /**
  903. * Returns a new Vecto2 set with the minimal coordinate values from the "left" and "right" vectors.
  904. */
  905. Vector2.Minimize = function (left, right) {
  906. var x = (left.x < right.x) ? left.x : right.x;
  907. var y = (left.y < right.y) ? left.y : right.y;
  908. return new Vector2(x, y);
  909. };
  910. /**
  911. * Returns a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors.
  912. */
  913. Vector2.Maximize = function (left, right) {
  914. var x = (left.x > right.x) ? left.x : right.x;
  915. var y = (left.y > right.y) ? left.y : right.y;
  916. return new Vector2(x, y);
  917. };
  918. /**
  919. * Returns a new Vecto2 set with the transformed coordinates of the passed vector by the passed transformation matrix.
  920. */
  921. Vector2.Transform = function (vector, transformation) {
  922. var r = Vector2.Zero();
  923. Vector2.TransformToRef(vector, transformation, r);
  924. return r;
  925. };
  926. /**
  927. * Transforms the passed vector coordinates by the passed transformation matrix and stores the result in the vector "result" coordinates.
  928. */
  929. Vector2.TransformToRef = function (vector, transformation, result) {
  930. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  931. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  932. result.x = x;
  933. result.y = y;
  934. };
  935. /**
  936. * Boolean : True if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  937. */
  938. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  939. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  940. var sign = a < 0 ? -1 : 1;
  941. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  942. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  943. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  944. };
  945. /**
  946. * Returns the distance (float) between the vectors "value1" and "value2".
  947. */
  948. Vector2.Distance = function (value1, value2) {
  949. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  950. };
  951. /**
  952. * Returns the squared distance (float) between the vectors "value1" and "value2".
  953. */
  954. Vector2.DistanceSquared = function (value1, value2) {
  955. var x = value1.x - value2.x;
  956. var y = value1.y - value2.y;
  957. return (x * x) + (y * y);
  958. };
  959. /**
  960. * Returns a new Vecto2 located at the center of the vectors "value1" and "value2".
  961. */
  962. Vector2.Center = function (value1, value2) {
  963. var center = value1.add(value2);
  964. center.scaleInPlace(0.5);
  965. return center;
  966. };
  967. /**
  968. * Returns the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  969. */
  970. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  971. var l2 = Vector2.DistanceSquared(segA, segB);
  972. if (l2 === 0.0) {
  973. return Vector2.Distance(p, segA);
  974. }
  975. var v = segB.subtract(segA);
  976. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  977. var proj = segA.add(v.multiplyByFloats(t, t));
  978. return Vector2.Distance(p, proj);
  979. };
  980. return Vector2;
  981. }());
  982. BABYLON.Vector2 = Vector2;
  983. var Vector3 = (function () {
  984. /**
  985. * Creates a new Vector3 object from the passed x, y, z (floats) coordinates.
  986. * A Vector3 is the main object used in 3D geometry.
  987. * It can represent etiher the coordinates of a point the space, either a direction.
  988. */
  989. function Vector3(x, y, z) {
  990. this.x = x;
  991. this.y = y;
  992. this.z = z;
  993. }
  994. /**
  995. * Returns a string with the Vector3 coordinates.
  996. */
  997. Vector3.prototype.toString = function () {
  998. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  999. };
  1000. /**
  1001. * Returns the string "Vector3"
  1002. */
  1003. Vector3.prototype.getClassName = function () {
  1004. return "Vector3";
  1005. };
  1006. /**
  1007. * Returns the Vector hash code.
  1008. */
  1009. Vector3.prototype.getHashCode = function () {
  1010. var hash = this.x || 0;
  1011. hash = (hash * 397) ^ (this.y || 0);
  1012. hash = (hash * 397) ^ (this.z || 0);
  1013. return hash;
  1014. };
  1015. // Operators
  1016. /**
  1017. * Returns a new array with three elements : the coordinates the Vector3.
  1018. */
  1019. Vector3.prototype.asArray = function () {
  1020. var result = [];
  1021. this.toArray(result, 0);
  1022. return result;
  1023. };
  1024. /**
  1025. * Populates the passed array or Float32Array from the passed index with the successive coordinates of the Vector3.
  1026. * Returns the Vector3.
  1027. */
  1028. Vector3.prototype.toArray = function (array, index) {
  1029. if (index === void 0) { index = 0; }
  1030. array[index] = this.x;
  1031. array[index + 1] = this.y;
  1032. array[index + 2] = this.z;
  1033. return this;
  1034. };
  1035. /**
  1036. * Returns a new Quaternion object, computed from the Vector3 coordinates.
  1037. */
  1038. Vector3.prototype.toQuaternion = function () {
  1039. var result = new Quaternion(0.0, 0.0, 0.0, 1.0);
  1040. var cosxPlusz = Math.cos((this.x + this.z) * 0.5);
  1041. var sinxPlusz = Math.sin((this.x + this.z) * 0.5);
  1042. var coszMinusx = Math.cos((this.z - this.x) * 0.5);
  1043. var sinzMinusx = Math.sin((this.z - this.x) * 0.5);
  1044. var cosy = Math.cos(this.y * 0.5);
  1045. var siny = Math.sin(this.y * 0.5);
  1046. result.x = coszMinusx * siny;
  1047. result.y = -sinzMinusx * siny;
  1048. result.z = sinxPlusz * cosy;
  1049. result.w = cosxPlusz * cosy;
  1050. return result;
  1051. };
  1052. /**
  1053. * Adds the passed vector to the current Vector3.
  1054. * Returns the updated Vector3.
  1055. */
  1056. Vector3.prototype.addInPlace = function (otherVector) {
  1057. this.x += otherVector.x;
  1058. this.y += otherVector.y;
  1059. this.z += otherVector.z;
  1060. return this;
  1061. };
  1062. /**
  1063. * Returns a new Vector3, result of the addition the current Vector3 and the passed vector.
  1064. */
  1065. Vector3.prototype.add = function (otherVector) {
  1066. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  1067. };
  1068. /**
  1069. * Adds the current Vector3 to the passed one and stores the result in the vector "result".
  1070. * Returns the current Vector3.
  1071. */
  1072. Vector3.prototype.addToRef = function (otherVector, result) {
  1073. result.x = this.x + otherVector.x;
  1074. result.y = this.y + otherVector.y;
  1075. result.z = this.z + otherVector.z;
  1076. return this;
  1077. };
  1078. /**
  1079. * Subtract the passed vector from the current Vector3.
  1080. * Returns the updated Vector3.
  1081. */
  1082. Vector3.prototype.subtractInPlace = function (otherVector) {
  1083. this.x -= otherVector.x;
  1084. this.y -= otherVector.y;
  1085. this.z -= otherVector.z;
  1086. return this;
  1087. };
  1088. /**
  1089. * Returns a new Vector3, result of the subtraction of the passed vector from the current Vector3.
  1090. */
  1091. Vector3.prototype.subtract = function (otherVector) {
  1092. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  1093. };
  1094. /**
  1095. * Subtracts the passed vector from the current Vector3 and stores the result in the vector "result".
  1096. * Returns the current Vector3.
  1097. */
  1098. Vector3.prototype.subtractToRef = function (otherVector, result) {
  1099. result.x = this.x - otherVector.x;
  1100. result.y = this.y - otherVector.y;
  1101. result.z = this.z - otherVector.z;
  1102. return this;
  1103. };
  1104. /**
  1105. * Returns a new Vector3 set with the subtraction of the passed floats from the current Vector3 coordinates.
  1106. */
  1107. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  1108. return new Vector3(this.x - x, this.y - y, this.z - z);
  1109. };
  1110. /**
  1111. * Subtracts the passed floats from the current Vector3 coordinates and set the passed vector "result" with this result.
  1112. * Returns the current Vector3.
  1113. */
  1114. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  1115. result.x = this.x - x;
  1116. result.y = this.y - y;
  1117. result.z = this.z - z;
  1118. return this;
  1119. };
  1120. /**
  1121. * Returns a new Vector3 set with the current Vector3 negated coordinates.
  1122. */
  1123. Vector3.prototype.negate = function () {
  1124. return new Vector3(-this.x, -this.y, -this.z);
  1125. };
  1126. /**
  1127. * Multiplies the Vector3 coordinates by the float "scale".
  1128. * Returns the updated Vector3.
  1129. */
  1130. Vector3.prototype.scaleInPlace = function (scale) {
  1131. this.x *= scale;
  1132. this.y *= scale;
  1133. this.z *= scale;
  1134. return this;
  1135. };
  1136. /**
  1137. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale".
  1138. */
  1139. Vector3.prototype.scale = function (scale) {
  1140. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  1141. };
  1142. /**
  1143. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the passed vector "result" coordinates.
  1144. * Returns the current Vector3.
  1145. */
  1146. Vector3.prototype.scaleToRef = function (scale, result) {
  1147. result.x = this.x * scale;
  1148. result.y = this.y * scale;
  1149. result.z = this.z * scale;
  1150. return this;
  1151. };
  1152. /**
  1153. * Boolean : True if the current Vector3 and the passed vector coordinates are strictly equal.
  1154. */
  1155. Vector3.prototype.equals = function (otherVector) {
  1156. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  1157. };
  1158. /**
  1159. * Boolean : True if the current Vector3 and the passed vector coordinates are distant less than epsilon.
  1160. */
  1161. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1162. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1163. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon) && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon);
  1164. };
  1165. /**
  1166. * Boolean : True if the current Vector3 coordinate equal the passed floats.
  1167. */
  1168. Vector3.prototype.equalsToFloats = function (x, y, z) {
  1169. return this.x === x && this.y === y && this.z === z;
  1170. };
  1171. /**
  1172. * Muliplies the current Vector3 coordinates by the passed ones.
  1173. * Returns the updated Vector3.
  1174. */
  1175. Vector3.prototype.multiplyInPlace = function (otherVector) {
  1176. this.x *= otherVector.x;
  1177. this.y *= otherVector.y;
  1178. this.z *= otherVector.z;
  1179. return this;
  1180. };
  1181. /**
  1182. * Returns a new Vector3, result of the multiplication of the current Vector3 by the passed vector.
  1183. */
  1184. Vector3.prototype.multiply = function (otherVector) {
  1185. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  1186. };
  1187. /**
  1188. * Multiplies the current Vector3 by the passed one and stores the result in the passed vector "result".
  1189. * Returns the current Vector3.
  1190. */
  1191. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  1192. result.x = this.x * otherVector.x;
  1193. result.y = this.y * otherVector.y;
  1194. result.z = this.z * otherVector.z;
  1195. return this;
  1196. };
  1197. /**
  1198. * Returns a new Vector3 set witth the result of the mulliplication of the current Vector3 coordinates by the passed floats.
  1199. */
  1200. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  1201. return new Vector3(this.x * x, this.y * y, this.z * z);
  1202. };
  1203. /**
  1204. * Returns a new Vector3 set witth the result of the division of the current Vector3 coordinates by the passed ones.
  1205. */
  1206. Vector3.prototype.divide = function (otherVector) {
  1207. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  1208. };
  1209. /**
  1210. * Divides the current Vector3 coordinates by the passed ones and stores the result in the passed vector "result".
  1211. * Returns the current Vector3.
  1212. */
  1213. Vector3.prototype.divideToRef = function (otherVector, result) {
  1214. result.x = this.x / otherVector.x;
  1215. result.y = this.y / otherVector.y;
  1216. result.z = this.z / otherVector.z;
  1217. return this;
  1218. };
  1219. /**
  1220. * Updates the current Vector3 with the minimal coordinate values between its and the passed vector ones.
  1221. * Returns the updated Vector3.
  1222. */
  1223. Vector3.prototype.MinimizeInPlace = function (other) {
  1224. if (other.x < this.x)
  1225. this.x = other.x;
  1226. if (other.y < this.y)
  1227. this.y = other.y;
  1228. if (other.z < this.z)
  1229. this.z = other.z;
  1230. return this;
  1231. };
  1232. /**
  1233. * Updates the current Vector3 with the maximal coordinate values between its and the passed vector ones.
  1234. * Returns the updated Vector3.
  1235. */
  1236. Vector3.prototype.MaximizeInPlace = function (other) {
  1237. if (other.x > this.x)
  1238. this.x = other.x;
  1239. if (other.y > this.y)
  1240. this.y = other.y;
  1241. if (other.z > this.z)
  1242. this.z = other.z;
  1243. return this;
  1244. };
  1245. // Properties
  1246. /**
  1247. * Returns the length of the Vector3 (float).
  1248. */
  1249. Vector3.prototype.length = function () {
  1250. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  1251. };
  1252. /**
  1253. * Returns the squared length of the Vector3 (float).
  1254. */
  1255. Vector3.prototype.lengthSquared = function () {
  1256. return (this.x * this.x + this.y * this.y + this.z * this.z);
  1257. };
  1258. // Methods
  1259. /**
  1260. * Normalize the current Vector3.
  1261. * Returns the updated Vector3.
  1262. */
  1263. Vector3.prototype.normalize = function () {
  1264. var len = this.length();
  1265. if (len === 0 || len === 1.0)
  1266. return this;
  1267. var num = 1.0 / len;
  1268. this.x *= num;
  1269. this.y *= num;
  1270. this.z *= num;
  1271. return this;
  1272. };
  1273. /**
  1274. * Returns a new Vector3 copied from the current Vector3.
  1275. */
  1276. Vector3.prototype.clone = function () {
  1277. return new Vector3(this.x, this.y, this.z);
  1278. };
  1279. /**
  1280. * Copies the passed vector coordinates to the current Vector3 ones.
  1281. * Returns the updated Vector3.
  1282. */
  1283. Vector3.prototype.copyFrom = function (source) {
  1284. this.x = source.x;
  1285. this.y = source.y;
  1286. this.z = source.z;
  1287. return this;
  1288. };
  1289. /**
  1290. * Copies the passed floats to the current Vector3 coordinates.
  1291. * Returns the updated Vector3.
  1292. */
  1293. Vector3.prototype.copyFromFloats = function (x, y, z) {
  1294. this.x = x;
  1295. this.y = y;
  1296. this.z = z;
  1297. return this;
  1298. };
  1299. /**
  1300. * Copies the passed floats to the current Vector3 coordinates.
  1301. * Returns the updated Vector3.
  1302. */
  1303. Vector3.prototype.set = function (x, y, z) {
  1304. return this.copyFromFloats(x, y, z);
  1305. };
  1306. // Statics
  1307. /**
  1308. *
  1309. */
  1310. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  1311. var d0 = Vector3.Dot(vector0, axis) - size;
  1312. var d1 = Vector3.Dot(vector1, axis) - size;
  1313. var s = d0 / (d0 - d1);
  1314. return s;
  1315. };
  1316. /**
  1317. * Returns a new Vector3 set from the index "offset" of the passed array.
  1318. */
  1319. Vector3.FromArray = function (array, offset) {
  1320. if (!offset) {
  1321. offset = 0;
  1322. }
  1323. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  1324. };
  1325. /**
  1326. * Returns a new Vector3 set from the index "offset" of the passed Float32Array.
  1327. * This function is deprecated. Use FromArray instead.
  1328. */
  1329. Vector3.FromFloatArray = function (array, offset) {
  1330. return Vector3.FromArray(array, offset);
  1331. };
  1332. /**
  1333. * Sets the passed vector "result" with the element values from the index "offset" of the passed array.
  1334. */
  1335. Vector3.FromArrayToRef = function (array, offset, result) {
  1336. result.x = array[offset];
  1337. result.y = array[offset + 1];
  1338. result.z = array[offset + 2];
  1339. };
  1340. /**
  1341. * Sets the passed vector "result" with the element values from the index "offset" of the passed Float32Array.
  1342. * This function is deprecated. Use FromArrayToRef instead.
  1343. */
  1344. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  1345. return Vector3.FromArrayToRef(array, offset, result);
  1346. };
  1347. /**
  1348. * Sets the passed vector "result" with the passed floats.
  1349. */
  1350. Vector3.FromFloatsToRef = function (x, y, z, result) {
  1351. result.x = x;
  1352. result.y = y;
  1353. result.z = z;
  1354. };
  1355. /**
  1356. * Returns a new Vector3 set to (0.0, 0.0, 0.0).
  1357. */
  1358. Vector3.Zero = function () {
  1359. return new Vector3(0.0, 0.0, 0.0);
  1360. };
  1361. /**
  1362. * Returns a new Vector3 set to (1.0, 1.0, 1.0).
  1363. */
  1364. Vector3.One = function () {
  1365. return new Vector3(1.0, 1.0, 1.0);
  1366. };
  1367. /**
  1368. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  1369. */
  1370. Vector3.Up = function () {
  1371. return new Vector3(0.0, 1.0, 0.0);
  1372. };
  1373. /**
  1374. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  1375. */
  1376. Vector3.Forward = function () {
  1377. return new Vector3(0.0, 0.0, 1.0);
  1378. };
  1379. /**
  1380. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  1381. */
  1382. Vector3.Right = function () {
  1383. return new Vector3(1.0, 0.0, 0.0);
  1384. };
  1385. /**
  1386. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  1387. */
  1388. Vector3.Left = function () {
  1389. return new Vector3(-1.0, 0.0, 0.0);
  1390. };
  1391. /**
  1392. * Returns a new Vector3 set with the result of the transformation by the passed matrix of the passed vector.
  1393. * This method computes tranformed coordinates only, not transformed direction vectors.
  1394. */
  1395. Vector3.TransformCoordinates = function (vector, transformation) {
  1396. var result = Vector3.Zero();
  1397. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  1398. return result;
  1399. };
  1400. /**
  1401. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed vector.
  1402. * This method computes tranformed coordinates only, not transformed direction vectors.
  1403. */
  1404. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  1405. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  1406. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  1407. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  1408. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  1409. result.x = x / w;
  1410. result.y = y / w;
  1411. result.z = z / w;
  1412. };
  1413. /**
  1414. * Sets the passed vector "result" coordinates with the result of the transformation by the passed matrix of the passed floats (x, y, z).
  1415. * This method computes tranformed coordinates only, not transformed direction vectors.
  1416. */
  1417. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  1418. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  1419. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  1420. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  1421. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  1422. result.x = rx / rw;
  1423. result.y = ry / rw;
  1424. result.z = rz / rw;
  1425. };
  1426. /**
  1427. * Returns a new Vector3 set with the result of the normal transformation by the passed matrix of the passed vector.
  1428. * This methods computes transformed normalized direction vectors only.
  1429. */
  1430. Vector3.TransformNormal = function (vector, transformation) {
  1431. var result = Vector3.Zero();
  1432. Vector3.TransformNormalToRef(vector, transformation, result);
  1433. return result;
  1434. };
  1435. /**
  1436. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  1437. * This methods computes transformed normalized direction vectors only.
  1438. */
  1439. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  1440. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  1441. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  1442. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  1443. result.x = x;
  1444. result.y = y;
  1445. result.z = z;
  1446. };
  1447. /**
  1448. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z).
  1449. * This methods computes transformed normalized direction vectors only.
  1450. */
  1451. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  1452. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  1453. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  1454. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  1455. };
  1456. /**
  1457. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4".
  1458. */
  1459. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  1460. var squared = amount * amount;
  1461. var cubed = amount * squared;
  1462. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  1463. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  1464. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  1465. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  1466. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  1467. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  1468. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  1469. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  1470. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  1471. return new Vector3(x, y, z);
  1472. };
  1473. /**
  1474. * Returns a new Vector3 set with the coordinates of "value", if the vector "value" is in the cube defined by the vectors "min" and "max".
  1475. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one.
  1476. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one.
  1477. */
  1478. Vector3.Clamp = function (value, min, max) {
  1479. var x = value.x;
  1480. x = (x > max.x) ? max.x : x;
  1481. x = (x < min.x) ? min.x : x;
  1482. var y = value.y;
  1483. y = (y > max.y) ? max.y : y;
  1484. y = (y < min.y) ? min.y : y;
  1485. var z = value.z;
  1486. z = (z > max.z) ? max.z : z;
  1487. z = (z < min.z) ? min.z : z;
  1488. return new Vector3(x, y, z);
  1489. };
  1490. /**
  1491. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  1492. */
  1493. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  1494. var squared = amount * amount;
  1495. var cubed = amount * squared;
  1496. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  1497. var part2 = (-2.0 * cubed) + (3.0 * squared);
  1498. var part3 = (cubed - (2.0 * squared)) + amount;
  1499. var part4 = cubed - squared;
  1500. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  1501. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  1502. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  1503. return new Vector3(x, y, z);
  1504. };
  1505. /**
  1506. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end".
  1507. */
  1508. Vector3.Lerp = function (start, end, amount) {
  1509. var result = new Vector3(0, 0, 0);
  1510. Vector3.LerpToRef(start, end, amount, result);
  1511. return result;
  1512. };
  1513. /**
  1514. * Sets the passed vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end".
  1515. */
  1516. Vector3.LerpToRef = function (start, end, amount, result) {
  1517. result.x = start.x + ((end.x - start.x) * amount);
  1518. result.y = start.y + ((end.y - start.y) * amount);
  1519. result.z = start.z + ((end.z - start.z) * amount);
  1520. };
  1521. /**
  1522. * Returns the dot product (float) between the vectors "left" and "right".
  1523. */
  1524. Vector3.Dot = function (left, right) {
  1525. return (left.x * right.x + left.y * right.y + left.z * right.z);
  1526. };
  1527. /**
  1528. * Returns a new Vector3 as the cross product of the vectors "left" and "right".
  1529. * The cross product is then orthogonal to both "left" and "right".
  1530. */
  1531. Vector3.Cross = function (left, right) {
  1532. var result = Vector3.Zero();
  1533. Vector3.CrossToRef(left, right, result);
  1534. return result;
  1535. };
  1536. /**
  1537. * Sets the passed vector "result" with the cross product of "left" and "right".
  1538. * The cross product is then orthogonal to both "left" and "right".
  1539. */
  1540. Vector3.CrossToRef = function (left, right, result) {
  1541. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  1542. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  1543. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  1544. result.copyFrom(MathTmp.Vector3[0]);
  1545. };
  1546. /**
  1547. * Returns a new Vector3 as the normalization of the passed vector.
  1548. */
  1549. Vector3.Normalize = function (vector) {
  1550. var result = Vector3.Zero();
  1551. Vector3.NormalizeToRef(vector, result);
  1552. return result;
  1553. };
  1554. /**
  1555. * Sets the passed vector "result" with the normalization of the passed first vector.
  1556. */
  1557. Vector3.NormalizeToRef = function (vector, result) {
  1558. result.copyFrom(vector);
  1559. result.normalize();
  1560. };
  1561. Vector3.Project = function (vector, world, transform, viewport) {
  1562. var cw = viewport.width;
  1563. var ch = viewport.height;
  1564. var cx = viewport.x;
  1565. var cy = viewport.y;
  1566. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  1567. Matrix.FromValuesToRef(cw / 2.0, 0, 0, 0, 0, -ch / 2.0, 0, 0, 0, 0, 0.5, 0, cx + cw / 2.0, ch / 2.0 + cy, 0.5, 1, viewportMatrix);
  1568. var matrix = MathTmp.Matrix[0];
  1569. world.multiplyToRef(transform, matrix);
  1570. matrix.multiplyToRef(viewportMatrix, matrix);
  1571. return Vector3.TransformCoordinates(vector, matrix);
  1572. };
  1573. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  1574. var matrix = MathTmp.Matrix[0];
  1575. world.multiplyToRef(transform, matrix);
  1576. matrix.invert();
  1577. source.x = source.x / viewportWidth * 2 - 1;
  1578. source.y = -(source.y / viewportHeight * 2 - 1);
  1579. var vector = Vector3.TransformCoordinates(source, matrix);
  1580. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  1581. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1582. vector = vector.scale(1.0 / num);
  1583. }
  1584. return vector;
  1585. };
  1586. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  1587. var matrix = MathTmp.Matrix[0];
  1588. world.multiplyToRef(view, matrix);
  1589. matrix.multiplyToRef(projection, matrix);
  1590. matrix.invert();
  1591. var screenSource = new Vector3(source.x / viewportWidth * 2 - 1, -(source.y / viewportHeight * 2 - 1), 2 * source.z - 1.0);
  1592. var vector = Vector3.TransformCoordinates(screenSource, matrix);
  1593. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  1594. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  1595. vector = vector.scale(1.0 / num);
  1596. }
  1597. return vector;
  1598. };
  1599. Vector3.Minimize = function (left, right) {
  1600. var min = left.clone();
  1601. min.MinimizeInPlace(right);
  1602. return min;
  1603. };
  1604. Vector3.Maximize = function (left, right) {
  1605. var max = left.clone();
  1606. max.MaximizeInPlace(right);
  1607. return max;
  1608. };
  1609. /**
  1610. * Returns the distance (float) between the vectors "value1" and "value2".
  1611. */
  1612. Vector3.Distance = function (value1, value2) {
  1613. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  1614. };
  1615. /**
  1616. * Returns the squared distance (float) between the vectors "value1" and "value2".
  1617. */
  1618. Vector3.DistanceSquared = function (value1, value2) {
  1619. var x = value1.x - value2.x;
  1620. var y = value1.y - value2.y;
  1621. var z = value1.z - value2.z;
  1622. return (x * x) + (y * y) + (z * z);
  1623. };
  1624. /**
  1625. * Returns a new Vector3 located at the center between "value1" and "value2".
  1626. */
  1627. Vector3.Center = function (value1, value2) {
  1628. var center = value1.add(value2);
  1629. center.scaleInPlace(0.5);
  1630. return center;
  1631. };
  1632. /**
  1633. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  1634. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  1635. * to something in order to rotate it from its local system to the given target system.
  1636. * Note : axis1, axis2 and axis3 are normalized during this operation.
  1637. * Returns a new Vector3.
  1638. */
  1639. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  1640. var rotation = Vector3.Zero();
  1641. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  1642. return rotation;
  1643. };
  1644. /**
  1645. * The same than RotationFromAxis but updates the passed ref Vector3 parameter instead of returning a new Vector3.
  1646. */
  1647. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  1648. var quat = MathTmp.Quaternion[0];
  1649. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  1650. quat.toEulerAnglesToRef(ref);
  1651. };
  1652. return Vector3;
  1653. }());
  1654. BABYLON.Vector3 = Vector3;
  1655. //Vector4 class created for EulerAngle class conversion to Quaternion
  1656. var Vector4 = (function () {
  1657. /**
  1658. * Creates a Vector4 object from the passed floats.
  1659. */
  1660. function Vector4(x, y, z, w) {
  1661. this.x = x;
  1662. this.y = y;
  1663. this.z = z;
  1664. this.w = w;
  1665. }
  1666. /**
  1667. * Returns the string with the Vector4 coordinates.
  1668. */
  1669. Vector4.prototype.toString = function () {
  1670. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  1671. };
  1672. /**
  1673. * Returns the string "Vector4".
  1674. */
  1675. Vector4.prototype.getClassName = function () {
  1676. return "Vector4";
  1677. };
  1678. /**
  1679. * Returns the Vector4 hash code.
  1680. */
  1681. Vector4.prototype.getHashCode = function () {
  1682. var hash = this.x || 0;
  1683. hash = (hash * 397) ^ (this.y || 0);
  1684. hash = (hash * 397) ^ (this.z || 0);
  1685. hash = (hash * 397) ^ (this.w || 0);
  1686. return hash;
  1687. };
  1688. // Operators
  1689. /**
  1690. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  1691. */
  1692. Vector4.prototype.asArray = function () {
  1693. var result = [];
  1694. this.toArray(result, 0);
  1695. return result;
  1696. };
  1697. /**
  1698. * Populates the passed array from the passed index with the Vector4 coordinates.
  1699. * Returns the Vector4.
  1700. */
  1701. Vector4.prototype.toArray = function (array, index) {
  1702. if (index === undefined) {
  1703. index = 0;
  1704. }
  1705. array[index] = this.x;
  1706. array[index + 1] = this.y;
  1707. array[index + 2] = this.z;
  1708. array[index + 3] = this.w;
  1709. return this;
  1710. };
  1711. /**
  1712. * Adds the passed vector to the current Vector4.
  1713. * Returns the updated Vector4.
  1714. */
  1715. Vector4.prototype.addInPlace = function (otherVector) {
  1716. this.x += otherVector.x;
  1717. this.y += otherVector.y;
  1718. this.z += otherVector.z;
  1719. this.w += otherVector.w;
  1720. return this;
  1721. };
  1722. /**
  1723. * Returns a new Vector4 as the result of the addition of the current Vector4 and the passed one.
  1724. */
  1725. Vector4.prototype.add = function (otherVector) {
  1726. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  1727. };
  1728. /**
  1729. * Updates the passed vector "result" with the result of the addition of the current Vector4 and the passed one.
  1730. * Returns the current Vector4.
  1731. */
  1732. Vector4.prototype.addToRef = function (otherVector, result) {
  1733. result.x = this.x + otherVector.x;
  1734. result.y = this.y + otherVector.y;
  1735. result.z = this.z + otherVector.z;
  1736. result.w = this.w + otherVector.w;
  1737. return this;
  1738. };
  1739. /**
  1740. * Subtract in place the passed vector from the current Vector4.
  1741. * Returns the updated Vector4.
  1742. */
  1743. Vector4.prototype.subtractInPlace = function (otherVector) {
  1744. this.x -= otherVector.x;
  1745. this.y -= otherVector.y;
  1746. this.z -= otherVector.z;
  1747. this.w -= otherVector.w;
  1748. return this;
  1749. };
  1750. /**
  1751. * Returns a new Vector4 with the result of the subtraction of the passed vector from the current Vector4.
  1752. */
  1753. Vector4.prototype.subtract = function (otherVector) {
  1754. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  1755. };
  1756. /**
  1757. * Sets the passed vector "result" with the result of the subtraction of the passed vector from the current Vector4.
  1758. * Returns the current Vector4.
  1759. */
  1760. Vector4.prototype.subtractToRef = function (otherVector, result) {
  1761. result.x = this.x - otherVector.x;
  1762. result.y = this.y - otherVector.y;
  1763. result.z = this.z - otherVector.z;
  1764. result.w = this.w - otherVector.w;
  1765. return this;
  1766. };
  1767. /**
  1768. * Returns a new Vector4 set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1769. */
  1770. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  1771. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  1772. };
  1773. /**
  1774. * Sets the passed vector "result" set with the result of the subtraction of the passed floats from the current Vector4 coordinates.
  1775. * Returns the current Vector4.
  1776. */
  1777. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  1778. result.x = this.x - x;
  1779. result.y = this.y - y;
  1780. result.z = this.z - z;
  1781. result.w = this.w - w;
  1782. return this;
  1783. };
  1784. /**
  1785. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  1786. */
  1787. Vector4.prototype.negate = function () {
  1788. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  1789. };
  1790. /**
  1791. * Multiplies the current Vector4 coordinates by scale (float).
  1792. * Returns the updated Vector4.
  1793. */
  1794. Vector4.prototype.scaleInPlace = function (scale) {
  1795. this.x *= scale;
  1796. this.y *= scale;
  1797. this.z *= scale;
  1798. this.w *= scale;
  1799. return this;
  1800. };
  1801. /**
  1802. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  1803. */
  1804. Vector4.prototype.scale = function (scale) {
  1805. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  1806. };
  1807. /**
  1808. * Sets the passed vector "result" with the current Vector4 coordinates multiplied by scale (float).
  1809. * Returns the current Vector4.
  1810. */
  1811. Vector4.prototype.scaleToRef = function (scale, result) {
  1812. result.x = this.x * scale;
  1813. result.y = this.y * scale;
  1814. result.z = this.z * scale;
  1815. result.w = this.w * scale;
  1816. return this;
  1817. };
  1818. /**
  1819. * Boolean : True if the current Vector4 coordinates are stricly equal to the passed ones.
  1820. */
  1821. Vector4.prototype.equals = function (otherVector) {
  1822. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  1823. };
  1824. /**
  1825. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the passed vector ones.
  1826. */
  1827. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  1828. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  1829. return otherVector
  1830. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  1831. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  1832. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  1833. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  1834. };
  1835. /**
  1836. * Boolean : True if the passed floats are strictly equal to the current Vector4 coordinates.
  1837. */
  1838. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  1839. return this.x === x && this.y === y && this.z === z && this.w === w;
  1840. };
  1841. /**
  1842. * Multiplies in place the current Vector4 by the passed one.
  1843. * Returns the updated Vector4.
  1844. */
  1845. Vector4.prototype.multiplyInPlace = function (otherVector) {
  1846. this.x *= otherVector.x;
  1847. this.y *= otherVector.y;
  1848. this.z *= otherVector.z;
  1849. this.w *= otherVector.w;
  1850. return this;
  1851. };
  1852. /**
  1853. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the passed one.
  1854. */
  1855. Vector4.prototype.multiply = function (otherVector) {
  1856. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  1857. };
  1858. /**
  1859. * Updates the passed vector "result" with the multiplication result of the current Vector4 and the passed one.
  1860. * Returns the current Vector4.
  1861. */
  1862. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  1863. result.x = this.x * otherVector.x;
  1864. result.y = this.y * otherVector.y;
  1865. result.z = this.z * otherVector.z;
  1866. result.w = this.w * otherVector.w;
  1867. return this;
  1868. };
  1869. /**
  1870. * Returns a new Vector4 set with the multiplication result of the passed floats and the current Vector4 coordinates.
  1871. */
  1872. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  1873. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  1874. };
  1875. /**
  1876. * Returns a new Vector4 set with the division result of the current Vector4 by the passed one.
  1877. */
  1878. Vector4.prototype.divide = function (otherVector) {
  1879. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  1880. };
  1881. /**
  1882. * Updates the passed vector "result" with the division result of the current Vector4 by the passed one.
  1883. * Returns the current Vector4.
  1884. */
  1885. Vector4.prototype.divideToRef = function (otherVector, result) {
  1886. result.x = this.x / otherVector.x;
  1887. result.y = this.y / otherVector.y;
  1888. result.z = this.z / otherVector.z;
  1889. result.w = this.w / otherVector.w;
  1890. return this;
  1891. };
  1892. /**
  1893. * Updates the Vector4 coordinates with the minimum values between its own and the passed vector ones.
  1894. */
  1895. Vector4.prototype.MinimizeInPlace = function (other) {
  1896. if (other.x < this.x)
  1897. this.x = other.x;
  1898. if (other.y < this.y)
  1899. this.y = other.y;
  1900. if (other.z < this.z)
  1901. this.z = other.z;
  1902. if (other.w < this.w)
  1903. this.w = other.w;
  1904. return this;
  1905. };
  1906. /**
  1907. * Updates the Vector4 coordinates with the maximum values between its own and the passed vector ones.
  1908. */
  1909. Vector4.prototype.MaximizeInPlace = function (other) {
  1910. if (other.x > this.x)
  1911. this.x = other.x;
  1912. if (other.y > this.y)
  1913. this.y = other.y;
  1914. if (other.z > this.z)
  1915. this.z = other.z;
  1916. if (other.w > this.w)
  1917. this.w = other.w;
  1918. return this;
  1919. };
  1920. // Properties
  1921. /**
  1922. * Returns the Vector4 length (float).
  1923. */
  1924. Vector4.prototype.length = function () {
  1925. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1926. };
  1927. /**
  1928. * Returns the Vector4 squared length (float).
  1929. */
  1930. Vector4.prototype.lengthSquared = function () {
  1931. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  1932. };
  1933. // Methods
  1934. /**
  1935. * Normalizes in place the Vector4.
  1936. * Returns the updated Vector4.
  1937. */
  1938. Vector4.prototype.normalize = function () {
  1939. var len = this.length();
  1940. if (len === 0)
  1941. return this;
  1942. var num = 1.0 / len;
  1943. this.x *= num;
  1944. this.y *= num;
  1945. this.z *= num;
  1946. this.w *= num;
  1947. return this;
  1948. };
  1949. /**
  1950. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  1951. */
  1952. Vector4.prototype.toVector3 = function () {
  1953. return new Vector3(this.x, this.y, this.z);
  1954. };
  1955. /**
  1956. * Returns a new Vector4 copied from the current one.
  1957. */
  1958. Vector4.prototype.clone = function () {
  1959. return new Vector4(this.x, this.y, this.z, this.w);
  1960. };
  1961. /**
  1962. * Updates the current Vector4 with the passed one coordinates.
  1963. * Returns the updated Vector4.
  1964. */
  1965. Vector4.prototype.copyFrom = function (source) {
  1966. this.x = source.x;
  1967. this.y = source.y;
  1968. this.z = source.z;
  1969. this.w = source.w;
  1970. return this;
  1971. };
  1972. /**
  1973. * Updates the current Vector4 coordinates with the passed floats.
  1974. * Returns the updated Vector4.
  1975. */
  1976. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  1977. this.x = x;
  1978. this.y = y;
  1979. this.z = z;
  1980. this.w = w;
  1981. return this;
  1982. };
  1983. /**
  1984. * Updates the current Vector4 coordinates with the passed floats.
  1985. * Returns the updated Vector4.
  1986. */
  1987. Vector4.prototype.set = function (x, y, z, w) {
  1988. return this.copyFromFloats(x, y, z, w);
  1989. };
  1990. // Statics
  1991. /**
  1992. * Returns a new Vector4 set from the starting index of the passed array.
  1993. */
  1994. Vector4.FromArray = function (array, offset) {
  1995. if (!offset) {
  1996. offset = 0;
  1997. }
  1998. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  1999. };
  2000. /**
  2001. * Updates the passed vector "result" from the starting index of the passed array.
  2002. */
  2003. Vector4.FromArrayToRef = function (array, offset, result) {
  2004. result.x = array[offset];
  2005. result.y = array[offset + 1];
  2006. result.z = array[offset + 2];
  2007. result.w = array[offset + 3];
  2008. };
  2009. /**
  2010. * Updates the passed vector "result" from the starting index of the passed Float32Array.
  2011. */
  2012. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  2013. Vector4.FromArrayToRef(array, offset, result);
  2014. };
  2015. /**
  2016. * Updates the passed vector "result" coordinates from the passed floats.
  2017. */
  2018. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  2019. result.x = x;
  2020. result.y = y;
  2021. result.z = z;
  2022. result.w = w;
  2023. };
  2024. /**
  2025. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  2026. */
  2027. Vector4.Zero = function () {
  2028. return new Vector4(0.0, 0.0, 0.0, 0.0);
  2029. };
  2030. /**
  2031. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  2032. */
  2033. Vector4.One = function () {
  2034. return new Vector4(1.0, 1.0, 1.0, 1.0);
  2035. };
  2036. /**
  2037. * Returns a new normalized Vector4 from the passed one.
  2038. */
  2039. Vector4.Normalize = function (vector) {
  2040. var result = Vector4.Zero();
  2041. Vector4.NormalizeToRef(vector, result);
  2042. return result;
  2043. };
  2044. /**
  2045. * Updates the passed vector "result" from the normalization of the passed one.
  2046. */
  2047. Vector4.NormalizeToRef = function (vector, result) {
  2048. result.copyFrom(vector);
  2049. result.normalize();
  2050. };
  2051. Vector4.Minimize = function (left, right) {
  2052. var min = left.clone();
  2053. min.MinimizeInPlace(right);
  2054. return min;
  2055. };
  2056. Vector4.Maximize = function (left, right) {
  2057. var max = left.clone();
  2058. max.MaximizeInPlace(right);
  2059. return max;
  2060. };
  2061. /**
  2062. * Returns the distance (float) between the vectors "value1" and "value2".
  2063. */
  2064. Vector4.Distance = function (value1, value2) {
  2065. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  2066. };
  2067. /**
  2068. * Returns the squared distance (float) between the vectors "value1" and "value2".
  2069. */
  2070. Vector4.DistanceSquared = function (value1, value2) {
  2071. var x = value1.x - value2.x;
  2072. var y = value1.y - value2.y;
  2073. var z = value1.z - value2.z;
  2074. var w = value1.w - value2.w;
  2075. return (x * x) + (y * y) + (z * z) + (w * w);
  2076. };
  2077. /**
  2078. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  2079. */
  2080. Vector4.Center = function (value1, value2) {
  2081. var center = value1.add(value2);
  2082. center.scaleInPlace(0.5);
  2083. return center;
  2084. };
  2085. /**
  2086. * Returns a new Vector4 set with the result of the normal transformation by the passed matrix of the passed vector.
  2087. * This methods computes transformed normalized direction vectors only.
  2088. */
  2089. Vector4.TransformNormal = function (vector, transformation) {
  2090. var result = Vector4.Zero();
  2091. Vector4.TransformNormalToRef(vector, transformation, result);
  2092. return result;
  2093. };
  2094. /**
  2095. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed vector.
  2096. * This methods computes transformed normalized direction vectors only.
  2097. */
  2098. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  2099. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  2100. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  2101. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  2102. result.x = x;
  2103. result.y = y;
  2104. result.z = z;
  2105. result.w = vector.w;
  2106. };
  2107. /**
  2108. * Sets the passed vector "result" with the result of the normal transformation by the passed matrix of the passed floats (x, y, z, w).
  2109. * This methods computes transformed normalized direction vectors only.
  2110. */
  2111. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  2112. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  2113. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  2114. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  2115. result.w = w;
  2116. };
  2117. return Vector4;
  2118. }());
  2119. BABYLON.Vector4 = Vector4;
  2120. var Size = (function () {
  2121. /**
  2122. * Creates a Size object from the passed width and height (floats).
  2123. */
  2124. function Size(width, height) {
  2125. this.width = width;
  2126. this.height = height;
  2127. }
  2128. // Returns a string with the Size width and height.
  2129. Size.prototype.toString = function () {
  2130. return "{W: " + this.width + ", H: " + this.height + "}";
  2131. };
  2132. /**
  2133. * Returns the string "Size"
  2134. */
  2135. Size.prototype.getClassName = function () {
  2136. return "Size";
  2137. };
  2138. /**
  2139. * Returns the Size hash code.
  2140. */
  2141. Size.prototype.getHashCode = function () {
  2142. var hash = this.width || 0;
  2143. hash = (hash * 397) ^ (this.height || 0);
  2144. return hash;
  2145. };
  2146. /**
  2147. * Updates the current size from the passed one.
  2148. * Returns the updated Size.
  2149. */
  2150. Size.prototype.copyFrom = function (src) {
  2151. this.width = src.width;
  2152. this.height = src.height;
  2153. };
  2154. /**
  2155. * Updates in place the current Size from the passed floats.
  2156. * Returns the updated Size.
  2157. */
  2158. Size.prototype.copyFromFloats = function (width, height) {
  2159. this.width = width;
  2160. this.height = height;
  2161. return this;
  2162. };
  2163. /**
  2164. * Updates in place the current Size from the passed floats.
  2165. * Returns the updated Size.
  2166. */
  2167. Size.prototype.set = function (width, height) {
  2168. return this.copyFromFloats(width, height);
  2169. };
  2170. /**
  2171. * Returns a new Size set with the multiplication result of the current Size and the passed floats.
  2172. */
  2173. Size.prototype.multiplyByFloats = function (w, h) {
  2174. return new Size(this.width * w, this.height * h);
  2175. };
  2176. /**
  2177. * Returns a new Size copied from the passed one.
  2178. */
  2179. Size.prototype.clone = function () {
  2180. return new Size(this.width, this.height);
  2181. };
  2182. /**
  2183. * Boolean : True if the current Size and the passed one width and height are strictly equal.
  2184. */
  2185. Size.prototype.equals = function (other) {
  2186. if (!other) {
  2187. return false;
  2188. }
  2189. return (this.width === other.width) && (this.height === other.height);
  2190. };
  2191. Object.defineProperty(Size.prototype, "surface", {
  2192. /**
  2193. * Returns the surface of the Size : width * height (float).
  2194. */
  2195. get: function () {
  2196. return this.width * this.height;
  2197. },
  2198. enumerable: true,
  2199. configurable: true
  2200. });
  2201. /**
  2202. * Returns a new Size set to (0.0, 0.0)
  2203. */
  2204. Size.Zero = function () {
  2205. return new Size(0.0, 0.0);
  2206. };
  2207. /**
  2208. * Returns a new Size set as the addition result of the current Size and the passed one.
  2209. */
  2210. Size.prototype.add = function (otherSize) {
  2211. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  2212. return r;
  2213. };
  2214. /**
  2215. * Returns a new Size set as the subtraction result of the passed one from the current Size.
  2216. */
  2217. Size.prototype.subtract = function (otherSize) {
  2218. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  2219. return r;
  2220. };
  2221. /**
  2222. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  2223. */
  2224. Size.Lerp = function (start, end, amount) {
  2225. var w = start.width + ((end.width - start.width) * amount);
  2226. var h = start.height + ((end.height - start.height) * amount);
  2227. return new Size(w, h);
  2228. };
  2229. return Size;
  2230. }());
  2231. BABYLON.Size = Size;
  2232. var Quaternion = (function () {
  2233. /**
  2234. * Creates a new Quaternion from the passed floats.
  2235. */
  2236. function Quaternion(x, y, z, w) {
  2237. if (x === void 0) { x = 0.0; }
  2238. if (y === void 0) { y = 0.0; }
  2239. if (z === void 0) { z = 0.0; }
  2240. if (w === void 0) { w = 1.0; }
  2241. this.x = x;
  2242. this.y = y;
  2243. this.z = z;
  2244. this.w = w;
  2245. }
  2246. /**
  2247. * Returns a string with the Quaternion coordinates.
  2248. */
  2249. Quaternion.prototype.toString = function () {
  2250. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  2251. };
  2252. /**
  2253. * Returns the string "Quaternion".
  2254. */
  2255. Quaternion.prototype.getClassName = function () {
  2256. return "Quaternion";
  2257. };
  2258. /**
  2259. * Returns the Quaternion hash code.
  2260. */
  2261. Quaternion.prototype.getHashCode = function () {
  2262. var hash = this.x || 0;
  2263. hash = (hash * 397) ^ (this.y || 0);
  2264. hash = (hash * 397) ^ (this.z || 0);
  2265. hash = (hash * 397) ^ (this.w || 0);
  2266. return hash;
  2267. };
  2268. /**
  2269. * Returns a new array populated with 4 elements : the Quaternion coordinates.
  2270. */
  2271. Quaternion.prototype.asArray = function () {
  2272. return [this.x, this.y, this.z, this.w];
  2273. };
  2274. /**
  2275. * Boolean : True if the current Quaterion and the passed one coordinates are strictly equal.
  2276. */
  2277. Quaternion.prototype.equals = function (otherQuaternion) {
  2278. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  2279. };
  2280. /**
  2281. * Returns a new Quaternion copied from the current one.
  2282. */
  2283. Quaternion.prototype.clone = function () {
  2284. return new Quaternion(this.x, this.y, this.z, this.w);
  2285. };
  2286. /**
  2287. * Updates the current Quaternion from the passed one coordinates.
  2288. * Returns the updated Quaterion.
  2289. */
  2290. Quaternion.prototype.copyFrom = function (other) {
  2291. this.x = other.x;
  2292. this.y = other.y;
  2293. this.z = other.z;
  2294. this.w = other.w;
  2295. return this;
  2296. };
  2297. /**
  2298. * Updates the current Quaternion from the passed float coordinates.
  2299. * Returns the updated Quaterion.
  2300. */
  2301. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  2302. this.x = x;
  2303. this.y = y;
  2304. this.z = z;
  2305. this.w = w;
  2306. return this;
  2307. };
  2308. /**
  2309. * Updates the current Quaternion from the passed float coordinates.
  2310. * Returns the updated Quaterion.
  2311. */
  2312. Quaternion.prototype.set = function (x, y, z, w) {
  2313. return this.copyFromFloats(x, y, z, w);
  2314. };
  2315. /**
  2316. * Returns a new Quaternion as the addition result of the passed one and the current Quaternion.
  2317. */
  2318. Quaternion.prototype.add = function (other) {
  2319. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  2320. };
  2321. /**
  2322. * Returns a new Quaternion as the subtraction result of the passed one from the current Quaternion.
  2323. */
  2324. Quaternion.prototype.subtract = function (other) {
  2325. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  2326. };
  2327. /**
  2328. * Returns a new Quaternion set by multiplying the current Quaterion coordinates by the float "scale".
  2329. */
  2330. Quaternion.prototype.scale = function (value) {
  2331. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  2332. };
  2333. /**
  2334. * Returns a new Quaternion set as the quaternion mulplication result of the current one with the passed one "q1".
  2335. */
  2336. Quaternion.prototype.multiply = function (q1) {
  2337. var result = new Quaternion(0, 0, 0, 1.0);
  2338. this.multiplyToRef(q1, result);
  2339. return result;
  2340. };
  2341. /**
  2342. * Sets the passed "result" as the quaternion mulplication result of the current one with the passed one "q1".
  2343. * Returns the current Quaternion.
  2344. */
  2345. Quaternion.prototype.multiplyToRef = function (q1, result) {
  2346. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  2347. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  2348. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  2349. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  2350. result.copyFromFloats(x, y, z, w);
  2351. return this;
  2352. };
  2353. /**
  2354. * Updates the current Quaternion with the quaternion mulplication result of itself with the passed one "q1".
  2355. * Returns the updated Quaternion.
  2356. */
  2357. Quaternion.prototype.multiplyInPlace = function (q1) {
  2358. this.multiplyToRef(q1, this);
  2359. return this;
  2360. };
  2361. /**
  2362. * Sets the passed "ref" with the conjugation of the current Quaternion.
  2363. * Returns the current Quaternion.
  2364. */
  2365. Quaternion.prototype.conjugateToRef = function (ref) {
  2366. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  2367. return this;
  2368. };
  2369. /**
  2370. * Conjugates in place the current Quaternion.
  2371. * Returns the updated Quaternion.
  2372. */
  2373. Quaternion.prototype.conjugateInPlace = function () {
  2374. this.x *= -1;
  2375. this.y *= -1;
  2376. this.z *= -1;
  2377. return this;
  2378. };
  2379. /**
  2380. * Returns a new Quaternion as the conjugate of the current Quaternion.
  2381. */
  2382. Quaternion.prototype.conjugate = function () {
  2383. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  2384. return result;
  2385. };
  2386. /**
  2387. * Returns the Quaternion length (float).
  2388. */
  2389. Quaternion.prototype.length = function () {
  2390. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  2391. };
  2392. /**
  2393. * Normalize in place the current Quaternion.
  2394. * Returns the updated Quaternion.
  2395. */
  2396. Quaternion.prototype.normalize = function () {
  2397. var length = 1.0 / this.length();
  2398. this.x *= length;
  2399. this.y *= length;
  2400. this.z *= length;
  2401. this.w *= length;
  2402. return this;
  2403. };
  2404. /**
  2405. * Returns a new Vector3 set with the Euler angles translated from the current Quaternion.
  2406. */
  2407. Quaternion.prototype.toEulerAngles = function (order) {
  2408. if (order === void 0) { order = "YZX"; }
  2409. var result = Vector3.Zero();
  2410. this.toEulerAnglesToRef(result, order);
  2411. return result;
  2412. };
  2413. /**
  2414. * Sets the passed vector3 "result" with the Euler angles translated from the current Quaternion.
  2415. * Returns the current Quaternion.
  2416. */
  2417. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  2418. if (order === void 0) { order = "YZX"; }
  2419. var qz = this.z;
  2420. var qx = this.x;
  2421. var qy = this.y;
  2422. var qw = this.w;
  2423. var sqw = qw * qw;
  2424. var sqz = qz * qz;
  2425. var sqx = qx * qx;
  2426. var sqy = qy * qy;
  2427. var zAxisY = qy * qz - qx * qw;
  2428. var limit = .4999999;
  2429. if (zAxisY < -limit) {
  2430. result.y = 2 * Math.atan2(qy, qw);
  2431. result.x = Math.PI / 2;
  2432. result.z = 0;
  2433. }
  2434. else if (zAxisY > limit) {
  2435. result.y = 2 * Math.atan2(qy, qw);
  2436. result.x = -Math.PI / 2;
  2437. result.z = 0;
  2438. }
  2439. else {
  2440. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  2441. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  2442. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  2443. }
  2444. return this;
  2445. };
  2446. /**
  2447. * Updates the passed rotation matrix with the current Quaternion values.
  2448. * Returns the current Quaternion.
  2449. */
  2450. Quaternion.prototype.toRotationMatrix = function (result) {
  2451. var xx = this.x * this.x;
  2452. var yy = this.y * this.y;
  2453. var zz = this.z * this.z;
  2454. var xy = this.x * this.y;
  2455. var zw = this.z * this.w;
  2456. var zx = this.z * this.x;
  2457. var yw = this.y * this.w;
  2458. var yz = this.y * this.z;
  2459. var xw = this.x * this.w;
  2460. result.m[0] = 1.0 - (2.0 * (yy + zz));
  2461. result.m[1] = 2.0 * (xy + zw);
  2462. result.m[2] = 2.0 * (zx - yw);
  2463. result.m[3] = 0;
  2464. result.m[4] = 2.0 * (xy - zw);
  2465. result.m[5] = 1.0 - (2.0 * (zz + xx));
  2466. result.m[6] = 2.0 * (yz + xw);
  2467. result.m[7] = 0;
  2468. result.m[8] = 2.0 * (zx + yw);
  2469. result.m[9] = 2.0 * (yz - xw);
  2470. result.m[10] = 1.0 - (2.0 * (yy + xx));
  2471. result.m[11] = 0;
  2472. result.m[12] = 0;
  2473. result.m[13] = 0;
  2474. result.m[14] = 0;
  2475. result.m[15] = 1.0;
  2476. result._markAsUpdated();
  2477. return this;
  2478. };
  2479. /**
  2480. * Updates the current Quaternion from the passed rotation matrix values.
  2481. * Returns the updated Quaternion.
  2482. */
  2483. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  2484. Quaternion.FromRotationMatrixToRef(matrix, this);
  2485. return this;
  2486. };
  2487. // Statics
  2488. /**
  2489. * Returns a new Quaternion set from the passed rotation matrix values.
  2490. */
  2491. Quaternion.FromRotationMatrix = function (matrix) {
  2492. var result = new Quaternion();
  2493. Quaternion.FromRotationMatrixToRef(matrix, result);
  2494. return result;
  2495. };
  2496. /**
  2497. * Updates the passed quaternion "result" with the passed rotation matrix values.
  2498. */
  2499. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  2500. var data = matrix.m;
  2501. var m11 = data[0], m12 = data[4], m13 = data[8];
  2502. var m21 = data[1], m22 = data[5], m23 = data[9];
  2503. var m31 = data[2], m32 = data[6], m33 = data[10];
  2504. var trace = m11 + m22 + m33;
  2505. var s;
  2506. if (trace > 0) {
  2507. s = 0.5 / Math.sqrt(trace + 1.0);
  2508. result.w = 0.25 / s;
  2509. result.x = (m32 - m23) * s;
  2510. result.y = (m13 - m31) * s;
  2511. result.z = (m21 - m12) * s;
  2512. }
  2513. else if (m11 > m22 && m11 > m33) {
  2514. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  2515. result.w = (m32 - m23) / s;
  2516. result.x = 0.25 * s;
  2517. result.y = (m12 + m21) / s;
  2518. result.z = (m13 + m31) / s;
  2519. }
  2520. else if (m22 > m33) {
  2521. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  2522. result.w = (m13 - m31) / s;
  2523. result.x = (m12 + m21) / s;
  2524. result.y = 0.25 * s;
  2525. result.z = (m23 + m32) / s;
  2526. }
  2527. else {
  2528. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  2529. result.w = (m21 - m12) / s;
  2530. result.x = (m13 + m31) / s;
  2531. result.y = (m23 + m32) / s;
  2532. result.z = 0.25 * s;
  2533. }
  2534. };
  2535. /**
  2536. * Returns a new Quaternion set to (0.0, 0.0, 0.0).
  2537. */
  2538. Quaternion.Zero = function () {
  2539. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  2540. };
  2541. /**
  2542. * Returns a new Quaternion as the inverted current Quaternion.
  2543. */
  2544. Quaternion.Inverse = function (q) {
  2545. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  2546. };
  2547. /**
  2548. * Returns the identity Quaternion.
  2549. */
  2550. Quaternion.Identity = function () {
  2551. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  2552. };
  2553. Quaternion.IsIdentity = function (quaternion) {
  2554. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  2555. };
  2556. /**
  2557. * Returns a new Quaternion set from the passed axis (Vector3) and angle in radians (float).
  2558. */
  2559. Quaternion.RotationAxis = function (axis, angle) {
  2560. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  2561. };
  2562. /**
  2563. * Sets the passed quaternion "result" from the passed axis (Vector3) and angle in radians (float).
  2564. */
  2565. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  2566. var sin = Math.sin(angle / 2);
  2567. axis.normalize();
  2568. result.w = Math.cos(angle / 2);
  2569. result.x = axis.x * sin;
  2570. result.y = axis.y * sin;
  2571. result.z = axis.z * sin;
  2572. return result;
  2573. };
  2574. /**
  2575. * Retuns a new Quaternion set from the starting index of the passed array.
  2576. */
  2577. Quaternion.FromArray = function (array, offset) {
  2578. if (!offset) {
  2579. offset = 0;
  2580. }
  2581. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2582. };
  2583. /**
  2584. * Returns a new Quaternion set from the passed Euler float angles (y, x, z).
  2585. */
  2586. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  2587. var q = new Quaternion();
  2588. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  2589. return q;
  2590. };
  2591. /**
  2592. * Sets the passed quaternion "result" from the passed float Euler angles (y, x, z).
  2593. */
  2594. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  2595. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  2596. var halfRoll = roll * 0.5;
  2597. var halfPitch = pitch * 0.5;
  2598. var halfYaw = yaw * 0.5;
  2599. var sinRoll = Math.sin(halfRoll);
  2600. var cosRoll = Math.cos(halfRoll);
  2601. var sinPitch = Math.sin(halfPitch);
  2602. var cosPitch = Math.cos(halfPitch);
  2603. var sinYaw = Math.sin(halfYaw);
  2604. var cosYaw = Math.cos(halfYaw);
  2605. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  2606. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  2607. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  2608. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  2609. };
  2610. /**
  2611. * Returns a new Quaternion from the passed float Euler angles expressed in z-x-z orientation
  2612. */
  2613. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  2614. var result = new Quaternion();
  2615. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  2616. return result;
  2617. };
  2618. /**
  2619. * Sets the passed quaternion "result" from the passed float Euler angles expressed in z-x-z orientation
  2620. */
  2621. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  2622. // Produces a quaternion from Euler angles in the z-x-z orientation
  2623. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  2624. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  2625. var halfBeta = beta * 0.5;
  2626. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2627. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  2628. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2629. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  2630. };
  2631. /**
  2632. * Returns a new Quaternion as the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2633. * cf to Vector3.RotationFromAxis() documentation.
  2634. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2635. */
  2636. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3, ref) {
  2637. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  2638. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  2639. return quat;
  2640. };
  2641. /**
  2642. * Sets the passed quaternion "ref" with the quaternion rotation value to reach the target (axis1, axis2, axis3) orientation as a rotated XYZ system.
  2643. * cf to Vector3.RotationFromAxis() documentation.
  2644. * Note : axis1, axis2 and axis3 are normalized during this operation.
  2645. */
  2646. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  2647. var rotMat = MathTmp.Matrix[0];
  2648. BABYLON.Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  2649. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, ref);
  2650. };
  2651. Quaternion.Slerp = function (left, right, amount) {
  2652. var result = Quaternion.Identity();
  2653. Quaternion.SlerpToRef(left, right, amount, result);
  2654. return result;
  2655. };
  2656. Quaternion.SlerpToRef = function (left, right, amount, result) {
  2657. var num2;
  2658. var num3;
  2659. var num = amount;
  2660. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  2661. var flag = false;
  2662. if (num4 < 0) {
  2663. flag = true;
  2664. num4 = -num4;
  2665. }
  2666. if (num4 > 0.999999) {
  2667. num3 = 1 - num;
  2668. num2 = flag ? -num : num;
  2669. }
  2670. else {
  2671. var num5 = Math.acos(num4);
  2672. var num6 = (1.0 / Math.sin(num5));
  2673. num3 = (Math.sin((1.0 - num) * num5)) * num6;
  2674. num2 = flag ? ((-Math.sin(num * num5)) * num6) : ((Math.sin(num * num5)) * num6);
  2675. }
  2676. result.x = (num3 * left.x) + (num2 * right.x);
  2677. result.y = (num3 * left.y) + (num2 * right.y);
  2678. result.z = (num3 * left.z) + (num2 * right.z);
  2679. result.w = (num3 * left.w) + (num2 * right.w);
  2680. };
  2681. /**
  2682. * Returns a new Quaternion located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2".
  2683. */
  2684. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2685. var squared = amount * amount;
  2686. var cubed = amount * squared;
  2687. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2688. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2689. var part3 = (cubed - (2.0 * squared)) + amount;
  2690. var part4 = cubed - squared;
  2691. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2692. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2693. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  2694. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  2695. return new Quaternion(x, y, z, w);
  2696. };
  2697. return Quaternion;
  2698. }());
  2699. BABYLON.Quaternion = Quaternion;
  2700. var Matrix = (function () {
  2701. function Matrix() {
  2702. this._isIdentity = false;
  2703. this._isIdentityDirty = true;
  2704. this.m = new Float32Array(16);
  2705. this._markAsUpdated();
  2706. }
  2707. Matrix.prototype._markAsUpdated = function () {
  2708. this.updateFlag = Matrix._updateFlagSeed++;
  2709. this._isIdentityDirty = true;
  2710. };
  2711. // Properties
  2712. /**
  2713. * Boolean : True is the matrix is the identity matrix
  2714. */
  2715. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  2716. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  2717. if (this._isIdentityDirty) {
  2718. this._isIdentityDirty = false;
  2719. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  2720. this._isIdentity = false;
  2721. }
  2722. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  2723. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  2724. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  2725. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  2726. this._isIdentity = false;
  2727. }
  2728. else {
  2729. this._isIdentity = true;
  2730. }
  2731. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  2732. this._isIdentity = false;
  2733. }
  2734. }
  2735. return this._isIdentity;
  2736. };
  2737. /**
  2738. * Returns the matrix determinant (float).
  2739. */
  2740. Matrix.prototype.determinant = function () {
  2741. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  2742. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  2743. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  2744. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  2745. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  2746. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  2747. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  2748. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  2749. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  2750. };
  2751. // Methods
  2752. /**
  2753. * Returns the matrix underlying array.
  2754. */
  2755. Matrix.prototype.toArray = function () {
  2756. return this.m;
  2757. };
  2758. /**
  2759. * Returns the matrix underlying array.
  2760. */
  2761. Matrix.prototype.asArray = function () {
  2762. return this.toArray();
  2763. };
  2764. /**
  2765. * Inverts in place the Matrix.
  2766. * Returns the Matrix inverted.
  2767. */
  2768. Matrix.prototype.invert = function () {
  2769. this.invertToRef(this);
  2770. return this;
  2771. };
  2772. /**
  2773. * Sets all the matrix elements to zero.
  2774. * Returns the Matrix.
  2775. */
  2776. Matrix.prototype.reset = function () {
  2777. for (var index = 0; index < 16; index++) {
  2778. this.m[index] = 0.0;
  2779. }
  2780. this._markAsUpdated();
  2781. return this;
  2782. };
  2783. /**
  2784. * Returns a new Matrix as the addition result of the current Matrix and the passed one.
  2785. */
  2786. Matrix.prototype.add = function (other) {
  2787. var result = new Matrix();
  2788. this.addToRef(other, result);
  2789. return result;
  2790. };
  2791. /**
  2792. * Sets the passed matrix "result" with the ddition result of the current Matrix and the passed one.
  2793. * Returns the Matrix.
  2794. */
  2795. Matrix.prototype.addToRef = function (other, result) {
  2796. for (var index = 0; index < 16; index++) {
  2797. result.m[index] = this.m[index] + other.m[index];
  2798. }
  2799. result._markAsUpdated();
  2800. return this;
  2801. };
  2802. /**
  2803. * Adds in place the passed matrix to the current Matrix.
  2804. * Returns the updated Matrix.
  2805. */
  2806. Matrix.prototype.addToSelf = function (other) {
  2807. for (var index = 0; index < 16; index++) {
  2808. this.m[index] += other.m[index];
  2809. }
  2810. this._markAsUpdated();
  2811. return this;
  2812. };
  2813. /**
  2814. * Sets the passed matrix with the current inverted Matrix.
  2815. * Returns the unmodified current Matrix.
  2816. */
  2817. Matrix.prototype.invertToRef = function (other) {
  2818. var l1 = this.m[0];
  2819. var l2 = this.m[1];
  2820. var l3 = this.m[2];
  2821. var l4 = this.m[3];
  2822. var l5 = this.m[4];
  2823. var l6 = this.m[5];
  2824. var l7 = this.m[6];
  2825. var l8 = this.m[7];
  2826. var l9 = this.m[8];
  2827. var l10 = this.m[9];
  2828. var l11 = this.m[10];
  2829. var l12 = this.m[11];
  2830. var l13 = this.m[12];
  2831. var l14 = this.m[13];
  2832. var l15 = this.m[14];
  2833. var l16 = this.m[15];
  2834. var l17 = (l11 * l16) - (l12 * l15);
  2835. var l18 = (l10 * l16) - (l12 * l14);
  2836. var l19 = (l10 * l15) - (l11 * l14);
  2837. var l20 = (l9 * l16) - (l12 * l13);
  2838. var l21 = (l9 * l15) - (l11 * l13);
  2839. var l22 = (l9 * l14) - (l10 * l13);
  2840. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  2841. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  2842. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  2843. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  2844. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  2845. var l28 = (l7 * l16) - (l8 * l15);
  2846. var l29 = (l6 * l16) - (l8 * l14);
  2847. var l30 = (l6 * l15) - (l7 * l14);
  2848. var l31 = (l5 * l16) - (l8 * l13);
  2849. var l32 = (l5 * l15) - (l7 * l13);
  2850. var l33 = (l5 * l14) - (l6 * l13);
  2851. var l34 = (l7 * l12) - (l8 * l11);
  2852. var l35 = (l6 * l12) - (l8 * l10);
  2853. var l36 = (l6 * l11) - (l7 * l10);
  2854. var l37 = (l5 * l12) - (l8 * l9);
  2855. var l38 = (l5 * l11) - (l7 * l9);
  2856. var l39 = (l5 * l10) - (l6 * l9);
  2857. other.m[0] = l23 * l27;
  2858. other.m[4] = l24 * l27;
  2859. other.m[8] = l25 * l27;
  2860. other.m[12] = l26 * l27;
  2861. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  2862. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  2863. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  2864. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  2865. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  2866. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  2867. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  2868. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  2869. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  2870. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  2871. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  2872. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  2873. other._markAsUpdated();
  2874. return this;
  2875. };
  2876. /**
  2877. * Inserts the translation vector (using 3 x floats) in the current Matrix.
  2878. * Returns the updated Matrix.
  2879. */
  2880. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  2881. this.m[12] = x;
  2882. this.m[13] = y;
  2883. this.m[14] = z;
  2884. this._markAsUpdated();
  2885. return this;
  2886. };
  2887. /**
  2888. * Inserts the translation vector in the current Matrix.
  2889. * Returns the updated Matrix.
  2890. */
  2891. Matrix.prototype.setTranslation = function (vector3) {
  2892. this.m[12] = vector3.x;
  2893. this.m[13] = vector3.y;
  2894. this.m[14] = vector3.z;
  2895. this._markAsUpdated();
  2896. return this;
  2897. };
  2898. /**
  2899. * Returns a new Vector3 as the extracted translation from the Matrix.
  2900. */
  2901. Matrix.prototype.getTranslation = function () {
  2902. return new Vector3(this.m[12], this.m[13], this.m[14]);
  2903. };
  2904. /**
  2905. * Fill a Vector3 with the extracted translation from the Matrix.
  2906. */
  2907. Matrix.prototype.getTranslationToRef = function (result) {
  2908. result.x = this.m[12];
  2909. result.y = this.m[13];
  2910. result.z = this.m[14];
  2911. return this;
  2912. };
  2913. /**
  2914. * Remove rotation and scaling part from the Matrix.
  2915. * Returns the updated Matrix.
  2916. */
  2917. Matrix.prototype.removeRotationAndScaling = function () {
  2918. this.setRowFromFloats(0, 1, 0, 0, 0);
  2919. this.setRowFromFloats(1, 0, 1, 0, 0);
  2920. this.setRowFromFloats(2, 0, 0, 1, 0);
  2921. return this;
  2922. };
  2923. /**
  2924. * Returns a new Matrix set with the multiplication result of the current Matrix and the passed one.
  2925. */
  2926. Matrix.prototype.multiply = function (other) {
  2927. var result = new Matrix();
  2928. this.multiplyToRef(other, result);
  2929. return result;
  2930. };
  2931. /**
  2932. * Updates the current Matrix from the passed one values.
  2933. * Returns the updated Matrix.
  2934. */
  2935. Matrix.prototype.copyFrom = function (other) {
  2936. for (var index = 0; index < 16; index++) {
  2937. this.m[index] = other.m[index];
  2938. }
  2939. this._markAsUpdated();
  2940. return this;
  2941. };
  2942. /**
  2943. * Populates the passed array from the starting index with the Matrix values.
  2944. * Returns the Matrix.
  2945. */
  2946. Matrix.prototype.copyToArray = function (array, offset) {
  2947. if (offset === void 0) { offset = 0; }
  2948. for (var index = 0; index < 16; index++) {
  2949. array[offset + index] = this.m[index];
  2950. }
  2951. return this;
  2952. };
  2953. /**
  2954. * Sets the passed matrix "result" with the multiplication result of the current Matrix and the passed one.
  2955. */
  2956. Matrix.prototype.multiplyToRef = function (other, result) {
  2957. this.multiplyToArray(other, result.m, 0);
  2958. result._markAsUpdated();
  2959. return this;
  2960. };
  2961. /**
  2962. * Sets the Float32Array "result" from the passed index "offset" with the multiplication result of the current Matrix and the passed one.
  2963. */
  2964. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  2965. var tm0 = this.m[0];
  2966. var tm1 = this.m[1];
  2967. var tm2 = this.m[2];
  2968. var tm3 = this.m[3];
  2969. var tm4 = this.m[4];
  2970. var tm5 = this.m[5];
  2971. var tm6 = this.m[6];
  2972. var tm7 = this.m[7];
  2973. var tm8 = this.m[8];
  2974. var tm9 = this.m[9];
  2975. var tm10 = this.m[10];
  2976. var tm11 = this.m[11];
  2977. var tm12 = this.m[12];
  2978. var tm13 = this.m[13];
  2979. var tm14 = this.m[14];
  2980. var tm15 = this.m[15];
  2981. var om0 = other.m[0];
  2982. var om1 = other.m[1];
  2983. var om2 = other.m[2];
  2984. var om3 = other.m[3];
  2985. var om4 = other.m[4];
  2986. var om5 = other.m[5];
  2987. var om6 = other.m[6];
  2988. var om7 = other.m[7];
  2989. var om8 = other.m[8];
  2990. var om9 = other.m[9];
  2991. var om10 = other.m[10];
  2992. var om11 = other.m[11];
  2993. var om12 = other.m[12];
  2994. var om13 = other.m[13];
  2995. var om14 = other.m[14];
  2996. var om15 = other.m[15];
  2997. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  2998. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  2999. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  3000. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  3001. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  3002. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  3003. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  3004. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  3005. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  3006. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  3007. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  3008. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  3009. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  3010. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  3011. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  3012. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  3013. return this;
  3014. };
  3015. /**
  3016. * Boolean : True is the current Matrix and the passed one values are strictly equal.
  3017. */
  3018. Matrix.prototype.equals = function (value) {
  3019. return value &&
  3020. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  3021. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  3022. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  3023. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  3024. };
  3025. /**
  3026. * Returns a new Matrix from the current Matrix.
  3027. */
  3028. Matrix.prototype.clone = function () {
  3029. 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]);
  3030. };
  3031. /**
  3032. * Returns the string "Matrix"
  3033. */
  3034. Matrix.prototype.getClassName = function () {
  3035. return "Matrix";
  3036. };
  3037. /**
  3038. * Returns the Matrix hash code.
  3039. */
  3040. Matrix.prototype.getHashCode = function () {
  3041. var hash = this.m[0] || 0;
  3042. for (var i = 1; i < 16; i++) {
  3043. hash = (hash * 397) ^ (this.m[i] || 0);
  3044. }
  3045. return hash;
  3046. };
  3047. /**
  3048. * Decomposes the current Matrix into :
  3049. * - a scale vector3 passed as a reference to update,
  3050. * - a rotation quaternion passed as a reference to update,
  3051. * - a translation vector3 passed as a reference to update.
  3052. * Returns the boolean `true`.
  3053. */
  3054. Matrix.prototype.decompose = function (scale, rotation, translation) {
  3055. translation.x = this.m[12];
  3056. translation.y = this.m[13];
  3057. translation.z = this.m[14];
  3058. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  3059. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  3060. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  3061. if (this.determinant() <= 0) {
  3062. scale.y *= -1;
  3063. }
  3064. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  3065. rotation.x = 0;
  3066. rotation.y = 0;
  3067. rotation.z = 0;
  3068. rotation.w = 1;
  3069. return false;
  3070. }
  3071. 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, MathTmp.Matrix[0]);
  3072. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  3073. return true;
  3074. };
  3075. /**
  3076. * Returns a new Matrix as the extracted rotation matrix from the current one.
  3077. */
  3078. Matrix.prototype.getRotationMatrix = function () {
  3079. var result = Matrix.Identity();
  3080. this.getRotationMatrixToRef(result);
  3081. return result;
  3082. };
  3083. /**
  3084. * Extracts the rotation matrix from the current one and sets it as the passed "result".
  3085. * Returns the current Matrix.
  3086. */
  3087. Matrix.prototype.getRotationMatrixToRef = function (result) {
  3088. var m = this.m;
  3089. var xs = m[0] * m[1] * m[2] * m[3] < 0 ? -1 : 1;
  3090. var ys = m[4] * m[5] * m[6] * m[7] < 0 ? -1 : 1;
  3091. var zs = m[8] * m[9] * m[10] * m[11] < 0 ? -1 : 1;
  3092. var sx = xs * Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  3093. var sy = ys * Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  3094. var sz = zs * Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  3095. 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);
  3096. return this;
  3097. };
  3098. // Statics
  3099. /**
  3100. * Returns a new Matrix set from the starting index of the passed array.
  3101. */
  3102. Matrix.FromArray = function (array, offset) {
  3103. var result = new Matrix();
  3104. if (!offset) {
  3105. offset = 0;
  3106. }
  3107. Matrix.FromArrayToRef(array, offset, result);
  3108. return result;
  3109. };
  3110. /**
  3111. * Sets the passed "result" matrix from the starting index of the passed array.
  3112. */
  3113. Matrix.FromArrayToRef = function (array, offset, result) {
  3114. for (var index = 0; index < 16; index++) {
  3115. result.m[index] = array[index + offset];
  3116. }
  3117. result._markAsUpdated();
  3118. };
  3119. /**
  3120. * Sets the passed "result" matrix from the starting index of the passed Float32Array by multiplying each element by the float "scale".
  3121. */
  3122. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  3123. for (var index = 0; index < 16; index++) {
  3124. result.m[index] = array[index + offset] * scale;
  3125. }
  3126. result._markAsUpdated();
  3127. };
  3128. /**
  3129. * Sets the passed matrix "result" with the 16 passed floats.
  3130. */
  3131. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  3132. result.m[0] = initialM11;
  3133. result.m[1] = initialM12;
  3134. result.m[2] = initialM13;
  3135. result.m[3] = initialM14;
  3136. result.m[4] = initialM21;
  3137. result.m[5] = initialM22;
  3138. result.m[6] = initialM23;
  3139. result.m[7] = initialM24;
  3140. result.m[8] = initialM31;
  3141. result.m[9] = initialM32;
  3142. result.m[10] = initialM33;
  3143. result.m[11] = initialM34;
  3144. result.m[12] = initialM41;
  3145. result.m[13] = initialM42;
  3146. result.m[14] = initialM43;
  3147. result.m[15] = initialM44;
  3148. result._markAsUpdated();
  3149. };
  3150. /**
  3151. * Returns the index-th row of the current matrix as a new Vector4.
  3152. */
  3153. Matrix.prototype.getRow = function (index) {
  3154. if (index < 0 || index > 3) {
  3155. return null;
  3156. }
  3157. var i = index * 4;
  3158. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  3159. };
  3160. /**
  3161. * Sets the index-th row of the current matrix with the passed Vector4 values.
  3162. * Returns the updated Matrix.
  3163. */
  3164. Matrix.prototype.setRow = function (index, row) {
  3165. if (index < 0 || index > 3) {
  3166. return this;
  3167. }
  3168. var i = index * 4;
  3169. this.m[i + 0] = row.x;
  3170. this.m[i + 1] = row.y;
  3171. this.m[i + 2] = row.z;
  3172. this.m[i + 3] = row.w;
  3173. this._markAsUpdated();
  3174. return this;
  3175. };
  3176. /**
  3177. * Sets the index-th row of the current matrix with the passed 4 x float values.
  3178. * Returns the updated Matrix.
  3179. */
  3180. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  3181. if (index < 0 || index > 3) {
  3182. return this;
  3183. }
  3184. var i = index * 4;
  3185. this.m[i + 0] = x;
  3186. this.m[i + 1] = y;
  3187. this.m[i + 2] = z;
  3188. this.m[i + 3] = w;
  3189. this._markAsUpdated();
  3190. return this;
  3191. };
  3192. /**
  3193. * Returns a new Matrix set from the 16 passed floats.
  3194. */
  3195. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  3196. var result = new Matrix();
  3197. result.m[0] = initialM11;
  3198. result.m[1] = initialM12;
  3199. result.m[2] = initialM13;
  3200. result.m[3] = initialM14;
  3201. result.m[4] = initialM21;
  3202. result.m[5] = initialM22;
  3203. result.m[6] = initialM23;
  3204. result.m[7] = initialM24;
  3205. result.m[8] = initialM31;
  3206. result.m[9] = initialM32;
  3207. result.m[10] = initialM33;
  3208. result.m[11] = initialM34;
  3209. result.m[12] = initialM41;
  3210. result.m[13] = initialM42;
  3211. result.m[14] = initialM43;
  3212. result.m[15] = initialM44;
  3213. return result;
  3214. };
  3215. /**
  3216. * Returns a new Matrix composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3217. */
  3218. Matrix.Compose = function (scale, rotation, translation) {
  3219. var result = Matrix.Identity();
  3220. Matrix.ComposeToRef(scale, rotation, translation, result);
  3221. return result;
  3222. };
  3223. /**
  3224. * Update a Matrix with values composed by the passed scale (vector3), rotation (quaternion) and translation (vector3).
  3225. */
  3226. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  3227. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  3228. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  3229. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  3230. result.setTranslation(translation);
  3231. };
  3232. /**
  3233. * Returns a new indentity Matrix.
  3234. */
  3235. Matrix.Identity = function () {
  3236. return Matrix.FromValues(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0);
  3237. };
  3238. /**
  3239. * Sets the passed "result" as an identity matrix.
  3240. */
  3241. Matrix.IdentityToRef = function (result) {
  3242. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, result);
  3243. };
  3244. /**
  3245. * Returns a new zero Matrix.
  3246. */
  3247. Matrix.Zero = function () {
  3248. return Matrix.FromValues(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
  3249. };
  3250. /**
  3251. * Returns a new rotation matrix for "angle" radians around the X axis.
  3252. */
  3253. Matrix.RotationX = function (angle) {
  3254. var result = new Matrix();
  3255. Matrix.RotationXToRef(angle, result);
  3256. return result;
  3257. };
  3258. /**
  3259. * Returns a new Matrix as the passed inverted one.
  3260. */
  3261. Matrix.Invert = function (source) {
  3262. var result = new Matrix();
  3263. source.invertToRef(result);
  3264. return result;
  3265. };
  3266. /**
  3267. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the X axis.
  3268. */
  3269. Matrix.RotationXToRef = function (angle, result) {
  3270. var s = Math.sin(angle);
  3271. var c = Math.cos(angle);
  3272. result.m[0] = 1.0;
  3273. result.m[15] = 1.0;
  3274. result.m[5] = c;
  3275. result.m[10] = c;
  3276. result.m[9] = -s;
  3277. result.m[6] = s;
  3278. result.m[1] = 0.0;
  3279. result.m[2] = 0.0;
  3280. result.m[3] = 0.0;
  3281. result.m[4] = 0.0;
  3282. result.m[7] = 0.0;
  3283. result.m[8] = 0.0;
  3284. result.m[11] = 0.0;
  3285. result.m[12] = 0.0;
  3286. result.m[13] = 0.0;
  3287. result.m[14] = 0.0;
  3288. result._markAsUpdated();
  3289. };
  3290. /**
  3291. * Returns a new rotation matrix for "angle" radians around the Y axis.
  3292. */
  3293. Matrix.RotationY = function (angle) {
  3294. var result = new Matrix();
  3295. Matrix.RotationYToRef(angle, result);
  3296. return result;
  3297. };
  3298. /**
  3299. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Y axis.
  3300. */
  3301. Matrix.RotationYToRef = function (angle, result) {
  3302. var s = Math.sin(angle);
  3303. var c = Math.cos(angle);
  3304. result.m[5] = 1.0;
  3305. result.m[15] = 1.0;
  3306. result.m[0] = c;
  3307. result.m[2] = -s;
  3308. result.m[8] = s;
  3309. result.m[10] = c;
  3310. result.m[1] = 0.0;
  3311. result.m[3] = 0.0;
  3312. result.m[4] = 0.0;
  3313. result.m[6] = 0.0;
  3314. result.m[7] = 0.0;
  3315. result.m[9] = 0.0;
  3316. result.m[11] = 0.0;
  3317. result.m[12] = 0.0;
  3318. result.m[13] = 0.0;
  3319. result.m[14] = 0.0;
  3320. result._markAsUpdated();
  3321. };
  3322. /**
  3323. * Returns a new rotation matrix for "angle" radians around the Z axis.
  3324. */
  3325. Matrix.RotationZ = function (angle) {
  3326. var result = new Matrix();
  3327. Matrix.RotationZToRef(angle, result);
  3328. return result;
  3329. };
  3330. /**
  3331. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the Z axis.
  3332. */
  3333. Matrix.RotationZToRef = function (angle, result) {
  3334. var s = Math.sin(angle);
  3335. var c = Math.cos(angle);
  3336. result.m[10] = 1.0;
  3337. result.m[15] = 1.0;
  3338. result.m[0] = c;
  3339. result.m[1] = s;
  3340. result.m[4] = -s;
  3341. result.m[5] = c;
  3342. result.m[2] = 0.0;
  3343. result.m[3] = 0.0;
  3344. result.m[6] = 0.0;
  3345. result.m[7] = 0.0;
  3346. result.m[8] = 0.0;
  3347. result.m[9] = 0.0;
  3348. result.m[11] = 0.0;
  3349. result.m[12] = 0.0;
  3350. result.m[13] = 0.0;
  3351. result.m[14] = 0.0;
  3352. result._markAsUpdated();
  3353. };
  3354. /**
  3355. * Returns a new rotation matrix for "angle" radians around the passed axis.
  3356. */
  3357. Matrix.RotationAxis = function (axis, angle) {
  3358. var result = Matrix.Zero();
  3359. Matrix.RotationAxisToRef(axis, angle, result);
  3360. return result;
  3361. };
  3362. /**
  3363. * Sets the passed matrix "result" as a rotation matrix for "angle" radians around the passed axis.
  3364. */
  3365. Matrix.RotationAxisToRef = function (axis, angle, result) {
  3366. var s = Math.sin(-angle);
  3367. var c = Math.cos(-angle);
  3368. var c1 = 1 - c;
  3369. axis.normalize();
  3370. result.m[0] = (axis.x * axis.x) * c1 + c;
  3371. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  3372. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  3373. result.m[3] = 0.0;
  3374. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  3375. result.m[5] = (axis.y * axis.y) * c1 + c;
  3376. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  3377. result.m[7] = 0.0;
  3378. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  3379. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  3380. result.m[10] = (axis.z * axis.z) * c1 + c;
  3381. result.m[11] = 0.0;
  3382. result.m[15] = 1.0;
  3383. result._markAsUpdated();
  3384. };
  3385. /**
  3386. * Returns a new Matrix as a rotation matrix from the Euler angles (y, x, z).
  3387. */
  3388. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  3389. var result = new Matrix();
  3390. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  3391. return result;
  3392. };
  3393. /**
  3394. * Sets the passed matrix "result" as a rotation matrix from the Euler angles (y, x, z).
  3395. */
  3396. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  3397. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  3398. this._tempQuaternion.toRotationMatrix(result);
  3399. };
  3400. /**
  3401. * Returns a new Matrix as a scaling matrix from the passed floats (x, y, z).
  3402. */
  3403. Matrix.Scaling = function (x, y, z) {
  3404. var result = Matrix.Zero();
  3405. Matrix.ScalingToRef(x, y, z, result);
  3406. return result;
  3407. };
  3408. /**
  3409. * Sets the passed matrix "result" as a scaling matrix from the passed floats (x, y, z).
  3410. */
  3411. Matrix.ScalingToRef = function (x, y, z, result) {
  3412. result.m[0] = x;
  3413. result.m[1] = 0.0;
  3414. result.m[2] = 0.0;
  3415. result.m[3] = 0.0;
  3416. result.m[4] = 0.0;
  3417. result.m[5] = y;
  3418. result.m[6] = 0.0;
  3419. result.m[7] = 0.0;
  3420. result.m[8] = 0.0;
  3421. result.m[9] = 0.0;
  3422. result.m[10] = z;
  3423. result.m[11] = 0.0;
  3424. result.m[12] = 0.0;
  3425. result.m[13] = 0.0;
  3426. result.m[14] = 0.0;
  3427. result.m[15] = 1.0;
  3428. result._markAsUpdated();
  3429. };
  3430. /**
  3431. * Returns a new Matrix as a translation matrix from the passed floats (x, y, z).
  3432. */
  3433. Matrix.Translation = function (x, y, z) {
  3434. var result = Matrix.Identity();
  3435. Matrix.TranslationToRef(x, y, z, result);
  3436. return result;
  3437. };
  3438. /**
  3439. * Sets the passed matrix "result" as a translation matrix from the passed floats (x, y, z).
  3440. */
  3441. Matrix.TranslationToRef = function (x, y, z, result) {
  3442. Matrix.FromValuesToRef(1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 0.0, 1.0, 0.0, x, y, z, 1.0, result);
  3443. };
  3444. /**
  3445. * Returns a new Matrix whose values are the interpolated values for "gradien" (float) between the ones of the matrices "startValue" and "endValue".
  3446. */
  3447. Matrix.Lerp = function (startValue, endValue, gradient) {
  3448. var result = Matrix.Zero();
  3449. for (var index = 0; index < 16; index++) {
  3450. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  3451. }
  3452. result._markAsUpdated();
  3453. return result;
  3454. };
  3455. /**
  3456. * Returns a new Matrix whose values are computed by :
  3457. * - decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices,
  3458. * - interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end,
  3459. * - recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices.
  3460. */
  3461. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  3462. var startScale = new Vector3(0, 0, 0);
  3463. var startRotation = new Quaternion();
  3464. var startTranslation = new Vector3(0, 0, 0);
  3465. startValue.decompose(startScale, startRotation, startTranslation);
  3466. var endScale = new Vector3(0, 0, 0);
  3467. var endRotation = new Quaternion();
  3468. var endTranslation = new Vector3(0, 0, 0);
  3469. endValue.decompose(endScale, endRotation, endTranslation);
  3470. var resultScale = Vector3.Lerp(startScale, endScale, gradient);
  3471. var resultRotation = Quaternion.Slerp(startRotation, endRotation, gradient);
  3472. var resultTranslation = Vector3.Lerp(startTranslation, endTranslation, gradient);
  3473. return Matrix.Compose(resultScale, resultRotation, resultTranslation);
  3474. };
  3475. /**
  3476. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3477. * This methods works for a Left-Handed system.
  3478. */
  3479. Matrix.LookAtLH = function (eye, target, up) {
  3480. var result = Matrix.Zero();
  3481. Matrix.LookAtLHToRef(eye, target, up, result);
  3482. return result;
  3483. };
  3484. /**
  3485. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3486. * This methods works for a Left-Handed system.
  3487. */
  3488. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  3489. // Z axis
  3490. target.subtractToRef(eye, this._zAxis);
  3491. this._zAxis.normalize();
  3492. // X axis
  3493. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3494. if (this._xAxis.lengthSquared() === 0) {
  3495. this._xAxis.x = 1.0;
  3496. }
  3497. else {
  3498. this._xAxis.normalize();
  3499. }
  3500. // Y axis
  3501. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3502. this._yAxis.normalize();
  3503. // Eye angles
  3504. var ex = -Vector3.Dot(this._xAxis, eye);
  3505. var ey = -Vector3.Dot(this._yAxis, eye);
  3506. var ez = -Vector3.Dot(this._zAxis, eye);
  3507. 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);
  3508. };
  3509. /**
  3510. * Returns a new rotation Matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3511. * This methods works for a Right-Handed system.
  3512. */
  3513. Matrix.LookAtRH = function (eye, target, up) {
  3514. var result = Matrix.Zero();
  3515. Matrix.LookAtRHToRef(eye, target, up, result);
  3516. return result;
  3517. };
  3518. /**
  3519. * Sets the passed "result" Matrix as a rotation matrix used to rotate a mesh so as it looks at the target Vector3, from the eye Vector3, the UP vector3 being orientated like "up".
  3520. * This methods works for a Left-Handed system.
  3521. */
  3522. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  3523. // Z axis
  3524. eye.subtractToRef(target, this._zAxis);
  3525. this._zAxis.normalize();
  3526. // X axis
  3527. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  3528. if (this._xAxis.lengthSquared() === 0) {
  3529. this._xAxis.x = 1.0;
  3530. }
  3531. else {
  3532. this._xAxis.normalize();
  3533. }
  3534. // Y axis
  3535. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  3536. this._yAxis.normalize();
  3537. // Eye angles
  3538. var ex = -Vector3.Dot(this._xAxis, eye);
  3539. var ey = -Vector3.Dot(this._yAxis, eye);
  3540. var ez = -Vector3.Dot(this._zAxis, eye);
  3541. 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);
  3542. };
  3543. /**
  3544. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3545. */
  3546. Matrix.OrthoLH = function (width, height, znear, zfar) {
  3547. var matrix = Matrix.Zero();
  3548. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  3549. return matrix;
  3550. };
  3551. /**
  3552. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3553. */
  3554. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  3555. var n = znear;
  3556. var f = zfar;
  3557. var a = 2.0 / width;
  3558. var b = 2.0 / height;
  3559. var c = 2.0 / (f - n);
  3560. var d = -(f + n) / (f - n);
  3561. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, 0.0, 0.0, d, 1.0, result);
  3562. };
  3563. /**
  3564. * Returns a new Matrix as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3565. */
  3566. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  3567. var matrix = Matrix.Zero();
  3568. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  3569. return matrix;
  3570. };
  3571. /**
  3572. * Sets the passed matrix "result" as a left-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3573. */
  3574. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3575. var n = znear;
  3576. var f = zfar;
  3577. var a = 2.0 / (right - left);
  3578. var b = 2.0 / (top - bottom);
  3579. var c = 2.0 / (f - n);
  3580. var d = -(f + n) / (f - n);
  3581. var i0 = (left + right) / (left - right);
  3582. var i1 = (top + bottom) / (bottom - top);
  3583. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 0.0, i0, i1, d, 1.0, result);
  3584. };
  3585. /**
  3586. * Returns a new Matrix as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3587. */
  3588. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  3589. var matrix = Matrix.Zero();
  3590. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  3591. return matrix;
  3592. };
  3593. /**
  3594. * Sets the passed matrix "result" as a right-handed orthographic projection matrix computed from the passed floats : left, right, top and bottom being the coordinates of the projection plane, z near and far limits.
  3595. */
  3596. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  3597. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  3598. result.m[10] *= -1.0;
  3599. };
  3600. /**
  3601. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : width and height of the projection plane, z near and far limits.
  3602. */
  3603. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  3604. var matrix = Matrix.Zero();
  3605. var n = znear;
  3606. var f = zfar;
  3607. var a = 2.0 * n / width;
  3608. var b = 2.0 * n / height;
  3609. var c = (f + n) / (f - n);
  3610. var d = -2.0 * f * n / (f - n);
  3611. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, matrix);
  3612. return matrix;
  3613. };
  3614. /**
  3615. * Returns a new Matrix as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3616. */
  3617. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  3618. var matrix = Matrix.Zero();
  3619. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  3620. return matrix;
  3621. };
  3622. /**
  3623. * Sets the passed matrix "result" as a left-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3624. */
  3625. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3626. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3627. var n = znear;
  3628. var f = zfar;
  3629. var t = 1.0 / (Math.tan(fov * 0.5));
  3630. var a = isVerticalFovFixed ? (t / aspect) : t;
  3631. var b = isVerticalFovFixed ? t : (t * aspect);
  3632. var c = (f + n) / (f - n);
  3633. var d = -2.0 * f * n / (f - n);
  3634. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, 1.0, 0.0, 0.0, d, 0.0, result);
  3635. };
  3636. /**
  3637. * Returns a new Matrix as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3638. */
  3639. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  3640. var matrix = Matrix.Zero();
  3641. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  3642. return matrix;
  3643. };
  3644. /**
  3645. * Sets the passed matrix "result" as a right-handed perspective projection matrix computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3646. */
  3647. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  3648. //alternatively this could be expressed as:
  3649. // m = PerspectiveFovLHToRef
  3650. // m[10] *= -1.0;
  3651. // m[11] *= -1.0;
  3652. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  3653. var n = znear;
  3654. var f = zfar;
  3655. var t = 1.0 / (Math.tan(fov * 0.5));
  3656. var a = isVerticalFovFixed ? (t / aspect) : t;
  3657. var b = isVerticalFovFixed ? t : (t * aspect);
  3658. var c = -(f + n) / (f - n);
  3659. var d = -2 * f * n / (f - n);
  3660. BABYLON.Matrix.FromValuesToRef(a, 0.0, 0.0, 0.0, 0.0, b, 0.0, 0.0, 0.0, 0.0, c, -1.0, 0.0, 0.0, d, 0.0, result);
  3661. };
  3662. /**
  3663. * Sets the passed matrix "result" as a left-handed perspective projection matrix for WebVR computed from the passed floats : vertical angle of view (fov), width/height ratio (aspect), z near and far limits.
  3664. */
  3665. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  3666. if (rightHanded === void 0) { rightHanded = false; }
  3667. var rightHandedFactor = rightHanded ? -1 : 1;
  3668. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  3669. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  3670. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  3671. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  3672. var xScale = 2.0 / (leftTan + rightTan);
  3673. var yScale = 2.0 / (upTan + downTan);
  3674. result.m[0] = xScale;
  3675. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  3676. result.m[5] = yScale;
  3677. result.m[6] = result.m[7] = 0.0;
  3678. result.m[8] = ((leftTan - rightTan) * xScale * 0.5); // * rightHandedFactor;
  3679. result.m[9] = -((upTan - downTan) * yScale * 0.5); // * rightHandedFactor;
  3680. //result.m[10] = -(znear + zfar) / (zfar - znear) * rightHandedFactor;
  3681. result.m[10] = -zfar / (znear - zfar);
  3682. result.m[11] = 1.0 * rightHandedFactor;
  3683. result.m[12] = result.m[13] = result.m[15] = 0.0;
  3684. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  3685. // result.m[14] = (znear * zfar) / (znear - zfar);
  3686. result._markAsUpdated();
  3687. };
  3688. /**
  3689. * Returns the final transformation matrix : world * view * projection * viewport
  3690. */
  3691. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  3692. var cw = viewport.width;
  3693. var ch = viewport.height;
  3694. var cx = viewport.x;
  3695. var cy = viewport.y;
  3696. var viewportMatrix = Matrix.FromValues(cw / 2.0, 0.0, 0.0, 0.0, 0.0, -ch / 2.0, 0.0, 0.0, 0.0, 0.0, zmax - zmin, 0.0, cx + cw / 2.0, ch / 2.0 + cy, zmin, 1);
  3697. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  3698. };
  3699. /**
  3700. * Returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the passed Matrix.
  3701. */
  3702. Matrix.GetAsMatrix2x2 = function (matrix) {
  3703. return new Float32Array([
  3704. matrix.m[0], matrix.m[1],
  3705. matrix.m[4], matrix.m[5]
  3706. ]);
  3707. };
  3708. /**
  3709. * Returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the passed Matrix.
  3710. */
  3711. Matrix.GetAsMatrix3x3 = function (matrix) {
  3712. return new Float32Array([
  3713. matrix.m[0], matrix.m[1], matrix.m[2],
  3714. matrix.m[4], matrix.m[5], matrix.m[6],
  3715. matrix.m[8], matrix.m[9], matrix.m[10]
  3716. ]);
  3717. };
  3718. /**
  3719. * Compute the transpose of the passed Matrix.
  3720. * Returns a new Matrix.
  3721. */
  3722. Matrix.Transpose = function (matrix) {
  3723. var result = new Matrix();
  3724. result.m[0] = matrix.m[0];
  3725. result.m[1] = matrix.m[4];
  3726. result.m[2] = matrix.m[8];
  3727. result.m[3] = matrix.m[12];
  3728. result.m[4] = matrix.m[1];
  3729. result.m[5] = matrix.m[5];
  3730. result.m[6] = matrix.m[9];
  3731. result.m[7] = matrix.m[13];
  3732. result.m[8] = matrix.m[2];
  3733. result.m[9] = matrix.m[6];
  3734. result.m[10] = matrix.m[10];
  3735. result.m[11] = matrix.m[14];
  3736. result.m[12] = matrix.m[3];
  3737. result.m[13] = matrix.m[7];
  3738. result.m[14] = matrix.m[11];
  3739. result.m[15] = matrix.m[15];
  3740. return result;
  3741. };
  3742. /**
  3743. * Returns a new Matrix as the reflection matrix across the passed plane.
  3744. */
  3745. Matrix.Reflection = function (plane) {
  3746. var matrix = new Matrix();
  3747. Matrix.ReflectionToRef(plane, matrix);
  3748. return matrix;
  3749. };
  3750. /**
  3751. * Sets the passed matrix "result" as the reflection matrix across the passed plane.
  3752. */
  3753. Matrix.ReflectionToRef = function (plane, result) {
  3754. plane.normalize();
  3755. var x = plane.normal.x;
  3756. var y = plane.normal.y;
  3757. var z = plane.normal.z;
  3758. var temp = -2 * x;
  3759. var temp2 = -2 * y;
  3760. var temp3 = -2 * z;
  3761. result.m[0] = (temp * x) + 1;
  3762. result.m[1] = temp2 * x;
  3763. result.m[2] = temp3 * x;
  3764. result.m[3] = 0.0;
  3765. result.m[4] = temp * y;
  3766. result.m[5] = (temp2 * y) + 1;
  3767. result.m[6] = temp3 * y;
  3768. result.m[7] = 0.0;
  3769. result.m[8] = temp * z;
  3770. result.m[9] = temp2 * z;
  3771. result.m[10] = (temp3 * z) + 1;
  3772. result.m[11] = 0.0;
  3773. result.m[12] = temp * plane.d;
  3774. result.m[13] = temp2 * plane.d;
  3775. result.m[14] = temp3 * plane.d;
  3776. result.m[15] = 1.0;
  3777. result._markAsUpdated();
  3778. };
  3779. /**
  3780. * Sets the passed matrix "mat" as a rotation matrix composed from the 3 passed left handed axis.
  3781. */
  3782. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  3783. result.m[0] = xaxis.x;
  3784. result.m[1] = xaxis.y;
  3785. result.m[2] = xaxis.z;
  3786. result.m[3] = 0.0;
  3787. result.m[4] = yaxis.x;
  3788. result.m[5] = yaxis.y;
  3789. result.m[6] = yaxis.z;
  3790. result.m[7] = 0.0;
  3791. result.m[8] = zaxis.x;
  3792. result.m[9] = zaxis.y;
  3793. result.m[10] = zaxis.z;
  3794. result.m[11] = 0.0;
  3795. result.m[12] = 0.0;
  3796. result.m[13] = 0.0;
  3797. result.m[14] = 0.0;
  3798. result.m[15] = 1.0;
  3799. result._markAsUpdated();
  3800. };
  3801. /**
  3802. * Sets the passed matrix "result" as a rotation matrix according to the passed quaternion.
  3803. */
  3804. Matrix.FromQuaternionToRef = function (quat, result) {
  3805. var xx = quat.x * quat.x;
  3806. var yy = quat.y * quat.y;
  3807. var zz = quat.z * quat.z;
  3808. var xy = quat.x * quat.y;
  3809. var zw = quat.z * quat.w;
  3810. var zx = quat.z * quat.x;
  3811. var yw = quat.y * quat.w;
  3812. var yz = quat.y * quat.z;
  3813. var xw = quat.x * quat.w;
  3814. result.m[0] = 1.0 - (2.0 * (yy + zz));
  3815. result.m[1] = 2.0 * (xy + zw);
  3816. result.m[2] = 2.0 * (zx - yw);
  3817. result.m[3] = 0.0;
  3818. result.m[4] = 2.0 * (xy - zw);
  3819. result.m[5] = 1.0 - (2.0 * (zz + xx));
  3820. result.m[6] = 2.0 * (yz + xw);
  3821. result.m[7] = 0.0;
  3822. result.m[8] = 2.0 * (zx + yw);
  3823. result.m[9] = 2.0 * (yz - xw);
  3824. result.m[10] = 1.0 - (2.0 * (yy + xx));
  3825. result.m[11] = 0.0;
  3826. result.m[12] = 0.0;
  3827. result.m[13] = 0.0;
  3828. result.m[14] = 0.0;
  3829. result.m[15] = 1.0;
  3830. result._markAsUpdated();
  3831. };
  3832. Matrix._tempQuaternion = new Quaternion();
  3833. Matrix._xAxis = Vector3.Zero();
  3834. Matrix._yAxis = Vector3.Zero();
  3835. Matrix._zAxis = Vector3.Zero();
  3836. Matrix._updateFlagSeed = 0;
  3837. return Matrix;
  3838. }());
  3839. BABYLON.Matrix = Matrix;
  3840. var Plane = (function () {
  3841. /**
  3842. * Creates a Plane object according to the passed floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  3843. */
  3844. function Plane(a, b, c, d) {
  3845. this.normal = new Vector3(a, b, c);
  3846. this.d = d;
  3847. }
  3848. /**
  3849. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  3850. */
  3851. Plane.prototype.asArray = function () {
  3852. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  3853. };
  3854. // Methods
  3855. /**
  3856. * Returns a new plane copied from the current Plane.
  3857. */
  3858. Plane.prototype.clone = function () {
  3859. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  3860. };
  3861. /**
  3862. * Returns the string "Plane".
  3863. */
  3864. Plane.prototype.getClassName = function () {
  3865. return "Plane";
  3866. };
  3867. /**
  3868. * Returns the Plane hash code.
  3869. */
  3870. Plane.prototype.getHashCode = function () {
  3871. var hash = this.normal.getHashCode();
  3872. hash = (hash * 397) ^ (this.d || 0);
  3873. return hash;
  3874. };
  3875. /**
  3876. * Normalize the current Plane in place.
  3877. * Returns the updated Plane.
  3878. */
  3879. Plane.prototype.normalize = function () {
  3880. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  3881. var magnitude = 0.0;
  3882. if (norm !== 0) {
  3883. magnitude = 1.0 / norm;
  3884. }
  3885. this.normal.x *= magnitude;
  3886. this.normal.y *= magnitude;
  3887. this.normal.z *= magnitude;
  3888. this.d *= magnitude;
  3889. return this;
  3890. };
  3891. /**
  3892. * Returns a new Plane as the result of the transformation of the current Plane by the passed matrix.
  3893. */
  3894. Plane.prototype.transform = function (transformation) {
  3895. var transposedMatrix = Matrix.Transpose(transformation);
  3896. var x = this.normal.x;
  3897. var y = this.normal.y;
  3898. var z = this.normal.z;
  3899. var d = this.d;
  3900. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  3901. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  3902. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  3903. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  3904. return new Plane(normalX, normalY, normalZ, finalD);
  3905. };
  3906. /**
  3907. * Returns the dot product (float) of the point coordinates and the plane normal.
  3908. */
  3909. Plane.prototype.dotCoordinate = function (point) {
  3910. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  3911. };
  3912. /**
  3913. * Updates the current Plane from the plane defined by the three passed points.
  3914. * Returns the updated Plane.
  3915. */
  3916. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  3917. var x1 = point2.x - point1.x;
  3918. var y1 = point2.y - point1.y;
  3919. var z1 = point2.z - point1.z;
  3920. var x2 = point3.x - point1.x;
  3921. var y2 = point3.y - point1.y;
  3922. var z2 = point3.z - point1.z;
  3923. var yz = (y1 * z2) - (z1 * y2);
  3924. var xz = (z1 * x2) - (x1 * z2);
  3925. var xy = (x1 * y2) - (y1 * x2);
  3926. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  3927. var invPyth;
  3928. if (pyth !== 0) {
  3929. invPyth = 1.0 / pyth;
  3930. }
  3931. else {
  3932. invPyth = 0.0;
  3933. }
  3934. this.normal.x = yz * invPyth;
  3935. this.normal.y = xz * invPyth;
  3936. this.normal.z = xy * invPyth;
  3937. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  3938. return this;
  3939. };
  3940. /**
  3941. * Boolean : True is the vector "direction" is the same side than the plane normal.
  3942. */
  3943. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  3944. var dot = Vector3.Dot(this.normal, direction);
  3945. return (dot <= epsilon);
  3946. };
  3947. /**
  3948. * Returns the signed distance (float) from the passed point to the Plane.
  3949. */
  3950. Plane.prototype.signedDistanceTo = function (point) {
  3951. return Vector3.Dot(point, this.normal) + this.d;
  3952. };
  3953. // Statics
  3954. /**
  3955. * Returns a new Plane from the passed array.
  3956. */
  3957. Plane.FromArray = function (array) {
  3958. return new Plane(array[0], array[1], array[2], array[3]);
  3959. };
  3960. /**
  3961. * Returns a new Plane defined by the three passed points.
  3962. */
  3963. Plane.FromPoints = function (point1, point2, point3) {
  3964. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3965. result.copyFromPoints(point1, point2, point3);
  3966. return result;
  3967. };
  3968. /**
  3969. * Returns a new Plane the normal vector to this plane at the passed origin point.
  3970. * Note : the vector "normal" is updated because normalized.
  3971. */
  3972. Plane.FromPositionAndNormal = function (origin, normal) {
  3973. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  3974. normal.normalize();
  3975. result.normal = normal;
  3976. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3977. return result;
  3978. };
  3979. /**
  3980. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the passed other point.
  3981. */
  3982. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  3983. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  3984. return Vector3.Dot(point, normal) + d;
  3985. };
  3986. return Plane;
  3987. }());
  3988. BABYLON.Plane = Plane;
  3989. var Viewport = (function () {
  3990. /**
  3991. * Creates a Viewport object located at (x, y) and sized (width, height).
  3992. */
  3993. function Viewport(x, y, width, height) {
  3994. this.x = x;
  3995. this.y = y;
  3996. this.width = width;
  3997. this.height = height;
  3998. }
  3999. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  4000. if (renderWidthOrEngine.getRenderWidth) {
  4001. var engine = renderWidthOrEngine;
  4002. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  4003. }
  4004. var renderWidth = renderWidthOrEngine;
  4005. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  4006. };
  4007. /**
  4008. * Returns a new Viewport copied from the current one.
  4009. */
  4010. Viewport.prototype.clone = function () {
  4011. return new Viewport(this.x, this.y, this.width, this.height);
  4012. };
  4013. return Viewport;
  4014. }());
  4015. BABYLON.Viewport = Viewport;
  4016. var Frustum = (function () {
  4017. function Frustum() {
  4018. }
  4019. /**
  4020. * Returns a new array of 6 Frustum planes computed by the passed transformation matrix.
  4021. */
  4022. Frustum.GetPlanes = function (transform) {
  4023. var frustumPlanes = [];
  4024. for (var index = 0; index < 6; index++) {
  4025. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  4026. }
  4027. Frustum.GetPlanesToRef(transform, frustumPlanes);
  4028. return frustumPlanes;
  4029. };
  4030. /**
  4031. * Sets the passed array "frustumPlanes" with the 6 Frustum planes computed by the passed transformation matrix.
  4032. */
  4033. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  4034. // Near
  4035. frustumPlanes[0].normal.x = transform.m[3] + transform.m[2];
  4036. frustumPlanes[0].normal.y = transform.m[7] + transform.m[6];
  4037. frustumPlanes[0].normal.z = transform.m[11] + transform.m[10];
  4038. frustumPlanes[0].d = transform.m[15] + transform.m[14];
  4039. frustumPlanes[0].normalize();
  4040. // Far
  4041. frustumPlanes[1].normal.x = transform.m[3] - transform.m[2];
  4042. frustumPlanes[1].normal.y = transform.m[7] - transform.m[6];
  4043. frustumPlanes[1].normal.z = transform.m[11] - transform.m[10];
  4044. frustumPlanes[1].d = transform.m[15] - transform.m[14];
  4045. frustumPlanes[1].normalize();
  4046. // Left
  4047. frustumPlanes[2].normal.x = transform.m[3] + transform.m[0];
  4048. frustumPlanes[2].normal.y = transform.m[7] + transform.m[4];
  4049. frustumPlanes[2].normal.z = transform.m[11] + transform.m[8];
  4050. frustumPlanes[2].d = transform.m[15] + transform.m[12];
  4051. frustumPlanes[2].normalize();
  4052. // Right
  4053. frustumPlanes[3].normal.x = transform.m[3] - transform.m[0];
  4054. frustumPlanes[3].normal.y = transform.m[7] - transform.m[4];
  4055. frustumPlanes[3].normal.z = transform.m[11] - transform.m[8];
  4056. frustumPlanes[3].d = transform.m[15] - transform.m[12];
  4057. frustumPlanes[3].normalize();
  4058. // Top
  4059. frustumPlanes[4].normal.x = transform.m[3] - transform.m[1];
  4060. frustumPlanes[4].normal.y = transform.m[7] - transform.m[5];
  4061. frustumPlanes[4].normal.z = transform.m[11] - transform.m[9];
  4062. frustumPlanes[4].d = transform.m[15] - transform.m[13];
  4063. frustumPlanes[4].normalize();
  4064. // Bottom
  4065. frustumPlanes[5].normal.x = transform.m[3] + transform.m[1];
  4066. frustumPlanes[5].normal.y = transform.m[7] + transform.m[5];
  4067. frustumPlanes[5].normal.z = transform.m[11] + transform.m[9];
  4068. frustumPlanes[5].d = transform.m[15] + transform.m[13];
  4069. frustumPlanes[5].normalize();
  4070. };
  4071. return Frustum;
  4072. }());
  4073. BABYLON.Frustum = Frustum;
  4074. var Space;
  4075. (function (Space) {
  4076. Space[Space["LOCAL"] = 0] = "LOCAL";
  4077. Space[Space["WORLD"] = 1] = "WORLD";
  4078. Space[Space["BONE"] = 2] = "BONE";
  4079. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  4080. var Axis = (function () {
  4081. function Axis() {
  4082. }
  4083. Axis.X = new Vector3(1.0, 0.0, 0.0);
  4084. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  4085. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  4086. return Axis;
  4087. }());
  4088. BABYLON.Axis = Axis;
  4089. ;
  4090. var BezierCurve = (function () {
  4091. function BezierCurve() {
  4092. }
  4093. /**
  4094. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the passed x1, y1, x2, y2 floats.
  4095. */
  4096. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  4097. // Extract X (which is equal to time here)
  4098. var f0 = 1 - 3 * x2 + 3 * x1;
  4099. var f1 = 3 * x2 - 6 * x1;
  4100. var f2 = 3 * x1;
  4101. var refinedT = t;
  4102. for (var i = 0; i < 5; i++) {
  4103. var refinedT2 = refinedT * refinedT;
  4104. var refinedT3 = refinedT2 * refinedT;
  4105. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  4106. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  4107. refinedT -= (x - t) * slope;
  4108. refinedT = Math.min(1, Math.max(0, refinedT));
  4109. }
  4110. // Resolve cubic bezier for the given x
  4111. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  4112. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  4113. Math.pow(refinedT, 3);
  4114. };
  4115. return BezierCurve;
  4116. }());
  4117. BABYLON.BezierCurve = BezierCurve;
  4118. var Orientation;
  4119. (function (Orientation) {
  4120. Orientation[Orientation["CW"] = 0] = "CW";
  4121. Orientation[Orientation["CCW"] = 1] = "CCW";
  4122. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  4123. var Angle = (function () {
  4124. /**
  4125. * Creates an Angle object of "radians" radians (float).
  4126. */
  4127. function Angle(radians) {
  4128. var _this = this;
  4129. /**
  4130. * Returns the Angle value in degrees (float).
  4131. */
  4132. this.degrees = function () { return _this._radians * 180.0 / Math.PI; };
  4133. /**
  4134. * Returns the Angle value in radians (float).
  4135. */
  4136. this.radians = function () { return _this._radians; };
  4137. this._radians = radians;
  4138. if (this._radians < 0.0)
  4139. this._radians += (2.0 * Math.PI);
  4140. }
  4141. /**
  4142. * Returns a new Angle object valued with the angle value in radians between the two passed vectors.
  4143. */
  4144. Angle.BetweenTwoPoints = function (a, b) {
  4145. var delta = b.subtract(a);
  4146. var theta = Math.atan2(delta.y, delta.x);
  4147. return new Angle(theta);
  4148. };
  4149. /**
  4150. * Returns a new Angle object from the passed float in radians.
  4151. */
  4152. Angle.FromRadians = function (radians) {
  4153. return new Angle(radians);
  4154. };
  4155. /**
  4156. * Returns a new Angle object from the passed float in degrees.
  4157. */
  4158. Angle.FromDegrees = function (degrees) {
  4159. return new Angle(degrees * Math.PI / 180.0);
  4160. };
  4161. return Angle;
  4162. }());
  4163. BABYLON.Angle = Angle;
  4164. var Arc2 = (function () {
  4165. /**
  4166. * Creates an Arc object from the three passed points : start, middle and end.
  4167. */
  4168. function Arc2(startPoint, midPoint, endPoint) {
  4169. this.startPoint = startPoint;
  4170. this.midPoint = midPoint;
  4171. this.endPoint = endPoint;
  4172. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  4173. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  4174. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  4175. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  4176. 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);
  4177. this.radius = this.centerPoint.subtract(this.startPoint).length();
  4178. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  4179. var a1 = this.startAngle.degrees();
  4180. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  4181. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  4182. // angles correction
  4183. if (a2 - a1 > +180.0)
  4184. a2 -= 360.0;
  4185. if (a2 - a1 < -180.0)
  4186. a2 += 360.0;
  4187. if (a3 - a2 > +180.0)
  4188. a3 -= 360.0;
  4189. if (a3 - a2 < -180.0)
  4190. a3 += 360.0;
  4191. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  4192. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  4193. }
  4194. return Arc2;
  4195. }());
  4196. BABYLON.Arc2 = Arc2;
  4197. var Path2 = (function () {
  4198. /**
  4199. * Creates a Path2 object from the starting 2D coordinates x and y.
  4200. */
  4201. function Path2(x, y) {
  4202. this._points = new Array();
  4203. this._length = 0.0;
  4204. this.closed = false;
  4205. this._points.push(new Vector2(x, y));
  4206. }
  4207. /**
  4208. * Adds a new segment until the passed coordinates (x, y) to the current Path2.
  4209. * Returns the updated Path2.
  4210. */
  4211. Path2.prototype.addLineTo = function (x, y) {
  4212. if (closed) {
  4213. //Tools.Error("cannot add lines to closed paths");
  4214. return this;
  4215. }
  4216. var newPoint = new Vector2(x, y);
  4217. var previousPoint = this._points[this._points.length - 1];
  4218. this._points.push(newPoint);
  4219. this._length += newPoint.subtract(previousPoint).length();
  4220. return this;
  4221. };
  4222. /**
  4223. * Adds _numberOfSegments_ segments according to the arc definition (middle point coordinates, end point coordinates, the arc start point being the current Path2 last point) to the current Path2.
  4224. * Returns the updated Path2.
  4225. */
  4226. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  4227. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  4228. if (closed) {
  4229. //Tools.Error("cannot add arcs to closed paths");
  4230. return this;
  4231. }
  4232. var startPoint = this._points[this._points.length - 1];
  4233. var midPoint = new Vector2(midX, midY);
  4234. var endPoint = new Vector2(endX, endY);
  4235. var arc = new Arc2(startPoint, midPoint, endPoint);
  4236. var increment = arc.angle.radians() / numberOfSegments;
  4237. if (arc.orientation === Orientation.CW)
  4238. increment *= -1;
  4239. var currentAngle = arc.startAngle.radians() + increment;
  4240. for (var i = 0; i < numberOfSegments; i++) {
  4241. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  4242. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  4243. this.addLineTo(x, y);
  4244. currentAngle += increment;
  4245. }
  4246. return this;
  4247. };
  4248. /**
  4249. * Closes the Path2.
  4250. * Returns the Path2.
  4251. */
  4252. Path2.prototype.close = function () {
  4253. this.closed = true;
  4254. return this;
  4255. };
  4256. /**
  4257. * Returns the Path2 total length (float).
  4258. */
  4259. Path2.prototype.length = function () {
  4260. var result = this._length;
  4261. if (!this.closed) {
  4262. var lastPoint = this._points[this._points.length - 1];
  4263. var firstPoint = this._points[0];
  4264. result += (firstPoint.subtract(lastPoint).length());
  4265. }
  4266. return result;
  4267. };
  4268. /**
  4269. * Returns the Path2 internal array of points.
  4270. */
  4271. Path2.prototype.getPoints = function () {
  4272. return this._points;
  4273. };
  4274. /**
  4275. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  4276. */
  4277. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  4278. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  4279. //Tools.Error("normalized length position should be between 0 and 1.");
  4280. return Vector2.Zero();
  4281. }
  4282. var lengthPosition = normalizedLengthPosition * this.length();
  4283. var previousOffset = 0;
  4284. for (var i = 0; i < this._points.length; i++) {
  4285. var j = (i + 1) % this._points.length;
  4286. var a = this._points[i];
  4287. var b = this._points[j];
  4288. var bToA = b.subtract(a);
  4289. var nextOffset = (bToA.length() + previousOffset);
  4290. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  4291. var dir = bToA.normalize();
  4292. var localOffset = lengthPosition - previousOffset;
  4293. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  4294. }
  4295. previousOffset = nextOffset;
  4296. }
  4297. //Tools.Error("internal error");
  4298. return Vector2.Zero();
  4299. };
  4300. /**
  4301. * Returns a new Path2 starting at the coordinates (x, y).
  4302. */
  4303. Path2.StartingAt = function (x, y) {
  4304. return new Path2(x, y);
  4305. };
  4306. return Path2;
  4307. }());
  4308. BABYLON.Path2 = Path2;
  4309. var Path3D = (function () {
  4310. /**
  4311. * new Path3D(path, normal, raw)
  4312. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  4313. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  4314. * path : an array of Vector3, the curve axis of the Path3D
  4315. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  4316. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  4317. */
  4318. function Path3D(path, firstNormal, raw) {
  4319. this.path = path;
  4320. this._curve = new Array();
  4321. this._distances = new Array();
  4322. this._tangents = new Array();
  4323. this._normals = new Array();
  4324. this._binormals = new Array();
  4325. for (var p = 0; p < path.length; p++) {
  4326. this._curve[p] = path[p].clone(); // hard copy
  4327. }
  4328. this._raw = raw || false;
  4329. this._compute(firstNormal);
  4330. }
  4331. /**
  4332. * Returns the Path3D array of successive Vector3 designing its curve.
  4333. */
  4334. Path3D.prototype.getCurve = function () {
  4335. return this._curve;
  4336. };
  4337. /**
  4338. * Returns an array populated with tangent vectors on each Path3D curve point.
  4339. */
  4340. Path3D.prototype.getTangents = function () {
  4341. return this._tangents;
  4342. };
  4343. /**
  4344. * Returns an array populated with normal vectors on each Path3D curve point.
  4345. */
  4346. Path3D.prototype.getNormals = function () {
  4347. return this._normals;
  4348. };
  4349. /**
  4350. * Returns an array populated with binormal vectors on each Path3D curve point.
  4351. */
  4352. Path3D.prototype.getBinormals = function () {
  4353. return this._binormals;
  4354. };
  4355. /**
  4356. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  4357. */
  4358. Path3D.prototype.getDistances = function () {
  4359. return this._distances;
  4360. };
  4361. /**
  4362. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  4363. * Returns the same object updated.
  4364. */
  4365. Path3D.prototype.update = function (path, firstNormal) {
  4366. for (var p = 0; p < path.length; p++) {
  4367. this._curve[p].x = path[p].x;
  4368. this._curve[p].y = path[p].y;
  4369. this._curve[p].z = path[p].z;
  4370. }
  4371. this._compute(firstNormal);
  4372. return this;
  4373. };
  4374. // private function compute() : computes tangents, normals and binormals
  4375. Path3D.prototype._compute = function (firstNormal) {
  4376. var l = this._curve.length;
  4377. // first and last tangents
  4378. this._tangents[0] = this._getFirstNonNullVector(0);
  4379. if (!this._raw) {
  4380. this._tangents[0].normalize();
  4381. }
  4382. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  4383. if (!this._raw) {
  4384. this._tangents[l - 1].normalize();
  4385. }
  4386. // normals and binormals at first point : arbitrary vector with _normalVector()
  4387. var tg0 = this._tangents[0];
  4388. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  4389. this._normals[0] = pp0;
  4390. if (!this._raw) {
  4391. this._normals[0].normalize();
  4392. }
  4393. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  4394. if (!this._raw) {
  4395. this._binormals[0].normalize();
  4396. }
  4397. this._distances[0] = 0.0;
  4398. // normals and binormals : next points
  4399. var prev; // previous vector (segment)
  4400. var cur; // current vector (segment)
  4401. var curTang; // current tangent
  4402. // previous normal
  4403. var prevBinor; // previous binormal
  4404. for (var i = 1; i < l; i++) {
  4405. // tangents
  4406. prev = this._getLastNonNullVector(i);
  4407. if (i < l - 1) {
  4408. cur = this._getFirstNonNullVector(i);
  4409. this._tangents[i] = prev.add(cur);
  4410. this._tangents[i].normalize();
  4411. }
  4412. this._distances[i] = this._distances[i - 1] + prev.length();
  4413. // normals and binormals
  4414. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  4415. curTang = this._tangents[i];
  4416. prevBinor = this._binormals[i - 1];
  4417. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  4418. if (!this._raw) {
  4419. this._normals[i].normalize();
  4420. }
  4421. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  4422. if (!this._raw) {
  4423. this._binormals[i].normalize();
  4424. }
  4425. }
  4426. };
  4427. // private function getFirstNonNullVector(index)
  4428. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  4429. Path3D.prototype._getFirstNonNullVector = function (index) {
  4430. var i = 1;
  4431. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  4432. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  4433. i++;
  4434. nNVector = this._curve[index + i].subtract(this._curve[index]);
  4435. }
  4436. return nNVector;
  4437. };
  4438. // private function getLastNonNullVector(index)
  4439. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  4440. Path3D.prototype._getLastNonNullVector = function (index) {
  4441. var i = 1;
  4442. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  4443. while (nLVector.length() === 0 && index > i + 1) {
  4444. i++;
  4445. nLVector = this._curve[index].subtract(this._curve[index - i]);
  4446. }
  4447. return nLVector;
  4448. };
  4449. // private function normalVector(v0, vt, va) :
  4450. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  4451. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  4452. Path3D.prototype._normalVector = function (v0, vt, va) {
  4453. var normal0;
  4454. var tgl = vt.length();
  4455. if (tgl === 0.0) {
  4456. tgl = 1.0;
  4457. }
  4458. if (va === undefined || va === null) {
  4459. var point;
  4460. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) {
  4461. point = new Vector3(0.0, -1.0, 0.0);
  4462. }
  4463. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  4464. point = new Vector3(1.0, 0.0, 0.0);
  4465. }
  4466. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  4467. point = new Vector3(0.0, 0.0, 1.0);
  4468. }
  4469. normal0 = Vector3.Cross(vt, point);
  4470. }
  4471. else {
  4472. normal0 = Vector3.Cross(vt, va);
  4473. Vector3.CrossToRef(normal0, vt, normal0);
  4474. }
  4475. normal0.normalize();
  4476. return normal0;
  4477. };
  4478. return Path3D;
  4479. }());
  4480. BABYLON.Path3D = Path3D;
  4481. var Curve3 = (function () {
  4482. /**
  4483. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  4484. * A Curve3 is designed from a series of successive Vector3.
  4485. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  4486. */
  4487. function Curve3(points) {
  4488. this._length = 0.0;
  4489. this._points = points;
  4490. this._length = this._computeLength(points);
  4491. }
  4492. /**
  4493. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  4494. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  4495. * @param v1 (Vector3) the control point
  4496. * @param v2 (Vector3) the end point of the Quadratic Bezier
  4497. * @param nbPoints (integer) the wanted number of points in the curve
  4498. */
  4499. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  4500. nbPoints = nbPoints > 2 ? nbPoints : 3;
  4501. var bez = new Array();
  4502. var equation = function (t, val0, val1, val2) {
  4503. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  4504. return res;
  4505. };
  4506. for (var i = 0; i <= nbPoints; i++) {
  4507. 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)));
  4508. }
  4509. return new Curve3(bez);
  4510. };
  4511. /**
  4512. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  4513. * @param v0 (Vector3) the origin point of the Cubic Bezier
  4514. * @param v1 (Vector3) the first control point
  4515. * @param v2 (Vector3) the second control point
  4516. * @param v3 (Vector3) the end point of the Cubic Bezier
  4517. * @param nbPoints (integer) the wanted number of points in the curve
  4518. */
  4519. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  4520. nbPoints = nbPoints > 3 ? nbPoints : 4;
  4521. var bez = new Array();
  4522. var equation = function (t, val0, val1, val2, val3) {
  4523. 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;
  4524. return res;
  4525. };
  4526. for (var i = 0; i <= nbPoints; i++) {
  4527. 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)));
  4528. }
  4529. return new Curve3(bez);
  4530. };
  4531. /**
  4532. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  4533. * @param p1 (Vector3) the origin point of the Hermite Spline
  4534. * @param t1 (Vector3) the tangent vector at the origin point
  4535. * @param p2 (Vector3) the end point of the Hermite Spline
  4536. * @param t2 (Vector3) the tangent vector at the end point
  4537. * @param nbPoints (integer) the wanted number of points in the curve
  4538. */
  4539. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  4540. var hermite = new Array();
  4541. var step = 1.0 / nbPoints;
  4542. for (var i = 0; i <= nbPoints; i++) {
  4543. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  4544. }
  4545. return new Curve3(hermite);
  4546. };
  4547. /**
  4548. * Returns a Curve3 object along a CatmullRom Spline curve :
  4549. * @param points (array of Vector3) the points the spline must pass through. At least, four points required.
  4550. * @param nbPoints (integer) the wanted number of points between each curve control points.
  4551. */
  4552. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  4553. var totalPoints = new Array();
  4554. totalPoints.push(points[0].clone());
  4555. Array.prototype.push.apply(totalPoints, points);
  4556. totalPoints.push(points[points.length - 1].clone());
  4557. var catmullRom = new Array();
  4558. var step = 1.0 / nbPoints;
  4559. for (var i = 0; i < totalPoints.length - 3; i++) {
  4560. var amount = 0.0;
  4561. for (var c = 0; c < nbPoints; c++) {
  4562. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4563. amount += step;
  4564. }
  4565. }
  4566. i--;
  4567. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  4568. return new Curve3(catmullRom);
  4569. };
  4570. /**
  4571. * Returns the Curve3 stored array of successive Vector3
  4572. */
  4573. Curve3.prototype.getPoints = function () {
  4574. return this._points;
  4575. };
  4576. /**
  4577. * Returns the computed length (float) of the curve.
  4578. */
  4579. Curve3.prototype.length = function () {
  4580. return this._length;
  4581. };
  4582. /**
  4583. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  4584. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  4585. * curveA and curveB keep unchanged.
  4586. */
  4587. Curve3.prototype.continue = function (curve) {
  4588. var lastPoint = this._points[this._points.length - 1];
  4589. var continuedPoints = this._points.slice();
  4590. var curvePoints = curve.getPoints();
  4591. for (var i = 1; i < curvePoints.length; i++) {
  4592. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  4593. }
  4594. var continuedCurve = new Curve3(continuedPoints);
  4595. return continuedCurve;
  4596. };
  4597. Curve3.prototype._computeLength = function (path) {
  4598. var l = 0;
  4599. for (var i = 1; i < path.length; i++) {
  4600. l += (path[i].subtract(path[i - 1])).length();
  4601. }
  4602. return l;
  4603. };
  4604. return Curve3;
  4605. }());
  4606. BABYLON.Curve3 = Curve3;
  4607. // Vertex formats
  4608. var PositionNormalVertex = (function () {
  4609. function PositionNormalVertex(position, normal) {
  4610. if (position === void 0) { position = Vector3.Zero(); }
  4611. if (normal === void 0) { normal = Vector3.Up(); }
  4612. this.position = position;
  4613. this.normal = normal;
  4614. }
  4615. PositionNormalVertex.prototype.clone = function () {
  4616. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  4617. };
  4618. return PositionNormalVertex;
  4619. }());
  4620. BABYLON.PositionNormalVertex = PositionNormalVertex;
  4621. var PositionNormalTextureVertex = (function () {
  4622. function PositionNormalTextureVertex(position, normal, uv) {
  4623. if (position === void 0) { position = Vector3.Zero(); }
  4624. if (normal === void 0) { normal = Vector3.Up(); }
  4625. if (uv === void 0) { uv = Vector2.Zero(); }
  4626. this.position = position;
  4627. this.normal = normal;
  4628. this.uv = uv;
  4629. }
  4630. PositionNormalTextureVertex.prototype.clone = function () {
  4631. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  4632. };
  4633. return PositionNormalTextureVertex;
  4634. }());
  4635. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  4636. // Temporary pre-allocated objects for engine internal use
  4637. // usage in any internal function :
  4638. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  4639. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  4640. var Tmp = (function () {
  4641. function Tmp() {
  4642. }
  4643. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  4644. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  4645. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  4646. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  4647. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  4648. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  4649. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  4650. Matrix.Zero(), Matrix.Zero(),
  4651. Matrix.Zero(), Matrix.Zero(),
  4652. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  4653. return Tmp;
  4654. }());
  4655. BABYLON.Tmp = Tmp;
  4656. // Same as Tmp but not exported to keep it onyl for math functions to avoid conflicts
  4657. var MathTmp = (function () {
  4658. function MathTmp() {
  4659. }
  4660. MathTmp.Vector3 = [Vector3.Zero()];
  4661. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  4662. MathTmp.Quaternion = [Quaternion.Zero()];
  4663. return MathTmp;
  4664. }());
  4665. })(BABYLON || (BABYLON = {}));
  4666. //# sourceMappingURL=babylon.math.js.map
  4667. var BABYLON;
  4668. (function (BABYLON) {
  4669. var Scalar = (function () {
  4670. function Scalar() {
  4671. }
  4672. /**
  4673. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  4674. */
  4675. Scalar.WithinEpsilon = function (a, b, epsilon) {
  4676. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  4677. var num = a - b;
  4678. return -epsilon <= num && num <= epsilon;
  4679. };
  4680. /**
  4681. * Returns a string : the upper case translation of the number i to hexadecimal.
  4682. */
  4683. Scalar.ToHex = function (i) {
  4684. var str = i.toString(16);
  4685. if (i <= 15) {
  4686. return ("0" + str).toUpperCase();
  4687. }
  4688. return str.toUpperCase();
  4689. };
  4690. /**
  4691. * Returns -1 if value is negative and +1 is value is positive.
  4692. * Returns the value itself if it's equal to zero.
  4693. */
  4694. Scalar.Sign = function (value) {
  4695. value = +value; // convert to a number
  4696. if (value === 0 || isNaN(value))
  4697. return value;
  4698. return value > 0 ? 1 : -1;
  4699. };
  4700. /**
  4701. * Returns the value itself if it's between min and max.
  4702. * Returns min if the value is lower than min.
  4703. * Returns max if the value is greater than max.
  4704. */
  4705. Scalar.Clamp = function (value, min, max) {
  4706. if (min === void 0) { min = 0; }
  4707. if (max === void 0) { max = 1; }
  4708. return Math.min(max, Math.max(min, value));
  4709. };
  4710. /**
  4711. * Returns the log2 of value.
  4712. */
  4713. Scalar.Log2 = function (value) {
  4714. return Math.log(value) * Math.LOG2E;
  4715. };
  4716. /**
  4717. * Loops the value, so that it is never larger than length and never smaller than 0.
  4718. *
  4719. * This is similar to the modulo operator but it works with floating point numbers.
  4720. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  4721. * With t = 5 and length = 2.5, the result would be 0.0.
  4722. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  4723. */
  4724. Scalar.Repeat = function (value, length) {
  4725. return value - Math.floor(value / length) * length;
  4726. };
  4727. /**
  4728. * Normalize the value between 0.0 and 1.0 using min and max values
  4729. */
  4730. Scalar.Normalize = function (value, min, max) {
  4731. return (value - min) / (max - min);
  4732. };
  4733. /**
  4734. * Denormalize the value from 0.0 and 1.0 using min and max values
  4735. */
  4736. Scalar.Denormalize = function (normalized, min, max) {
  4737. return (normalized * (max - min) + min);
  4738. };
  4739. /**
  4740. * Calculates the shortest difference between two given angles given in degrees.
  4741. */
  4742. Scalar.DeltaAngle = function (current, target) {
  4743. var num = Scalar.Repeat(target - current, 360.0);
  4744. if (num > 180.0) {
  4745. num -= 360.0;
  4746. }
  4747. return num;
  4748. };
  4749. /**
  4750. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  4751. *
  4752. * The returned value will move back and forth between 0 and length
  4753. */
  4754. Scalar.PingPong = function (tx, length) {
  4755. var t = Scalar.Repeat(tx, length * 2.0);
  4756. return length - Math.abs(t - length);
  4757. };
  4758. /**
  4759. * Interpolates between min and max with smoothing at the limits.
  4760. *
  4761. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  4762. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  4763. */
  4764. Scalar.SmoothStep = function (from, to, tx) {
  4765. var t = Scalar.Clamp(tx);
  4766. t = -2.0 * t * t * t + 3.0 * t * t;
  4767. return to * t + from * (1.0 - t);
  4768. };
  4769. /**
  4770. * Moves a value current towards target.
  4771. *
  4772. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  4773. * Negative values of maxDelta pushes the value away from target.
  4774. */
  4775. Scalar.MoveTowards = function (current, target, maxDelta) {
  4776. var result = 0;
  4777. if (Math.abs(target - current) <= maxDelta) {
  4778. result = target;
  4779. }
  4780. else {
  4781. result = current + Scalar.Sign(target - current) * maxDelta;
  4782. }
  4783. return result;
  4784. };
  4785. /**
  4786. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4787. *
  4788. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  4789. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  4790. */
  4791. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  4792. var num = Scalar.DeltaAngle(current, target);
  4793. var result = 0;
  4794. if (-maxDelta < num && num < maxDelta) {
  4795. result = target;
  4796. }
  4797. else {
  4798. target = current + num;
  4799. result = Scalar.MoveTowards(current, target, maxDelta);
  4800. }
  4801. return result;
  4802. };
  4803. /**
  4804. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  4805. */
  4806. Scalar.Lerp = function (start, end, amount) {
  4807. return start + ((end - start) * amount);
  4808. };
  4809. /**
  4810. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  4811. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  4812. */
  4813. Scalar.LerpAngle = function (start, end, amount) {
  4814. var num = Scalar.Repeat(end - start, 360.0);
  4815. if (num > 180.0) {
  4816. num -= 360.0;
  4817. }
  4818. return start + num * Scalar.Clamp(amount);
  4819. };
  4820. /**
  4821. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  4822. */
  4823. Scalar.InverseLerp = function (a, b, value) {
  4824. var result = 0;
  4825. if (a != b) {
  4826. result = Scalar.Clamp((value - a) / (b - a));
  4827. }
  4828. else {
  4829. result = 0.0;
  4830. }
  4831. return result;
  4832. };
  4833. /**
  4834. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  4835. */
  4836. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  4837. var squared = amount * amount;
  4838. var cubed = amount * squared;
  4839. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  4840. var part2 = (-2.0 * cubed) + (3.0 * squared);
  4841. var part3 = (cubed - (2.0 * squared)) + amount;
  4842. var part4 = cubed - squared;
  4843. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  4844. };
  4845. /**
  4846. * Returns a random float number between and min and max values
  4847. */
  4848. Scalar.RandomRange = function (min, max) {
  4849. if (min === max)
  4850. return min;
  4851. return ((Math.random() * (max - min)) + min);
  4852. };
  4853. /**
  4854. * This function returns percentage of a number in a given range.
  4855. *
  4856. * RangeToPercent(40,20,60) will return 0.5 (50%)
  4857. * RangeToPercent(34,0,100) will return 0.34 (34%)
  4858. */
  4859. Scalar.RangeToPercent = function (number, min, max) {
  4860. return ((number - min) / (max - min));
  4861. };
  4862. /**
  4863. * This function returns number that corresponds to the percentage in a given range.
  4864. *
  4865. * PercentToRange(0.34,0,100) will return 34.
  4866. */
  4867. Scalar.PercentToRange = function (percent, min, max) {
  4868. return ((max - min) * percent + min);
  4869. };
  4870. return Scalar;
  4871. }());
  4872. BABYLON.Scalar = Scalar;
  4873. })(BABYLON || (BABYLON = {}));
  4874. //# sourceMappingURL=babylon.math.scalar.js.map
  4875. //# sourceMappingURL=babylon.mixins.js.map
  4876. var BABYLON;
  4877. (function (BABYLON) {
  4878. var __decoratorInitialStore = {};
  4879. var __mergedStore = {};
  4880. var _copySource = function (creationFunction, source, instanciate) {
  4881. var destination = creationFunction();
  4882. // Tags
  4883. if (BABYLON.Tags) {
  4884. BABYLON.Tags.AddTagsTo(destination, source.tags);
  4885. }
  4886. var classStore = getMergedStore(destination);
  4887. // Properties
  4888. for (var property in classStore) {
  4889. var propertyDescriptor = classStore[property];
  4890. var sourceProperty = source[property];
  4891. var propertyType = propertyDescriptor.type;
  4892. if (sourceProperty !== undefined && sourceProperty !== null) {
  4893. switch (propertyType) {
  4894. case 0: // Value
  4895. case 6:// Mesh reference
  4896. destination[property] = sourceProperty;
  4897. break;
  4898. case 1: // Texture
  4899. case 2: // Color3
  4900. case 3: // FresnelParameters
  4901. case 4: // Vector2
  4902. case 5: // Vector3
  4903. case 7:// Color Curves
  4904. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  4905. break;
  4906. }
  4907. }
  4908. }
  4909. return destination;
  4910. };
  4911. function getDirectStore(target) {
  4912. var classKey = target.getClassName();
  4913. if (!__decoratorInitialStore[classKey]) {
  4914. __decoratorInitialStore[classKey] = {};
  4915. }
  4916. return __decoratorInitialStore[classKey];
  4917. }
  4918. /**
  4919. * Return the list of properties flagged as serializable
  4920. * @param target: host object
  4921. */
  4922. function getMergedStore(target) {
  4923. var classKey = target.getClassName();
  4924. if (__mergedStore[classKey]) {
  4925. return __mergedStore[classKey];
  4926. }
  4927. __mergedStore[classKey] = {};
  4928. var store = __mergedStore[classKey];
  4929. var currentTarget = target;
  4930. var currentKey = classKey;
  4931. while (currentKey) {
  4932. var initialStore = __decoratorInitialStore[currentKey];
  4933. for (var property in initialStore) {
  4934. store[property] = initialStore[property];
  4935. }
  4936. var parent_1 = void 0;
  4937. var done = false;
  4938. do {
  4939. parent_1 = Object.getPrototypeOf(currentTarget);
  4940. if (!parent_1.getClassName) {
  4941. done = true;
  4942. break;
  4943. }
  4944. if (parent_1.getClassName() !== currentKey) {
  4945. break;
  4946. }
  4947. currentTarget = parent_1;
  4948. } while (parent_1);
  4949. if (done) {
  4950. break;
  4951. }
  4952. currentKey = parent_1.getClassName();
  4953. currentTarget = parent_1;
  4954. }
  4955. return store;
  4956. }
  4957. function generateSerializableMember(type, sourceName) {
  4958. return function (target, propertyKey) {
  4959. var classStore = getDirectStore(target);
  4960. if (!classStore[propertyKey]) {
  4961. classStore[propertyKey] = { type: type, sourceName: sourceName };
  4962. }
  4963. };
  4964. }
  4965. function generateExpandMember(setCallback, targetKey) {
  4966. return function (target, propertyKey) {
  4967. var key = targetKey || ("_" + propertyKey);
  4968. Object.defineProperty(target, propertyKey, {
  4969. get: function () {
  4970. return this[key];
  4971. },
  4972. set: function (value) {
  4973. if (this[key] === value) {
  4974. return;
  4975. }
  4976. this[key] = value;
  4977. target[setCallback].apply(this);
  4978. },
  4979. enumerable: true,
  4980. configurable: true
  4981. });
  4982. };
  4983. }
  4984. function expandToProperty(callback, targetKey) {
  4985. return generateExpandMember(callback, targetKey);
  4986. }
  4987. BABYLON.expandToProperty = expandToProperty;
  4988. function serialize(sourceName) {
  4989. return generateSerializableMember(0, sourceName); // value member
  4990. }
  4991. BABYLON.serialize = serialize;
  4992. function serializeAsTexture(sourceName) {
  4993. return generateSerializableMember(1, sourceName); // texture member
  4994. }
  4995. BABYLON.serializeAsTexture = serializeAsTexture;
  4996. function serializeAsColor3(sourceName) {
  4997. return generateSerializableMember(2, sourceName); // color3 member
  4998. }
  4999. BABYLON.serializeAsColor3 = serializeAsColor3;
  5000. function serializeAsFresnelParameters(sourceName) {
  5001. return generateSerializableMember(3, sourceName); // fresnel parameters member
  5002. }
  5003. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  5004. function serializeAsVector2(sourceName) {
  5005. return generateSerializableMember(4, sourceName); // vector2 member
  5006. }
  5007. BABYLON.serializeAsVector2 = serializeAsVector2;
  5008. function serializeAsVector3(sourceName) {
  5009. return generateSerializableMember(5, sourceName); // vector3 member
  5010. }
  5011. BABYLON.serializeAsVector3 = serializeAsVector3;
  5012. function serializeAsMeshReference(sourceName) {
  5013. return generateSerializableMember(6, sourceName); // mesh reference member
  5014. }
  5015. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  5016. function serializeAsColorCurves(sourceName) {
  5017. return generateSerializableMember(7, sourceName); // color curves
  5018. }
  5019. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  5020. function serializeAsColor4(sourceName) {
  5021. return generateSerializableMember(8, sourceName); // color 4
  5022. }
  5023. BABYLON.serializeAsColor4 = serializeAsColor4;
  5024. function serializeAsImageProcessingConfiguration(sourceName) {
  5025. return generateSerializableMember(9, sourceName); // image processing
  5026. }
  5027. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  5028. var SerializationHelper = (function () {
  5029. function SerializationHelper() {
  5030. }
  5031. SerializationHelper.Serialize = function (entity, serializationObject) {
  5032. if (!serializationObject) {
  5033. serializationObject = {};
  5034. }
  5035. // Tags
  5036. if (BABYLON.Tags) {
  5037. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  5038. }
  5039. var serializedProperties = getMergedStore(entity);
  5040. // Properties
  5041. for (var property in serializedProperties) {
  5042. var propertyDescriptor = serializedProperties[property];
  5043. var targetPropertyName = propertyDescriptor.sourceName || property;
  5044. var propertyType = propertyDescriptor.type;
  5045. var sourceProperty = entity[property];
  5046. if (sourceProperty !== undefined && sourceProperty !== null) {
  5047. switch (propertyType) {
  5048. case 0:// Value
  5049. serializationObject[targetPropertyName] = sourceProperty;
  5050. break;
  5051. case 1:// Texture
  5052. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5053. break;
  5054. case 2:// Color3
  5055. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5056. break;
  5057. case 3:// FresnelParameters
  5058. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5059. break;
  5060. case 4:// Vector2
  5061. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5062. break;
  5063. case 5:// Vector3
  5064. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5065. break;
  5066. case 6:// Mesh reference
  5067. serializationObject[targetPropertyName] = sourceProperty.id;
  5068. break;
  5069. case 7:// Color Curves
  5070. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5071. break;
  5072. case 8:// Color 4
  5073. serializationObject[targetPropertyName] = sourceProperty.asArray();
  5074. break;
  5075. case 9:// Image Processing
  5076. serializationObject[targetPropertyName] = sourceProperty.serialize();
  5077. break;
  5078. }
  5079. }
  5080. }
  5081. return serializationObject;
  5082. };
  5083. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  5084. var destination = creationFunction();
  5085. // Tags
  5086. if (BABYLON.Tags) {
  5087. BABYLON.Tags.AddTagsTo(destination, source.tags);
  5088. }
  5089. var classStore = getMergedStore(destination);
  5090. // Properties
  5091. for (var property in classStore) {
  5092. var propertyDescriptor = classStore[property];
  5093. var sourceProperty = source[propertyDescriptor.sourceName || property];
  5094. var propertyType = propertyDescriptor.type;
  5095. if (sourceProperty !== undefined && sourceProperty !== null) {
  5096. switch (propertyType) {
  5097. case 0:// Value
  5098. destination[property] = sourceProperty;
  5099. break;
  5100. case 1:// Texture
  5101. destination[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  5102. break;
  5103. case 2:// Color3
  5104. destination[property] = BABYLON.Color3.FromArray(sourceProperty);
  5105. break;
  5106. case 3:// FresnelParameters
  5107. destination[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  5108. break;
  5109. case 4:// Vector2
  5110. destination[property] = BABYLON.Vector2.FromArray(sourceProperty);
  5111. break;
  5112. case 5:// Vector3
  5113. destination[property] = BABYLON.Vector3.FromArray(sourceProperty);
  5114. break;
  5115. case 6:// Mesh reference
  5116. destination[property] = scene.getLastMeshByID(sourceProperty);
  5117. break;
  5118. case 7:// Color Curves
  5119. destination[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  5120. break;
  5121. case 8:// Color 4
  5122. destination[property] = BABYLON.Color4.FromArray(sourceProperty);
  5123. break;
  5124. case 9:// Image Processing
  5125. destination[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  5126. break;
  5127. }
  5128. }
  5129. }
  5130. return destination;
  5131. };
  5132. SerializationHelper.Clone = function (creationFunction, source) {
  5133. return _copySource(creationFunction, source, false);
  5134. };
  5135. SerializationHelper.Instanciate = function (creationFunction, source) {
  5136. return _copySource(creationFunction, source, true);
  5137. };
  5138. return SerializationHelper;
  5139. }());
  5140. BABYLON.SerializationHelper = SerializationHelper;
  5141. })(BABYLON || (BABYLON = {}));
  5142. //# sourceMappingURL=babylon.decorators.js.map
  5143. var BABYLON;
  5144. (function (BABYLON) {
  5145. /**
  5146. * A class serves as a medium between the observable and its observers
  5147. */
  5148. var EventState = (function () {
  5149. /**
  5150. * If the callback of a given Observer set skipNextObservers to true the following observers will be ignored
  5151. */
  5152. function EventState(mask, skipNextObservers) {
  5153. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5154. this.initalize(mask, skipNextObservers);
  5155. }
  5156. EventState.prototype.initalize = function (mask, skipNextObservers) {
  5157. if (skipNextObservers === void 0) { skipNextObservers = false; }
  5158. this.mask = mask;
  5159. this.skipNextObservers = skipNextObservers;
  5160. return this;
  5161. };
  5162. return EventState;
  5163. }());
  5164. BABYLON.EventState = EventState;
  5165. /**
  5166. * Represent an Observer registered to a given Observable object.
  5167. */
  5168. var Observer = (function () {
  5169. function Observer(callback, mask) {
  5170. this.callback = callback;
  5171. this.mask = mask;
  5172. }
  5173. return Observer;
  5174. }());
  5175. BABYLON.Observer = Observer;
  5176. /**
  5177. * The Observable class is a simple implementation of the Observable pattern.
  5178. * 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.
  5179. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  5180. * 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).
  5181. * 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.
  5182. */
  5183. var Observable = (function () {
  5184. function Observable() {
  5185. this._observers = new Array();
  5186. this._eventState = new EventState(0);
  5187. }
  5188. /**
  5189. * Create a new Observer with the specified callback
  5190. * @param callback the callback that will be executed for that Observer
  5191. * @param mask the mask used to filter observers
  5192. * @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.
  5193. */
  5194. Observable.prototype.add = function (callback, mask, insertFirst) {
  5195. if (mask === void 0) { mask = -1; }
  5196. if (insertFirst === void 0) { insertFirst = false; }
  5197. if (!callback) {
  5198. return null;
  5199. }
  5200. var observer = new Observer(callback, mask);
  5201. if (insertFirst) {
  5202. this._observers.unshift(observer);
  5203. }
  5204. else {
  5205. this._observers.push(observer);
  5206. }
  5207. return observer;
  5208. };
  5209. /**
  5210. * Remove an Observer from the Observable object
  5211. * @param observer the instance of the Observer to remove. If it doesn't belong to this Observable, false will be returned.
  5212. */
  5213. Observable.prototype.remove = function (observer) {
  5214. var index = this._observers.indexOf(observer);
  5215. if (index !== -1) {
  5216. this._observers.splice(index, 1);
  5217. return true;
  5218. }
  5219. return false;
  5220. };
  5221. /**
  5222. * Remove a callback from the Observable object
  5223. * @param callback the callback to remove. If it doesn't belong to this Observable, false will be returned.
  5224. */
  5225. Observable.prototype.removeCallback = function (callback) {
  5226. for (var index = 0; index < this._observers.length; index++) {
  5227. if (this._observers[index].callback === callback) {
  5228. this._observers.splice(index, 1);
  5229. return true;
  5230. }
  5231. }
  5232. return false;
  5233. };
  5234. /**
  5235. * Notify all Observers by calling their respective callback with the given data
  5236. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  5237. * @param eventData
  5238. * @param mask
  5239. */
  5240. Observable.prototype.notifyObservers = function (eventData, mask) {
  5241. if (mask === void 0) { mask = -1; }
  5242. var state = this._eventState;
  5243. state.mask = mask;
  5244. state.skipNextObservers = false;
  5245. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5246. var obs = _a[_i];
  5247. if (obs.mask & mask) {
  5248. obs.callback(eventData, state);
  5249. }
  5250. if (state.skipNextObservers) {
  5251. return false;
  5252. }
  5253. }
  5254. return true;
  5255. };
  5256. /**
  5257. * return true is the Observable has at least one Observer registered
  5258. */
  5259. Observable.prototype.hasObservers = function () {
  5260. return this._observers.length > 0;
  5261. };
  5262. /**
  5263. * Clear the list of observers
  5264. */
  5265. Observable.prototype.clear = function () {
  5266. this._observers = new Array();
  5267. };
  5268. /**
  5269. * Clone the current observable
  5270. */
  5271. Observable.prototype.clone = function () {
  5272. var result = new Observable();
  5273. result._observers = this._observers.slice(0);
  5274. return result;
  5275. };
  5276. /**
  5277. * Does this observable handles observer registered with a given mask
  5278. * @param {number} trigger - the mask to be tested
  5279. * @return {boolean} whether or not one observer registered with the given mask is handeled
  5280. **/
  5281. Observable.prototype.hasSpecificMask = function (mask) {
  5282. if (mask === void 0) { mask = -1; }
  5283. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  5284. var obs = _a[_i];
  5285. if (obs.mask & mask && obs.mask === mask) {
  5286. return true;
  5287. }
  5288. }
  5289. return false;
  5290. };
  5291. return Observable;
  5292. }());
  5293. BABYLON.Observable = Observable;
  5294. })(BABYLON || (BABYLON = {}));
  5295. //# sourceMappingURL=babylon.observable.js.map
  5296. var BABYLON;
  5297. (function (BABYLON) {
  5298. var SmartArray = (function () {
  5299. function SmartArray(capacity) {
  5300. this.length = 0;
  5301. this._duplicateId = 0;
  5302. this.data = new Array(capacity);
  5303. this._id = SmartArray._GlobalId++;
  5304. }
  5305. SmartArray.prototype.push = function (value) {
  5306. this.data[this.length++] = value;
  5307. if (this.length > this.data.length) {
  5308. this.data.length *= 2;
  5309. }
  5310. if (!value.__smartArrayFlags) {
  5311. value.__smartArrayFlags = {};
  5312. }
  5313. value.__smartArrayFlags[this._id] = this._duplicateId;
  5314. };
  5315. SmartArray.prototype.forEach = function (func) {
  5316. for (var index = 0; index < this.length; index++) {
  5317. func(this.data[index]);
  5318. }
  5319. };
  5320. SmartArray.prototype.pushNoDuplicate = function (value) {
  5321. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  5322. return false;
  5323. }
  5324. this.push(value);
  5325. return true;
  5326. };
  5327. SmartArray.prototype.sort = function (compareFn) {
  5328. this.data.sort(compareFn);
  5329. };
  5330. SmartArray.prototype.reset = function () {
  5331. this.length = 0;
  5332. this._duplicateId++;
  5333. };
  5334. SmartArray.prototype.dispose = function () {
  5335. this.reset();
  5336. if (this.data) {
  5337. this.data.length = 0;
  5338. this.data = null;
  5339. }
  5340. };
  5341. SmartArray.prototype.concat = function (array) {
  5342. if (array.length === 0) {
  5343. return;
  5344. }
  5345. if (this.length + array.length > this.data.length) {
  5346. this.data.length = (this.length + array.length) * 2;
  5347. }
  5348. for (var index = 0; index < array.length; index++) {
  5349. this.data[this.length++] = (array.data || array)[index];
  5350. }
  5351. };
  5352. SmartArray.prototype.concatWithNoDuplicate = function (array) {
  5353. if (array.length === 0) {
  5354. return;
  5355. }
  5356. if (this.length + array.length > this.data.length) {
  5357. this.data.length = (this.length + array.length) * 2;
  5358. }
  5359. for (var index = 0; index < array.length; index++) {
  5360. var item = (array.data || array)[index];
  5361. this.pushNoDuplicate(item);
  5362. }
  5363. };
  5364. SmartArray.prototype.indexOf = function (value) {
  5365. var position = this.data.indexOf(value);
  5366. if (position >= this.length) {
  5367. return -1;
  5368. }
  5369. return position;
  5370. };
  5371. SmartArray.prototype.contains = function (value) {
  5372. return this.data.indexOf(value) !== -1;
  5373. };
  5374. // Statics
  5375. SmartArray._GlobalId = 0;
  5376. return SmartArray;
  5377. }());
  5378. BABYLON.SmartArray = SmartArray;
  5379. })(BABYLON || (BABYLON = {}));
  5380. //# sourceMappingURL=babylon.smartArray.js.map
  5381. var BABYLON;
  5382. (function (BABYLON) {
  5383. // Screenshots
  5384. var screenshotCanvas;
  5385. var cloneValue = function (source, destinationObject) {
  5386. if (!source)
  5387. return null;
  5388. if (source instanceof BABYLON.Mesh) {
  5389. return null;
  5390. }
  5391. if (source instanceof BABYLON.SubMesh) {
  5392. return source.clone(destinationObject);
  5393. }
  5394. else if (source.clone) {
  5395. return source.clone();
  5396. }
  5397. return null;
  5398. };
  5399. var Tools = (function () {
  5400. function Tools() {
  5401. }
  5402. ;
  5403. /**
  5404. * Interpolates between a and b via alpha
  5405. * @param a The lower value (returned when alpha = 0)
  5406. * @param b The upper value (returned when alpha = 1)
  5407. * @param alpha The interpolation-factor
  5408. * @return The mixed value
  5409. */
  5410. Tools.Mix = function (a, b, alpha) {
  5411. return a * (1 - alpha) + b * alpha;
  5412. };
  5413. Tools.Instantiate = function (className) {
  5414. var arr = className.split(".");
  5415. var fn = (window || this);
  5416. for (var i = 0, len = arr.length; i < len; i++) {
  5417. fn = fn[arr[i]];
  5418. }
  5419. if (typeof fn !== "function") {
  5420. return null;
  5421. }
  5422. return fn;
  5423. };
  5424. Tools.SetImmediate = function (action) {
  5425. if (window.setImmediate) {
  5426. window.setImmediate(action);
  5427. }
  5428. else {
  5429. setTimeout(action, 1);
  5430. }
  5431. };
  5432. Tools.IsExponentOfTwo = function (value) {
  5433. var count = 1;
  5434. do {
  5435. count *= 2;
  5436. } while (count < value);
  5437. return count === value;
  5438. };
  5439. /**
  5440. * Find the next highest power of two.
  5441. * @param x Number to start search from.
  5442. * @return Next highest power of two.
  5443. */
  5444. Tools.CeilingPOT = function (x) {
  5445. x--;
  5446. x |= x >> 1;
  5447. x |= x >> 2;
  5448. x |= x >> 4;
  5449. x |= x >> 8;
  5450. x |= x >> 16;
  5451. x++;
  5452. return x;
  5453. };
  5454. /**
  5455. * Find the next lowest power of two.
  5456. * @param x Number to start search from.
  5457. * @return Next lowest power of two.
  5458. */
  5459. Tools.FloorPOT = function (x) {
  5460. x = x | (x >> 1);
  5461. x = x | (x >> 2);
  5462. x = x | (x >> 4);
  5463. x = x | (x >> 8);
  5464. x = x | (x >> 16);
  5465. return x - (x >> 1);
  5466. };
  5467. /**
  5468. * Find the nearest power of two.
  5469. * @param x Number to start search from.
  5470. * @return Next nearest power of two.
  5471. */
  5472. Tools.NearestPOT = function (x) {
  5473. var c = Tools.CeilingPOT(x);
  5474. var f = Tools.FloorPOT(x);
  5475. return (c - x) > (x - f) ? f : c;
  5476. };
  5477. Tools.GetExponentOfTwo = function (value, max, mode) {
  5478. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  5479. var pot;
  5480. switch (mode) {
  5481. case BABYLON.Engine.SCALEMODE_FLOOR:
  5482. pot = Tools.FloorPOT(value);
  5483. break;
  5484. case BABYLON.Engine.SCALEMODE_NEAREST:
  5485. pot = Tools.NearestPOT(value);
  5486. break;
  5487. case BABYLON.Engine.SCALEMODE_CEILING:
  5488. pot = Tools.CeilingPOT(value);
  5489. break;
  5490. }
  5491. return Math.min(pot, max);
  5492. };
  5493. Tools.GetFilename = function (path) {
  5494. var index = path.lastIndexOf("/");
  5495. if (index < 0)
  5496. return path;
  5497. return path.substring(index + 1);
  5498. };
  5499. Tools.GetDOMTextContent = function (element) {
  5500. var result = "";
  5501. var child = element.firstChild;
  5502. while (child) {
  5503. if (child.nodeType === 3) {
  5504. result += child.textContent;
  5505. }
  5506. child = child.nextSibling;
  5507. }
  5508. return result;
  5509. };
  5510. Tools.ToDegrees = function (angle) {
  5511. return angle * 180 / Math.PI;
  5512. };
  5513. Tools.ToRadians = function (angle) {
  5514. return angle * Math.PI / 180;
  5515. };
  5516. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  5517. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  5518. var output = "";
  5519. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  5520. var i = 0;
  5521. var bytes = new Uint8Array(buffer);
  5522. while (i < bytes.length) {
  5523. chr1 = bytes[i++];
  5524. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  5525. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  5526. enc1 = chr1 >> 2;
  5527. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  5528. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  5529. enc4 = chr3 & 63;
  5530. if (isNaN(chr2)) {
  5531. enc3 = enc4 = 64;
  5532. }
  5533. else if (isNaN(chr3)) {
  5534. enc4 = 64;
  5535. }
  5536. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  5537. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  5538. }
  5539. return "data:image/png;base64," + output;
  5540. };
  5541. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  5542. if (bias === void 0) { bias = null; }
  5543. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5544. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5545. for (var index = indexStart; index < indexStart + indexCount; index++) {
  5546. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  5547. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5548. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5549. }
  5550. if (bias) {
  5551. minimum.x -= minimum.x * bias.x + bias.y;
  5552. minimum.y -= minimum.y * bias.x + bias.y;
  5553. minimum.z -= minimum.z * bias.x + bias.y;
  5554. maximum.x += maximum.x * bias.x + bias.y;
  5555. maximum.y += maximum.y * bias.x + bias.y;
  5556. maximum.z += maximum.z * bias.x + bias.y;
  5557. }
  5558. return {
  5559. minimum: minimum,
  5560. maximum: maximum
  5561. };
  5562. };
  5563. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  5564. if (bias === void 0) { bias = null; }
  5565. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  5566. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  5567. if (!stride) {
  5568. stride = 3;
  5569. }
  5570. for (var index = start; index < start + count; index++) {
  5571. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  5572. minimum = BABYLON.Vector3.Minimize(current, minimum);
  5573. maximum = BABYLON.Vector3.Maximize(current, maximum);
  5574. }
  5575. if (bias) {
  5576. minimum.x -= minimum.x * bias.x + bias.y;
  5577. minimum.y -= minimum.y * bias.x + bias.y;
  5578. minimum.z -= minimum.z * bias.x + bias.y;
  5579. maximum.x += maximum.x * bias.x + bias.y;
  5580. maximum.y += maximum.y * bias.x + bias.y;
  5581. maximum.z += maximum.z * bias.x + bias.y;
  5582. }
  5583. return {
  5584. minimum: minimum,
  5585. maximum: maximum
  5586. };
  5587. };
  5588. Tools.Vector2ArrayFeeder = function (array) {
  5589. return function (index) {
  5590. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  5591. var length = isFloatArray ? array.length / 2 : array.length;
  5592. if (index >= length) {
  5593. return null;
  5594. }
  5595. if (isFloatArray) {
  5596. var fa = array;
  5597. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  5598. }
  5599. var a = array;
  5600. return a[index];
  5601. };
  5602. };
  5603. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  5604. if (bias === void 0) { bias = null; }
  5605. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  5606. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  5607. var i = 0;
  5608. var cur = feeder(i++);
  5609. while (cur) {
  5610. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  5611. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  5612. cur = feeder(i++);
  5613. }
  5614. if (bias) {
  5615. minimum.x -= minimum.x * bias.x + bias.y;
  5616. minimum.y -= minimum.y * bias.x + bias.y;
  5617. maximum.x += maximum.x * bias.x + bias.y;
  5618. maximum.y += maximum.y * bias.x + bias.y;
  5619. }
  5620. return {
  5621. minimum: minimum,
  5622. maximum: maximum
  5623. };
  5624. };
  5625. Tools.MakeArray = function (obj, allowsNullUndefined) {
  5626. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  5627. return undefined;
  5628. return Array.isArray(obj) ? obj : [obj];
  5629. };
  5630. // Misc.
  5631. Tools.GetPointerPrefix = function () {
  5632. var eventPrefix = "pointer";
  5633. // Check if pointer events are supported
  5634. if (!window.PointerEvent && !navigator.pointerEnabled) {
  5635. eventPrefix = "mouse";
  5636. }
  5637. return eventPrefix;
  5638. };
  5639. /**
  5640. * @param func - the function to be called
  5641. * @param requester - the object that will request the next frame. Falls back to window.
  5642. */
  5643. Tools.QueueNewFrame = function (func, requester) {
  5644. if (requester === void 0) { requester = window; }
  5645. //if WebVR is enabled AND presenting, requestAnimationFrame is triggered when enabled.
  5646. /*if(requester.isPresenting) {
  5647. return;
  5648. } else*/ if (requester.requestAnimationFrame)
  5649. requester.requestAnimationFrame(func);
  5650. else if (requester.msRequestAnimationFrame)
  5651. requester.msRequestAnimationFrame(func);
  5652. else if (requester.webkitRequestAnimationFrame)
  5653. requester.webkitRequestAnimationFrame(func);
  5654. else if (requester.mozRequestAnimationFrame)
  5655. requester.mozRequestAnimationFrame(func);
  5656. else if (requester.oRequestAnimationFrame)
  5657. requester.oRequestAnimationFrame(func);
  5658. else {
  5659. window.setTimeout(func, 16);
  5660. }
  5661. };
  5662. Tools.RequestFullscreen = function (element) {
  5663. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  5664. if (!requestFunction)
  5665. return;
  5666. requestFunction.call(element);
  5667. };
  5668. Tools.ExitFullscreen = function () {
  5669. if (document.exitFullscreen) {
  5670. document.exitFullscreen();
  5671. }
  5672. else if (document.mozCancelFullScreen) {
  5673. document.mozCancelFullScreen();
  5674. }
  5675. else if (document.webkitCancelFullScreen) {
  5676. document.webkitCancelFullScreen();
  5677. }
  5678. else if (document.msCancelFullScreen) {
  5679. document.msCancelFullScreen();
  5680. }
  5681. };
  5682. Tools.SetCorsBehavior = function (url, img) {
  5683. if (Tools.CorsBehavior) {
  5684. switch (typeof (Tools.CorsBehavior)) {
  5685. case "function":
  5686. var result = Tools.CorsBehavior(url);
  5687. if (result) {
  5688. img.crossOrigin = result;
  5689. }
  5690. break;
  5691. case "string":
  5692. default:
  5693. img.crossOrigin = Tools.CorsBehavior;
  5694. break;
  5695. }
  5696. }
  5697. };
  5698. // External files
  5699. Tools.CleanUrl = function (url) {
  5700. url = url.replace(/#/mg, "%23");
  5701. return url;
  5702. };
  5703. Tools.LoadImage = function (url, onload, onerror, database) {
  5704. if (url instanceof ArrayBuffer) {
  5705. url = Tools.EncodeArrayBufferTobase64(url);
  5706. }
  5707. url = Tools.CleanUrl(url);
  5708. url = Tools.PreprocessUrl(url);
  5709. var img = new Image();
  5710. if (url.substr(0, 5) !== "data:") {
  5711. Tools.SetCorsBehavior(url, img);
  5712. }
  5713. img.onload = function () {
  5714. onload(img);
  5715. };
  5716. img.onerror = function (err) {
  5717. Tools.Error("Error while trying to load image: " + url);
  5718. if (Tools.UseFallbackTexture) {
  5719. img.src = Tools.fallbackTexture;
  5720. onload(img);
  5721. }
  5722. else {
  5723. onerror();
  5724. }
  5725. };
  5726. var noIndexedDB = function () {
  5727. img.src = url;
  5728. };
  5729. var loadFromIndexedDB = function () {
  5730. database.loadImageFromDB(url, img);
  5731. };
  5732. //ANY database to do!
  5733. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  5734. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5735. }
  5736. else {
  5737. if (url.indexOf("file:") !== 0) {
  5738. noIndexedDB();
  5739. }
  5740. else {
  5741. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  5742. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  5743. try {
  5744. var blobURL;
  5745. try {
  5746. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  5747. }
  5748. catch (ex) {
  5749. // Chrome doesn't support oneTimeOnly parameter
  5750. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  5751. }
  5752. img.src = blobURL;
  5753. }
  5754. catch (e) {
  5755. img.src = null;
  5756. }
  5757. }
  5758. else {
  5759. Tools.Error("Image: " + textureName + " not found. Did you forget to provide it?");
  5760. img.src = Tools.fallbackTexture;
  5761. }
  5762. }
  5763. }
  5764. return img;
  5765. };
  5766. //ANY
  5767. Tools.LoadFile = function (url, callback, progressCallBack, database, useArrayBuffer, onError) {
  5768. url = Tools.CleanUrl(url);
  5769. url = Tools.PreprocessUrl(url);
  5770. var noIndexedDB = function () {
  5771. var request = new XMLHttpRequest();
  5772. var loadUrl = Tools.BaseUrl + url;
  5773. request.open('GET', loadUrl, true);
  5774. if (useArrayBuffer) {
  5775. request.responseType = "arraybuffer";
  5776. }
  5777. request.onprogress = progressCallBack;
  5778. request.onreadystatechange = function () {
  5779. // In case of undefined state in some browsers.
  5780. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  5781. request.onreadystatechange = null; //some browsers have issues where onreadystatechange can be called multiple times with the same value
  5782. if (request.status >= 200 && request.status < 300 || (navigator.isCocoonJS && (request.status === 0))) {
  5783. callback(!useArrayBuffer ? request.responseText : request.response);
  5784. }
  5785. else {
  5786. if (onError) {
  5787. onError(request);
  5788. }
  5789. else {
  5790. throw new Error("Error status: " + request.status + " - Unable to load " + loadUrl);
  5791. }
  5792. }
  5793. }
  5794. };
  5795. request.send(null);
  5796. };
  5797. var loadFromIndexedDB = function () {
  5798. database.loadFileFromDB(url, callback, progressCallBack, noIndexedDB, useArrayBuffer);
  5799. };
  5800. if (url.indexOf("file:") !== -1) {
  5801. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  5802. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  5803. Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], callback, progressCallBack, useArrayBuffer);
  5804. }
  5805. else {
  5806. Tools.Error("File: " + fileName + " not found. Did you forget to provide it?");
  5807. }
  5808. }
  5809. else {
  5810. // Caching all files
  5811. if (database && database.enableSceneOffline) {
  5812. database.openAsync(loadFromIndexedDB, noIndexedDB);
  5813. }
  5814. else {
  5815. noIndexedDB();
  5816. }
  5817. }
  5818. };
  5819. /**
  5820. * Load a script (identified by an url). When the url returns, the
  5821. * content of this file is added into a new script element, attached to the DOM (body element)
  5822. */
  5823. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  5824. var head = document.getElementsByTagName('head')[0];
  5825. var script = document.createElement('script');
  5826. script.type = 'text/javascript';
  5827. script.src = scriptUrl;
  5828. var self = this;
  5829. script.onload = function () {
  5830. if (onSuccess) {
  5831. onSuccess();
  5832. }
  5833. };
  5834. script.onerror = function () {
  5835. if (onError) {
  5836. onError();
  5837. }
  5838. };
  5839. head.appendChild(script);
  5840. };
  5841. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  5842. var reader = new FileReader();
  5843. reader.onload = function (e) {
  5844. //target doesn't have result from ts 1.3
  5845. callback(e.target['result']);
  5846. };
  5847. reader.onprogress = progressCallback;
  5848. reader.readAsDataURL(fileToLoad);
  5849. };
  5850. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  5851. var reader = new FileReader();
  5852. reader.onerror = function (e) {
  5853. Tools.Log("Error while reading file: " + fileToLoad.name);
  5854. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  5855. };
  5856. reader.onload = function (e) {
  5857. //target doesn't have result from ts 1.3
  5858. callback(e.target['result']);
  5859. };
  5860. reader.onprogress = progressCallBack;
  5861. if (!useArrayBuffer) {
  5862. // Asynchronous read
  5863. reader.readAsText(fileToLoad);
  5864. }
  5865. else {
  5866. reader.readAsArrayBuffer(fileToLoad);
  5867. }
  5868. };
  5869. //returns a downloadable url to a file content.
  5870. Tools.FileAsURL = function (content) {
  5871. var fileBlob = new Blob([content]);
  5872. var url = window.URL || window.webkitURL;
  5873. var link = url.createObjectURL(fileBlob);
  5874. return link;
  5875. };
  5876. // Misc.
  5877. Tools.Format = function (value, decimals) {
  5878. if (decimals === void 0) { decimals = 2; }
  5879. return value.toFixed(decimals);
  5880. };
  5881. Tools.CheckExtends = function (v, min, max) {
  5882. if (v.x < min.x)
  5883. min.x = v.x;
  5884. if (v.y < min.y)
  5885. min.y = v.y;
  5886. if (v.z < min.z)
  5887. min.z = v.z;
  5888. if (v.x > max.x)
  5889. max.x = v.x;
  5890. if (v.y > max.y)
  5891. max.y = v.y;
  5892. if (v.z > max.z)
  5893. max.z = v.z;
  5894. };
  5895. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  5896. for (var prop in source) {
  5897. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  5898. continue;
  5899. }
  5900. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  5901. continue;
  5902. }
  5903. var sourceValue = source[prop];
  5904. var typeOfSourceValue = typeof sourceValue;
  5905. if (typeOfSourceValue === "function") {
  5906. continue;
  5907. }
  5908. if (typeOfSourceValue === "object") {
  5909. if (sourceValue instanceof Array) {
  5910. destination[prop] = [];
  5911. if (sourceValue.length > 0) {
  5912. if (typeof sourceValue[0] == "object") {
  5913. for (var index = 0; index < sourceValue.length; index++) {
  5914. var clonedValue = cloneValue(sourceValue[index], destination);
  5915. if (destination[prop].indexOf(clonedValue) === -1) {
  5916. destination[prop].push(clonedValue);
  5917. }
  5918. }
  5919. }
  5920. else {
  5921. destination[prop] = sourceValue.slice(0);
  5922. }
  5923. }
  5924. }
  5925. else {
  5926. destination[prop] = cloneValue(sourceValue, destination);
  5927. }
  5928. }
  5929. else {
  5930. destination[prop] = sourceValue;
  5931. }
  5932. }
  5933. };
  5934. Tools.IsEmpty = function (obj) {
  5935. for (var i in obj) {
  5936. return false;
  5937. }
  5938. return true;
  5939. };
  5940. Tools.RegisterTopRootEvents = function (events) {
  5941. for (var index = 0; index < events.length; index++) {
  5942. var event = events[index];
  5943. window.addEventListener(event.name, event.handler, false);
  5944. try {
  5945. if (window.parent) {
  5946. window.parent.addEventListener(event.name, event.handler, false);
  5947. }
  5948. }
  5949. catch (e) {
  5950. // Silently fails...
  5951. }
  5952. }
  5953. };
  5954. Tools.UnregisterTopRootEvents = function (events) {
  5955. for (var index = 0; index < events.length; index++) {
  5956. var event = events[index];
  5957. window.removeEventListener(event.name, event.handler);
  5958. try {
  5959. if (window.parent) {
  5960. window.parent.removeEventListener(event.name, event.handler);
  5961. }
  5962. }
  5963. catch (e) {
  5964. // Silently fails...
  5965. }
  5966. }
  5967. };
  5968. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType) {
  5969. if (mimeType === void 0) { mimeType = "image/png"; }
  5970. // Read the contents of the framebuffer
  5971. var numberOfChannelsByLine = width * 4;
  5972. var halfHeight = height / 2;
  5973. //Reading datas from WebGL
  5974. var data = engine.readPixels(0, 0, width, height);
  5975. //To flip image on Y axis.
  5976. for (var i = 0; i < halfHeight; i++) {
  5977. for (var j = 0; j < numberOfChannelsByLine; j++) {
  5978. var currentCell = j + i * numberOfChannelsByLine;
  5979. var targetLine = height - i - 1;
  5980. var targetCell = j + targetLine * numberOfChannelsByLine;
  5981. var temp = data[currentCell];
  5982. data[currentCell] = data[targetCell];
  5983. data[targetCell] = temp;
  5984. }
  5985. }
  5986. // Create a 2D canvas to store the result
  5987. if (!screenshotCanvas) {
  5988. screenshotCanvas = document.createElement('canvas');
  5989. }
  5990. screenshotCanvas.width = width;
  5991. screenshotCanvas.height = height;
  5992. var context = screenshotCanvas.getContext('2d');
  5993. // Copy the pixels to a 2D canvas
  5994. var imageData = context.createImageData(width, height);
  5995. var castData = (imageData.data);
  5996. castData.set(data);
  5997. context.putImageData(imageData, 0, 0);
  5998. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  5999. };
  6000. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType) {
  6001. if (mimeType === void 0) { mimeType = "image/png"; }
  6002. var base64Image = screenshotCanvas.toDataURL(mimeType);
  6003. if (successCallback) {
  6004. successCallback(base64Image);
  6005. }
  6006. else {
  6007. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  6008. if (("download" in document.createElement("a"))) {
  6009. var a = window.document.createElement("a");
  6010. a.href = base64Image;
  6011. var date = new Date();
  6012. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  6013. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  6014. window.document.body.appendChild(a);
  6015. a.addEventListener("click", function () {
  6016. a.parentElement.removeChild(a);
  6017. });
  6018. a.click();
  6019. //Or opening a new tab with the image if it is not possible to automatically start download.
  6020. }
  6021. else {
  6022. var newWindow = window.open("");
  6023. var img = newWindow.document.createElement("img");
  6024. img.src = base64Image;
  6025. newWindow.document.body.appendChild(img);
  6026. }
  6027. }
  6028. };
  6029. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  6030. if (mimeType === void 0) { mimeType = "image/png"; }
  6031. var width;
  6032. var height;
  6033. // If a precision value is specified
  6034. if (size.precision) {
  6035. width = Math.round(engine.getRenderWidth() * size.precision);
  6036. height = Math.round(width / engine.getAspectRatio(camera));
  6037. }
  6038. else if (size.width && size.height) {
  6039. width = size.width;
  6040. height = size.height;
  6041. }
  6042. else if (size.width && !size.height) {
  6043. width = size.width;
  6044. height = Math.round(width / engine.getAspectRatio(camera));
  6045. }
  6046. else if (size.height && !size.width) {
  6047. height = size.height;
  6048. width = Math.round(height * engine.getAspectRatio(camera));
  6049. }
  6050. else if (!isNaN(size)) {
  6051. height = size;
  6052. width = size;
  6053. }
  6054. else {
  6055. Tools.Error("Invalid 'size' parameter !");
  6056. return;
  6057. }
  6058. if (!screenshotCanvas) {
  6059. screenshotCanvas = document.createElement('canvas');
  6060. }
  6061. screenshotCanvas.width = width;
  6062. screenshotCanvas.height = height;
  6063. var renderContext = screenshotCanvas.getContext("2d");
  6064. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  6065. var newWidth = width;
  6066. var newHeight = newWidth / ratio;
  6067. if (newHeight > height) {
  6068. newHeight = height;
  6069. newWidth = newHeight * ratio;
  6070. }
  6071. var offsetX = Math.max(0, width - newWidth) / 2;
  6072. var offsetY = Math.max(0, height - newHeight) / 2;
  6073. renderContext.drawImage(engine.getRenderingCanvas(), offsetX, offsetY, newWidth, newHeight);
  6074. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  6075. };
  6076. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples) {
  6077. if (mimeType === void 0) { mimeType = "image/png"; }
  6078. if (samples === void 0) { samples = 1; }
  6079. var width;
  6080. var height;
  6081. //If a precision value is specified
  6082. if (size.precision) {
  6083. width = Math.round(engine.getRenderWidth() * size.precision);
  6084. height = Math.round(width / engine.getAspectRatio(camera));
  6085. size = { width: width, height: height };
  6086. }
  6087. else if (size.width && size.height) {
  6088. width = size.width;
  6089. height = size.height;
  6090. }
  6091. else if (size.width && !size.height) {
  6092. width = size.width;
  6093. height = Math.round(width / engine.getAspectRatio(camera));
  6094. size = { width: width, height: height };
  6095. }
  6096. else if (size.height && !size.width) {
  6097. height = size.height;
  6098. width = Math.round(height * engine.getAspectRatio(camera));
  6099. size = { width: width, height: height };
  6100. }
  6101. else if (!isNaN(size)) {
  6102. height = size;
  6103. width = size;
  6104. }
  6105. else {
  6106. Tools.Error("Invalid 'size' parameter !");
  6107. return;
  6108. }
  6109. var scene = camera.getScene();
  6110. var previousCamera = null;
  6111. if (scene.activeCamera !== camera) {
  6112. previousCamera = scene.activeCamera;
  6113. scene.activeCamera = camera;
  6114. }
  6115. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  6116. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  6117. texture.renderList = null;
  6118. texture.samples = samples;
  6119. texture.onAfterRenderObservable.add(function () {
  6120. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType);
  6121. });
  6122. scene.incrementRenderId();
  6123. scene.resetCachedMaterial();
  6124. texture.render(true);
  6125. texture.dispose();
  6126. if (previousCamera) {
  6127. scene.activeCamera = previousCamera;
  6128. }
  6129. camera.getProjectionMatrix(true); // Force cache refresh;
  6130. };
  6131. // XHR response validator for local file scenario
  6132. Tools.ValidateXHRData = function (xhr, dataType) {
  6133. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  6134. if (dataType === void 0) { dataType = 7; }
  6135. try {
  6136. if (dataType & 1) {
  6137. if (xhr.responseText && xhr.responseText.length > 0) {
  6138. return true;
  6139. }
  6140. else if (dataType === 1) {
  6141. return false;
  6142. }
  6143. }
  6144. if (dataType & 2) {
  6145. // Check header width and height since there is no "TGA" magic number
  6146. var tgaHeader = BABYLON.Internals.TGATools.GetTGAHeader(xhr.response);
  6147. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  6148. return true;
  6149. }
  6150. else if (dataType === 2) {
  6151. return false;
  6152. }
  6153. }
  6154. if (dataType & 4) {
  6155. // Check for the "DDS" magic number
  6156. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  6157. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  6158. return true;
  6159. }
  6160. else {
  6161. return false;
  6162. }
  6163. }
  6164. }
  6165. catch (e) {
  6166. // Global protection
  6167. }
  6168. return false;
  6169. };
  6170. /**
  6171. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  6172. * Be aware Math.random() could cause collisions, but:
  6173. * "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"
  6174. */
  6175. Tools.RandomId = function () {
  6176. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  6177. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  6178. return v.toString(16);
  6179. });
  6180. };
  6181. Object.defineProperty(Tools, "NoneLogLevel", {
  6182. get: function () {
  6183. return Tools._NoneLogLevel;
  6184. },
  6185. enumerable: true,
  6186. configurable: true
  6187. });
  6188. Object.defineProperty(Tools, "MessageLogLevel", {
  6189. get: function () {
  6190. return Tools._MessageLogLevel;
  6191. },
  6192. enumerable: true,
  6193. configurable: true
  6194. });
  6195. Object.defineProperty(Tools, "WarningLogLevel", {
  6196. get: function () {
  6197. return Tools._WarningLogLevel;
  6198. },
  6199. enumerable: true,
  6200. configurable: true
  6201. });
  6202. Object.defineProperty(Tools, "ErrorLogLevel", {
  6203. get: function () {
  6204. return Tools._ErrorLogLevel;
  6205. },
  6206. enumerable: true,
  6207. configurable: true
  6208. });
  6209. Object.defineProperty(Tools, "AllLogLevel", {
  6210. get: function () {
  6211. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  6212. },
  6213. enumerable: true,
  6214. configurable: true
  6215. });
  6216. Tools._AddLogEntry = function (entry) {
  6217. Tools._LogCache = entry + Tools._LogCache;
  6218. if (Tools.OnNewCacheEntry) {
  6219. Tools.OnNewCacheEntry(entry);
  6220. }
  6221. };
  6222. Tools._FormatMessage = function (message) {
  6223. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  6224. var date = new Date();
  6225. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  6226. };
  6227. Tools._LogDisabled = function (message) {
  6228. // nothing to do
  6229. };
  6230. Tools._LogEnabled = function (message) {
  6231. var formattedMessage = Tools._FormatMessage(message);
  6232. console.log("BJS - " + formattedMessage);
  6233. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  6234. Tools._AddLogEntry(entry);
  6235. };
  6236. Tools._WarnDisabled = function (message) {
  6237. // nothing to do
  6238. };
  6239. Tools._WarnEnabled = function (message) {
  6240. var formattedMessage = Tools._FormatMessage(message);
  6241. console.warn("BJS - " + formattedMessage);
  6242. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  6243. Tools._AddLogEntry(entry);
  6244. };
  6245. Tools._ErrorDisabled = function (message) {
  6246. // nothing to do
  6247. };
  6248. Tools._ErrorEnabled = function (message) {
  6249. Tools.errorsCount++;
  6250. var formattedMessage = Tools._FormatMessage(message);
  6251. console.error("BJS - " + formattedMessage);
  6252. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  6253. Tools._AddLogEntry(entry);
  6254. };
  6255. Object.defineProperty(Tools, "LogCache", {
  6256. get: function () {
  6257. return Tools._LogCache;
  6258. },
  6259. enumerable: true,
  6260. configurable: true
  6261. });
  6262. Tools.ClearLogCache = function () {
  6263. Tools._LogCache = "";
  6264. Tools.errorsCount = 0;
  6265. };
  6266. Object.defineProperty(Tools, "LogLevels", {
  6267. set: function (level) {
  6268. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  6269. Tools.Log = Tools._LogEnabled;
  6270. }
  6271. else {
  6272. Tools.Log = Tools._LogDisabled;
  6273. }
  6274. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  6275. Tools.Warn = Tools._WarnEnabled;
  6276. }
  6277. else {
  6278. Tools.Warn = Tools._WarnDisabled;
  6279. }
  6280. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  6281. Tools.Error = Tools._ErrorEnabled;
  6282. }
  6283. else {
  6284. Tools.Error = Tools._ErrorDisabled;
  6285. }
  6286. },
  6287. enumerable: true,
  6288. configurable: true
  6289. });
  6290. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  6291. get: function () {
  6292. return Tools._PerformanceNoneLogLevel;
  6293. },
  6294. enumerable: true,
  6295. configurable: true
  6296. });
  6297. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  6298. get: function () {
  6299. return Tools._PerformanceUserMarkLogLevel;
  6300. },
  6301. enumerable: true,
  6302. configurable: true
  6303. });
  6304. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  6305. get: function () {
  6306. return Tools._PerformanceConsoleLogLevel;
  6307. },
  6308. enumerable: true,
  6309. configurable: true
  6310. });
  6311. Object.defineProperty(Tools, "PerformanceLogLevel", {
  6312. set: function (level) {
  6313. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  6314. Tools.StartPerformanceCounter = Tools._StartUserMark;
  6315. Tools.EndPerformanceCounter = Tools._EndUserMark;
  6316. return;
  6317. }
  6318. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  6319. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  6320. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  6321. return;
  6322. }
  6323. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6324. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6325. },
  6326. enumerable: true,
  6327. configurable: true
  6328. });
  6329. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  6330. };
  6331. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  6332. };
  6333. Tools._StartUserMark = function (counterName, condition) {
  6334. if (condition === void 0) { condition = true; }
  6335. if (!condition || !Tools._performance.mark) {
  6336. return;
  6337. }
  6338. Tools._performance.mark(counterName + "-Begin");
  6339. };
  6340. Tools._EndUserMark = function (counterName, condition) {
  6341. if (condition === void 0) { condition = true; }
  6342. if (!condition || !Tools._performance.mark) {
  6343. return;
  6344. }
  6345. Tools._performance.mark(counterName + "-End");
  6346. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  6347. };
  6348. Tools._StartPerformanceConsole = function (counterName, condition) {
  6349. if (condition === void 0) { condition = true; }
  6350. if (!condition) {
  6351. return;
  6352. }
  6353. Tools._StartUserMark(counterName, condition);
  6354. if (console.time) {
  6355. console.time(counterName);
  6356. }
  6357. };
  6358. Tools._EndPerformanceConsole = function (counterName, condition) {
  6359. if (condition === void 0) { condition = true; }
  6360. if (!condition) {
  6361. return;
  6362. }
  6363. Tools._EndUserMark(counterName, condition);
  6364. if (console.time) {
  6365. console.timeEnd(counterName);
  6366. }
  6367. };
  6368. Object.defineProperty(Tools, "Now", {
  6369. get: function () {
  6370. if (window.performance && window.performance.now) {
  6371. return window.performance.now();
  6372. }
  6373. return new Date().getTime();
  6374. },
  6375. enumerable: true,
  6376. configurable: true
  6377. });
  6378. /**
  6379. * This method will return the name of the class used to create the instance of the given object.
  6380. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  6381. * @param object the object to get the class name from
  6382. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  6383. */
  6384. Tools.GetClassName = function (object, isType) {
  6385. if (isType === void 0) { isType = false; }
  6386. var name = null;
  6387. if (!isType && object.getClassName) {
  6388. name = object.getClassName();
  6389. }
  6390. else {
  6391. if (object instanceof Object) {
  6392. var classObj = isType ? object : Object.getPrototypeOf(object);
  6393. name = classObj.constructor["__bjsclassName__"];
  6394. }
  6395. if (!name) {
  6396. name = typeof object;
  6397. }
  6398. }
  6399. return name;
  6400. };
  6401. Tools.first = function (array, predicate) {
  6402. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  6403. var el = array_1[_i];
  6404. if (predicate(el)) {
  6405. return el;
  6406. }
  6407. }
  6408. };
  6409. /**
  6410. * This method will return the name of the full name of the class, including its owning module (if any).
  6411. * 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).
  6412. * @param object the object to get the class name from
  6413. * @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.
  6414. */
  6415. Tools.getFullClassName = function (object, isType) {
  6416. if (isType === void 0) { isType = false; }
  6417. var className = null;
  6418. var moduleName = null;
  6419. if (!isType && object.getClassName) {
  6420. className = object.getClassName();
  6421. }
  6422. else {
  6423. if (object instanceof Object) {
  6424. var classObj = isType ? object : Object.getPrototypeOf(object);
  6425. className = classObj.constructor["__bjsclassName__"];
  6426. moduleName = classObj.constructor["__bjsmoduleName__"];
  6427. }
  6428. if (!className) {
  6429. className = typeof object;
  6430. }
  6431. }
  6432. if (!className) {
  6433. return null;
  6434. }
  6435. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  6436. };
  6437. /**
  6438. * 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.
  6439. * @param array
  6440. */
  6441. Tools.arrayOrStringFeeder = function (array) {
  6442. return function (index) {
  6443. if (index >= array.length) {
  6444. return null;
  6445. }
  6446. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  6447. if (val && val.getHashCode) {
  6448. val = val.getHashCode();
  6449. }
  6450. if (typeof val === "string") {
  6451. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  6452. }
  6453. return val;
  6454. };
  6455. };
  6456. /**
  6457. * Compute the hashCode of a stream of number
  6458. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  6459. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  6460. * @return the hash code computed
  6461. */
  6462. Tools.hashCodeFromStream = function (feeder) {
  6463. // Based from here: http://stackoverflow.com/a/7616484/802124
  6464. var hash = 0;
  6465. var index = 0;
  6466. var chr = feeder(index++);
  6467. while (chr != null) {
  6468. hash = ((hash << 5) - hash) + chr;
  6469. hash |= 0; // Convert to 32bit integer
  6470. chr = feeder(index++);
  6471. }
  6472. return hash;
  6473. };
  6474. Tools.BaseUrl = "";
  6475. Tools.CorsBehavior = "anonymous";
  6476. Tools.UseFallbackTexture = true;
  6477. // Used in case of a texture loading problem
  6478. Tools.fallbackTexture = "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";
  6479. Tools.PreprocessUrl = function (url) {
  6480. return url;
  6481. };
  6482. // Logs
  6483. Tools._NoneLogLevel = 0;
  6484. Tools._MessageLogLevel = 1;
  6485. Tools._WarningLogLevel = 2;
  6486. Tools._ErrorLogLevel = 4;
  6487. Tools._LogCache = "";
  6488. Tools.errorsCount = 0;
  6489. Tools.Log = Tools._LogEnabled;
  6490. Tools.Warn = Tools._WarnEnabled;
  6491. Tools.Error = Tools._ErrorEnabled;
  6492. // Performances
  6493. Tools._PerformanceNoneLogLevel = 0;
  6494. Tools._PerformanceUserMarkLogLevel = 1;
  6495. Tools._PerformanceConsoleLogLevel = 2;
  6496. Tools._performance = window.performance;
  6497. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  6498. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  6499. return Tools;
  6500. }());
  6501. BABYLON.Tools = Tools;
  6502. /**
  6503. * This class is used to track a performance counter which is number based.
  6504. * The user has access to many properties which give statistics of different nature
  6505. *
  6506. * The implementer can track two kinds of Performance Counter: time and count
  6507. * 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.
  6508. * 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.
  6509. */
  6510. var PerfCounter = (function () {
  6511. function PerfCounter() {
  6512. this._startMonitoringTime = 0;
  6513. this._min = 0;
  6514. this._max = 0;
  6515. this._average = 0;
  6516. this._lastSecAverage = 0;
  6517. this._current = 0;
  6518. this._totalValueCount = 0;
  6519. this._totalAccumulated = 0;
  6520. this._lastSecAccumulated = 0;
  6521. this._lastSecTime = 0;
  6522. this._lastSecValueCount = 0;
  6523. }
  6524. Object.defineProperty(PerfCounter.prototype, "min", {
  6525. /**
  6526. * Returns the smallest value ever
  6527. */
  6528. get: function () {
  6529. return this._min;
  6530. },
  6531. enumerable: true,
  6532. configurable: true
  6533. });
  6534. Object.defineProperty(PerfCounter.prototype, "max", {
  6535. /**
  6536. * Returns the biggest value ever
  6537. */
  6538. get: function () {
  6539. return this._max;
  6540. },
  6541. enumerable: true,
  6542. configurable: true
  6543. });
  6544. Object.defineProperty(PerfCounter.prototype, "average", {
  6545. /**
  6546. * Returns the average value since the performance counter is running
  6547. */
  6548. get: function () {
  6549. return this._average;
  6550. },
  6551. enumerable: true,
  6552. configurable: true
  6553. });
  6554. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  6555. /**
  6556. * Returns the average value of the last second the counter was monitored
  6557. */
  6558. get: function () {
  6559. return this._lastSecAverage;
  6560. },
  6561. enumerable: true,
  6562. configurable: true
  6563. });
  6564. Object.defineProperty(PerfCounter.prototype, "current", {
  6565. /**
  6566. * Returns the current value
  6567. */
  6568. get: function () {
  6569. return this._current;
  6570. },
  6571. enumerable: true,
  6572. configurable: true
  6573. });
  6574. Object.defineProperty(PerfCounter.prototype, "total", {
  6575. get: function () {
  6576. return this._totalAccumulated;
  6577. },
  6578. enumerable: true,
  6579. configurable: true
  6580. });
  6581. /**
  6582. * Call this method to start monitoring a new frame.
  6583. * 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.
  6584. */
  6585. PerfCounter.prototype.fetchNewFrame = function () {
  6586. this._totalValueCount++;
  6587. this._current = 0;
  6588. this._lastSecValueCount++;
  6589. };
  6590. /**
  6591. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  6592. * @param newCount the count value to add to the monitored count
  6593. * @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.
  6594. */
  6595. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  6596. if (!PerfCounter.Enabled) {
  6597. return;
  6598. }
  6599. this._current += newCount;
  6600. if (fetchResult) {
  6601. this._fetchResult();
  6602. }
  6603. };
  6604. /**
  6605. * Start monitoring this performance counter
  6606. */
  6607. PerfCounter.prototype.beginMonitoring = function () {
  6608. if (!PerfCounter.Enabled) {
  6609. return;
  6610. }
  6611. this._startMonitoringTime = Tools.Now;
  6612. };
  6613. /**
  6614. * Compute the time lapsed since the previous beginMonitoring() call.
  6615. * @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
  6616. */
  6617. PerfCounter.prototype.endMonitoring = function (newFrame) {
  6618. if (newFrame === void 0) { newFrame = true; }
  6619. if (!PerfCounter.Enabled) {
  6620. return;
  6621. }
  6622. if (newFrame) {
  6623. this.fetchNewFrame();
  6624. }
  6625. var currentTime = Tools.Now;
  6626. this._current = currentTime - this._startMonitoringTime;
  6627. if (newFrame) {
  6628. this._fetchResult();
  6629. }
  6630. };
  6631. PerfCounter.prototype._fetchResult = function () {
  6632. this._totalAccumulated += this._current;
  6633. this._lastSecAccumulated += this._current;
  6634. // Min/Max update
  6635. this._min = Math.min(this._min, this._current);
  6636. this._max = Math.max(this._max, this._current);
  6637. this._average = this._totalAccumulated / this._totalValueCount;
  6638. // Reset last sec?
  6639. var now = Tools.Now;
  6640. if ((now - this._lastSecTime) > 1000) {
  6641. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  6642. this._lastSecTime = now;
  6643. this._lastSecAccumulated = 0;
  6644. this._lastSecValueCount = 0;
  6645. }
  6646. };
  6647. PerfCounter.Enabled = true;
  6648. return PerfCounter;
  6649. }());
  6650. BABYLON.PerfCounter = PerfCounter;
  6651. /**
  6652. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  6653. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  6654. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  6655. * @param name The name of the class, case should be preserved
  6656. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  6657. */
  6658. function className(name, module) {
  6659. return function (target) {
  6660. target["__bjsclassName__"] = name;
  6661. target["__bjsmoduleName__"] = (module != null) ? module : null;
  6662. };
  6663. }
  6664. BABYLON.className = className;
  6665. /**
  6666. * An implementation of a loop for asynchronous functions.
  6667. */
  6668. var AsyncLoop = (function () {
  6669. /**
  6670. * Constroctor.
  6671. * @param iterations the number of iterations.
  6672. * @param _fn the function to run each iteration
  6673. * @param _successCallback the callback that will be called upon succesful execution
  6674. * @param offset starting offset.
  6675. */
  6676. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  6677. if (offset === void 0) { offset = 0; }
  6678. this.iterations = iterations;
  6679. this._fn = _fn;
  6680. this._successCallback = _successCallback;
  6681. this.index = offset - 1;
  6682. this._done = false;
  6683. }
  6684. /**
  6685. * Execute the next iteration. Must be called after the last iteration was finished.
  6686. */
  6687. AsyncLoop.prototype.executeNext = function () {
  6688. if (!this._done) {
  6689. if (this.index + 1 < this.iterations) {
  6690. ++this.index;
  6691. this._fn(this);
  6692. }
  6693. else {
  6694. this.breakLoop();
  6695. }
  6696. }
  6697. };
  6698. /**
  6699. * Break the loop and run the success callback.
  6700. */
  6701. AsyncLoop.prototype.breakLoop = function () {
  6702. this._done = true;
  6703. this._successCallback();
  6704. };
  6705. /**
  6706. * Helper function
  6707. */
  6708. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  6709. if (offset === void 0) { offset = 0; }
  6710. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  6711. loop.executeNext();
  6712. return loop;
  6713. };
  6714. /**
  6715. * A for-loop that will run a given number of iterations synchronous and the rest async.
  6716. * @param iterations total number of iterations
  6717. * @param syncedIterations number of synchronous iterations in each async iteration.
  6718. * @param fn the function to call each iteration.
  6719. * @param callback a success call back that will be called when iterating stops.
  6720. * @param breakFunction a break condition (optional)
  6721. * @param timeout timeout settings for the setTimeout function. default - 0.
  6722. * @constructor
  6723. */
  6724. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  6725. if (timeout === void 0) { timeout = 0; }
  6726. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  6727. if (breakFunction && breakFunction())
  6728. loop.breakLoop();
  6729. else {
  6730. setTimeout(function () {
  6731. for (var i = 0; i < syncedIterations; ++i) {
  6732. var iteration = (loop.index * syncedIterations) + i;
  6733. if (iteration >= iterations)
  6734. break;
  6735. fn(iteration);
  6736. if (breakFunction && breakFunction()) {
  6737. loop.breakLoop();
  6738. break;
  6739. }
  6740. }
  6741. loop.executeNext();
  6742. }, timeout);
  6743. }
  6744. }, callback);
  6745. };
  6746. return AsyncLoop;
  6747. }());
  6748. BABYLON.AsyncLoop = AsyncLoop;
  6749. })(BABYLON || (BABYLON = {}));
  6750. //# sourceMappingURL=babylon.tools.js.map
  6751. var BABYLON;
  6752. (function (BABYLON) {
  6753. var Internals;
  6754. (function (Internals) {
  6755. var _AlphaState = (function () {
  6756. /**
  6757. * Initializes the state.
  6758. */
  6759. function _AlphaState() {
  6760. this._isAlphaBlendDirty = false;
  6761. this._isBlendFunctionParametersDirty = false;
  6762. this._isBlendEquationParametersDirty = false;
  6763. this._isBlendConstantsDirty = false;
  6764. this._alphaBlend = false;
  6765. this._blendFunctionParameters = new Array(4);
  6766. this._blendEquationParameters = new Array(2);
  6767. this._blendConstants = new Array(4);
  6768. this.reset();
  6769. }
  6770. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  6771. get: function () {
  6772. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  6773. },
  6774. enumerable: true,
  6775. configurable: true
  6776. });
  6777. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  6778. get: function () {
  6779. return this._alphaBlend;
  6780. },
  6781. set: function (value) {
  6782. if (this._alphaBlend === value) {
  6783. return;
  6784. }
  6785. this._alphaBlend = value;
  6786. this._isAlphaBlendDirty = true;
  6787. },
  6788. enumerable: true,
  6789. configurable: true
  6790. });
  6791. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  6792. if (this._blendConstants[0] === r &&
  6793. this._blendConstants[1] === g &&
  6794. this._blendConstants[2] === b &&
  6795. this._blendConstants[3] === a) {
  6796. return;
  6797. }
  6798. this._blendConstants[0] = r;
  6799. this._blendConstants[1] = g;
  6800. this._blendConstants[2] = b;
  6801. this._blendConstants[3] = a;
  6802. this._isBlendConstantsDirty = true;
  6803. };
  6804. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  6805. if (this._blendFunctionParameters[0] === value0 &&
  6806. this._blendFunctionParameters[1] === value1 &&
  6807. this._blendFunctionParameters[2] === value2 &&
  6808. this._blendFunctionParameters[3] === value3) {
  6809. return;
  6810. }
  6811. this._blendFunctionParameters[0] = value0;
  6812. this._blendFunctionParameters[1] = value1;
  6813. this._blendFunctionParameters[2] = value2;
  6814. this._blendFunctionParameters[3] = value3;
  6815. this._isBlendFunctionParametersDirty = true;
  6816. };
  6817. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  6818. if (this._blendEquationParameters[0] === rgb &&
  6819. this._blendEquationParameters[1] === alpha) {
  6820. return;
  6821. }
  6822. this._blendEquationParameters[0] = rgb;
  6823. this._blendEquationParameters[1] = alpha;
  6824. this._isBlendEquationParametersDirty = true;
  6825. };
  6826. _AlphaState.prototype.reset = function () {
  6827. this._alphaBlend = false;
  6828. this._blendFunctionParameters[0] = null;
  6829. this._blendFunctionParameters[1] = null;
  6830. this._blendFunctionParameters[2] = null;
  6831. this._blendFunctionParameters[3] = null;
  6832. this._blendEquationParameters[0] = null;
  6833. this._blendEquationParameters[1] = null;
  6834. this._blendConstants[0] = null;
  6835. this._blendConstants[1] = null;
  6836. this._blendConstants[2] = null;
  6837. this._blendConstants[3] = null;
  6838. this._isAlphaBlendDirty = true;
  6839. this._isBlendFunctionParametersDirty = false;
  6840. this._isBlendEquationParametersDirty = false;
  6841. this._isBlendConstantsDirty = false;
  6842. };
  6843. _AlphaState.prototype.apply = function (gl) {
  6844. if (!this.isDirty) {
  6845. return;
  6846. }
  6847. // Alpha blend
  6848. if (this._isAlphaBlendDirty) {
  6849. if (this._alphaBlend) {
  6850. gl.enable(gl.BLEND);
  6851. }
  6852. else {
  6853. gl.disable(gl.BLEND);
  6854. }
  6855. this._isAlphaBlendDirty = false;
  6856. }
  6857. // Alpha function
  6858. if (this._isBlendFunctionParametersDirty) {
  6859. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  6860. this._isBlendFunctionParametersDirty = false;
  6861. }
  6862. // Alpha equation
  6863. if (this._isBlendEquationParametersDirty) {
  6864. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  6865. this._isBlendEquationParametersDirty = false;
  6866. }
  6867. // Constants
  6868. if (this._isBlendConstantsDirty) {
  6869. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  6870. this._isBlendConstantsDirty = false;
  6871. }
  6872. };
  6873. return _AlphaState;
  6874. }());
  6875. Internals._AlphaState = _AlphaState;
  6876. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  6877. })(BABYLON || (BABYLON = {}));
  6878. //# sourceMappingURL=babylon.alphaCullingState.js.map
  6879. var BABYLON;
  6880. (function (BABYLON) {
  6881. var Internals;
  6882. (function (Internals) {
  6883. var _DepthCullingState = (function () {
  6884. /**
  6885. * Initializes the state.
  6886. */
  6887. function _DepthCullingState() {
  6888. this._isDepthTestDirty = false;
  6889. this._isDepthMaskDirty = false;
  6890. this._isDepthFuncDirty = false;
  6891. this._isCullFaceDirty = false;
  6892. this._isCullDirty = false;
  6893. this._isZOffsetDirty = false;
  6894. this.reset();
  6895. }
  6896. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  6897. get: function () {
  6898. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty;
  6899. },
  6900. enumerable: true,
  6901. configurable: true
  6902. });
  6903. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  6904. get: function () {
  6905. return this._zOffset;
  6906. },
  6907. set: function (value) {
  6908. if (this._zOffset === value) {
  6909. return;
  6910. }
  6911. this._zOffset = value;
  6912. this._isZOffsetDirty = true;
  6913. },
  6914. enumerable: true,
  6915. configurable: true
  6916. });
  6917. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  6918. get: function () {
  6919. return this._cullFace;
  6920. },
  6921. set: function (value) {
  6922. if (this._cullFace === value) {
  6923. return;
  6924. }
  6925. this._cullFace = value;
  6926. this._isCullFaceDirty = true;
  6927. },
  6928. enumerable: true,
  6929. configurable: true
  6930. });
  6931. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  6932. get: function () {
  6933. return this._cull;
  6934. },
  6935. set: function (value) {
  6936. if (this._cull === value) {
  6937. return;
  6938. }
  6939. this._cull = value;
  6940. this._isCullDirty = true;
  6941. },
  6942. enumerable: true,
  6943. configurable: true
  6944. });
  6945. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  6946. get: function () {
  6947. return this._depthFunc;
  6948. },
  6949. set: function (value) {
  6950. if (this._depthFunc === value) {
  6951. return;
  6952. }
  6953. this._depthFunc = value;
  6954. this._isDepthFuncDirty = true;
  6955. },
  6956. enumerable: true,
  6957. configurable: true
  6958. });
  6959. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  6960. get: function () {
  6961. return this._depthMask;
  6962. },
  6963. set: function (value) {
  6964. if (this._depthMask === value) {
  6965. return;
  6966. }
  6967. this._depthMask = value;
  6968. this._isDepthMaskDirty = true;
  6969. },
  6970. enumerable: true,
  6971. configurable: true
  6972. });
  6973. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  6974. get: function () {
  6975. return this._depthTest;
  6976. },
  6977. set: function (value) {
  6978. if (this._depthTest === value) {
  6979. return;
  6980. }
  6981. this._depthTest = value;
  6982. this._isDepthTestDirty = true;
  6983. },
  6984. enumerable: true,
  6985. configurable: true
  6986. });
  6987. _DepthCullingState.prototype.reset = function () {
  6988. this._depthMask = true;
  6989. this._depthTest = true;
  6990. this._depthFunc = null;
  6991. this._cullFace = null;
  6992. this._cull = null;
  6993. this._zOffset = 0;
  6994. this._isDepthTestDirty = true;
  6995. this._isDepthMaskDirty = true;
  6996. this._isDepthFuncDirty = false;
  6997. this._isCullFaceDirty = false;
  6998. this._isCullDirty = false;
  6999. this._isZOffsetDirty = false;
  7000. };
  7001. _DepthCullingState.prototype.apply = function (gl) {
  7002. if (!this.isDirty) {
  7003. return;
  7004. }
  7005. // Cull
  7006. if (this._isCullDirty) {
  7007. if (this.cull) {
  7008. gl.enable(gl.CULL_FACE);
  7009. }
  7010. else {
  7011. gl.disable(gl.CULL_FACE);
  7012. }
  7013. this._isCullDirty = false;
  7014. }
  7015. // Cull face
  7016. if (this._isCullFaceDirty) {
  7017. gl.cullFace(this.cullFace);
  7018. this._isCullFaceDirty = false;
  7019. }
  7020. // Depth mask
  7021. if (this._isDepthMaskDirty) {
  7022. gl.depthMask(this.depthMask);
  7023. this._isDepthMaskDirty = false;
  7024. }
  7025. // Depth test
  7026. if (this._isDepthTestDirty) {
  7027. if (this.depthTest) {
  7028. gl.enable(gl.DEPTH_TEST);
  7029. }
  7030. else {
  7031. gl.disable(gl.DEPTH_TEST);
  7032. }
  7033. this._isDepthTestDirty = false;
  7034. }
  7035. // Depth func
  7036. if (this._isDepthFuncDirty) {
  7037. gl.depthFunc(this.depthFunc);
  7038. this._isDepthFuncDirty = false;
  7039. }
  7040. // zOffset
  7041. if (this._isZOffsetDirty) {
  7042. if (this.zOffset) {
  7043. gl.enable(gl.POLYGON_OFFSET_FILL);
  7044. gl.polygonOffset(this.zOffset, 0);
  7045. }
  7046. else {
  7047. gl.disable(gl.POLYGON_OFFSET_FILL);
  7048. }
  7049. this._isZOffsetDirty = false;
  7050. }
  7051. };
  7052. return _DepthCullingState;
  7053. }());
  7054. Internals._DepthCullingState = _DepthCullingState;
  7055. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7056. })(BABYLON || (BABYLON = {}));
  7057. //# sourceMappingURL=babylon.depthCullingState.js.map
  7058. var BABYLON;
  7059. (function (BABYLON) {
  7060. var Internals;
  7061. (function (Internals) {
  7062. var _StencilState = (function () {
  7063. function _StencilState() {
  7064. this._isStencilTestDirty = false;
  7065. this._isStencilMaskDirty = false;
  7066. this._isStencilFuncDirty = false;
  7067. this._isStencilOpDirty = false;
  7068. this.reset();
  7069. }
  7070. Object.defineProperty(_StencilState.prototype, "isDirty", {
  7071. get: function () {
  7072. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  7073. },
  7074. enumerable: true,
  7075. configurable: true
  7076. });
  7077. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  7078. get: function () {
  7079. return this._stencilFunc;
  7080. },
  7081. set: function (value) {
  7082. if (this._stencilFunc === value) {
  7083. return;
  7084. }
  7085. this._stencilFunc = value;
  7086. this._isStencilFuncDirty = true;
  7087. },
  7088. enumerable: true,
  7089. configurable: true
  7090. });
  7091. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  7092. get: function () {
  7093. return this._stencilFuncRef;
  7094. },
  7095. set: function (value) {
  7096. if (this._stencilFuncRef === value) {
  7097. return;
  7098. }
  7099. this._stencilFuncRef = value;
  7100. this._isStencilFuncDirty = true;
  7101. },
  7102. enumerable: true,
  7103. configurable: true
  7104. });
  7105. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  7106. get: function () {
  7107. return this._stencilFuncMask;
  7108. },
  7109. set: function (value) {
  7110. if (this._stencilFuncMask === value) {
  7111. return;
  7112. }
  7113. this._stencilFuncMask = value;
  7114. this._isStencilFuncDirty = true;
  7115. },
  7116. enumerable: true,
  7117. configurable: true
  7118. });
  7119. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  7120. get: function () {
  7121. return this._stencilOpStencilFail;
  7122. },
  7123. set: function (value) {
  7124. if (this._stencilOpStencilFail === value) {
  7125. return;
  7126. }
  7127. this._stencilOpStencilFail = value;
  7128. this._isStencilOpDirty = true;
  7129. },
  7130. enumerable: true,
  7131. configurable: true
  7132. });
  7133. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  7134. get: function () {
  7135. return this._stencilOpDepthFail;
  7136. },
  7137. set: function (value) {
  7138. if (this._stencilOpDepthFail === value) {
  7139. return;
  7140. }
  7141. this._stencilOpDepthFail = value;
  7142. this._isStencilOpDirty = true;
  7143. },
  7144. enumerable: true,
  7145. configurable: true
  7146. });
  7147. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  7148. get: function () {
  7149. return this._stencilOpStencilDepthPass;
  7150. },
  7151. set: function (value) {
  7152. if (this._stencilOpStencilDepthPass === value) {
  7153. return;
  7154. }
  7155. this._stencilOpStencilDepthPass = value;
  7156. this._isStencilOpDirty = true;
  7157. },
  7158. enumerable: true,
  7159. configurable: true
  7160. });
  7161. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  7162. get: function () {
  7163. return this._stencilMask;
  7164. },
  7165. set: function (value) {
  7166. if (this._stencilMask === value) {
  7167. return;
  7168. }
  7169. this._stencilMask = value;
  7170. this._isStencilMaskDirty = true;
  7171. },
  7172. enumerable: true,
  7173. configurable: true
  7174. });
  7175. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  7176. get: function () {
  7177. return this._stencilTest;
  7178. },
  7179. set: function (value) {
  7180. if (this._stencilTest === value) {
  7181. return;
  7182. }
  7183. this._stencilTest = value;
  7184. this._isStencilTestDirty = true;
  7185. },
  7186. enumerable: true,
  7187. configurable: true
  7188. });
  7189. _StencilState.prototype.reset = function () {
  7190. this._stencilTest = false;
  7191. this._stencilMask = 0xFF;
  7192. this._stencilFunc = BABYLON.Engine.ALWAYS;
  7193. this._stencilFuncRef = 1;
  7194. this._stencilFuncMask = 0xFF;
  7195. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  7196. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  7197. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  7198. this._isStencilTestDirty = true;
  7199. this._isStencilMaskDirty = true;
  7200. this._isStencilFuncDirty = true;
  7201. this._isStencilOpDirty = true;
  7202. };
  7203. _StencilState.prototype.apply = function (gl) {
  7204. if (!this.isDirty) {
  7205. return;
  7206. }
  7207. // Stencil test
  7208. if (this._isStencilTestDirty) {
  7209. if (this.stencilTest) {
  7210. gl.enable(gl.STENCIL_TEST);
  7211. }
  7212. else {
  7213. gl.disable(gl.STENCIL_TEST);
  7214. }
  7215. this._isStencilTestDirty = false;
  7216. }
  7217. // Stencil mask
  7218. if (this._isStencilMaskDirty) {
  7219. gl.stencilMask(this.stencilMask);
  7220. this._isStencilMaskDirty = false;
  7221. }
  7222. // Stencil func
  7223. if (this._isStencilFuncDirty) {
  7224. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  7225. this._isStencilFuncDirty = false;
  7226. }
  7227. // Stencil op
  7228. if (this._isStencilOpDirty) {
  7229. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  7230. this._isStencilOpDirty = false;
  7231. }
  7232. };
  7233. return _StencilState;
  7234. }());
  7235. Internals._StencilState = _StencilState;
  7236. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  7237. })(BABYLON || (BABYLON = {}));
  7238. //# sourceMappingURL=babylon.stencilState.js.map
  7239. var BABYLON;
  7240. (function (BABYLON) {
  7241. var compileShader = function (gl, source, type, defines, shaderVersion) {
  7242. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  7243. gl.shaderSource(shader, shaderVersion + (defines ? defines + "\n" : "") + source);
  7244. gl.compileShader(shader);
  7245. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  7246. throw new Error(gl.getShaderInfoLog(shader));
  7247. }
  7248. return shader;
  7249. };
  7250. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  7251. var magFilter = gl.NEAREST;
  7252. var minFilter = gl.NEAREST;
  7253. switch (samplingMode) {
  7254. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  7255. magFilter = gl.LINEAR;
  7256. if (generateMipMaps) {
  7257. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7258. }
  7259. else {
  7260. minFilter = gl.LINEAR;
  7261. }
  7262. break;
  7263. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  7264. magFilter = gl.LINEAR;
  7265. if (generateMipMaps) {
  7266. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7267. }
  7268. else {
  7269. minFilter = gl.LINEAR;
  7270. }
  7271. break;
  7272. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  7273. magFilter = gl.NEAREST;
  7274. if (generateMipMaps) {
  7275. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7276. }
  7277. else {
  7278. minFilter = gl.NEAREST;
  7279. }
  7280. break;
  7281. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  7282. magFilter = gl.NEAREST;
  7283. if (generateMipMaps) {
  7284. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7285. }
  7286. else {
  7287. minFilter = gl.NEAREST;
  7288. }
  7289. break;
  7290. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  7291. magFilter = gl.NEAREST;
  7292. if (generateMipMaps) {
  7293. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  7294. }
  7295. else {
  7296. minFilter = gl.LINEAR;
  7297. }
  7298. break;
  7299. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  7300. magFilter = gl.NEAREST;
  7301. if (generateMipMaps) {
  7302. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  7303. }
  7304. else {
  7305. minFilter = gl.LINEAR;
  7306. }
  7307. break;
  7308. case BABYLON.Texture.NEAREST_LINEAR:
  7309. magFilter = gl.NEAREST;
  7310. minFilter = gl.LINEAR;
  7311. break;
  7312. case BABYLON.Texture.NEAREST_NEAREST:
  7313. magFilter = gl.NEAREST;
  7314. minFilter = gl.NEAREST;
  7315. break;
  7316. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  7317. magFilter = gl.LINEAR;
  7318. if (generateMipMaps) {
  7319. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  7320. }
  7321. else {
  7322. minFilter = gl.NEAREST;
  7323. }
  7324. break;
  7325. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  7326. magFilter = gl.LINEAR;
  7327. if (generateMipMaps) {
  7328. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  7329. }
  7330. else {
  7331. minFilter = gl.NEAREST;
  7332. }
  7333. break;
  7334. case BABYLON.Texture.LINEAR_LINEAR:
  7335. magFilter = gl.LINEAR;
  7336. minFilter = gl.LINEAR;
  7337. break;
  7338. case BABYLON.Texture.LINEAR_NEAREST:
  7339. magFilter = gl.LINEAR;
  7340. minFilter = gl.NEAREST;
  7341. break;
  7342. }
  7343. return {
  7344. min: minFilter,
  7345. mag: magFilter
  7346. };
  7347. };
  7348. var partialLoad = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  7349. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  7350. var img;
  7351. var onload = function () {
  7352. loadedImages[index] = img;
  7353. loadedImages._internalCount++;
  7354. if (scene) {
  7355. scene._removePendingData(img);
  7356. }
  7357. if (loadedImages._internalCount === 6) {
  7358. onfinish(loadedImages);
  7359. }
  7360. };
  7361. var onerror = function () {
  7362. if (scene) {
  7363. scene._removePendingData(img);
  7364. }
  7365. if (onErrorCallBack) {
  7366. onErrorCallBack();
  7367. }
  7368. };
  7369. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  7370. if (scene) {
  7371. scene._addPendingData(img);
  7372. }
  7373. };
  7374. var cascadeLoad = function (rootUrl, scene, onfinish, files, onError) {
  7375. if (onError === void 0) { onError = null; }
  7376. var loadedImages = [];
  7377. loadedImages._internalCount = 0;
  7378. for (var index = 0; index < 6; index++) {
  7379. partialLoad(files[index], index, loadedImages, scene, onfinish, onError);
  7380. }
  7381. };
  7382. var BufferPointer = (function () {
  7383. function BufferPointer() {
  7384. }
  7385. return BufferPointer;
  7386. }());
  7387. var InstancingAttributeInfo = (function () {
  7388. function InstancingAttributeInfo() {
  7389. }
  7390. return InstancingAttributeInfo;
  7391. }());
  7392. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  7393. /**
  7394. * Define options used to create a render target texture
  7395. */
  7396. var RenderTargetCreationOptions = (function () {
  7397. function RenderTargetCreationOptions() {
  7398. }
  7399. return RenderTargetCreationOptions;
  7400. }());
  7401. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  7402. /**
  7403. * Regroup several parameters relative to the browser in use
  7404. */
  7405. var EngineCapabilities = (function () {
  7406. function EngineCapabilities() {
  7407. }
  7408. return EngineCapabilities;
  7409. }());
  7410. BABYLON.EngineCapabilities = EngineCapabilities;
  7411. /**
  7412. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio.
  7413. */
  7414. var Engine = (function () {
  7415. /**
  7416. * @constructor
  7417. * @param {HTMLCanvasElement | WebGLRenderingContext} canvasOrContext - the canvas or the webgl context to be used for rendering
  7418. * @param {boolean} [antialias] - enable antialias
  7419. * @param options - further options to be sent to the getContext function
  7420. */
  7421. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  7422. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  7423. var _this = this;
  7424. // Public members
  7425. this.forcePOTTextures = false;
  7426. this.isFullscreen = false;
  7427. this.isPointerLock = false;
  7428. this.cullBackFaces = true;
  7429. this.renderEvenInBackground = true;
  7430. this.preventCacheWipeBetweenFrames = false;
  7431. // To enable/disable IDB support and avoid XHR on .manifest
  7432. this.enableOfflineSupport = false;
  7433. this.scenes = new Array();
  7434. this.postProcesses = new Array();
  7435. // Observables
  7436. /**
  7437. * Observable event triggered each time the rendering canvas is resized
  7438. */
  7439. this.onResizeObservable = new BABYLON.Observable();
  7440. /**
  7441. * Observable event triggered each time the canvas lost focus
  7442. */
  7443. this.onCanvasBlurObservable = new BABYLON.Observable();
  7444. // Uniform buffers list
  7445. this._uniformBuffers = new Array();
  7446. this._windowIsBackground = false;
  7447. this._webGLVersion = 1.0;
  7448. this._badOS = false;
  7449. this._badDesktopOS = false;
  7450. this._drawCalls = new BABYLON.PerfCounter();
  7451. this._renderingQueueLaunched = false;
  7452. this._activeRenderLoops = [];
  7453. // Deterministic lockstepMaxSteps
  7454. this._deterministicLockstep = false;
  7455. this._lockstepMaxSteps = 4;
  7456. this._contextWasLost = false;
  7457. this._doNotHandleContextLost = false;
  7458. // FPS
  7459. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  7460. this._fps = 60;
  7461. this._deltaTime = 0;
  7462. /**
  7463. * Turn this value on if you want to pause FPS computation when in background
  7464. */
  7465. this.disablePerformanceMonitorInBackground = false;
  7466. // States
  7467. this._depthCullingState = new BABYLON.Internals._DepthCullingState();
  7468. this._stencilState = new BABYLON.Internals._StencilState();
  7469. this._alphaState = new BABYLON.Internals._AlphaState();
  7470. this._alphaMode = Engine.ALPHA_DISABLE;
  7471. // Cache
  7472. this._internalTexturesCache = new Array();
  7473. this._maxTextureChannels = 16;
  7474. this._activeTexturesCache = {};
  7475. this._compiledEffects = {};
  7476. this._vertexAttribArraysEnabled = [];
  7477. this._uintIndicesCurrentlySet = false;
  7478. this._currentBoundBuffer = new Array();
  7479. this._currentBufferPointers = new Array();
  7480. this._currentInstanceLocations = new Array();
  7481. this._currentInstanceBuffers = new Array();
  7482. this._vaoRecordInProgress = false;
  7483. this._mustWipeVertexAttributes = false;
  7484. // Hardware supported Compressed Textures
  7485. this._texturesSupported = new Array();
  7486. this._onVRFullScreenTriggered = function () {
  7487. if (_this._vrDisplayEnabled && _this._vrDisplayEnabled.isPresenting) {
  7488. //get the old size before we change
  7489. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  7490. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  7491. //get the width and height, change the render size
  7492. var leftEye = _this._vrDisplayEnabled.getEyeParameters('left');
  7493. var width, height;
  7494. _this.setHardwareScalingLevel(1);
  7495. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  7496. }
  7497. else {
  7498. //When the specs are implemented, need to uncomment this.
  7499. //this._vrDisplayEnabled.cancelAnimationFrame(this._vrAnimationFrameHandler);
  7500. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  7501. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  7502. _this._vrDisplayEnabled = undefined;
  7503. }
  7504. };
  7505. var canvas;
  7506. Engine.Instances.push(this);
  7507. options = options || {};
  7508. if (canvasOrContext.getContext) {
  7509. canvas = canvasOrContext;
  7510. this._renderingCanvas = canvas;
  7511. if (antialias != null) {
  7512. options.antialias = antialias;
  7513. }
  7514. if (options.deterministicLockstep === undefined) {
  7515. options.deterministicLockstep = false;
  7516. }
  7517. if (options.lockstepMaxSteps === undefined) {
  7518. options.lockstepMaxSteps = 4;
  7519. }
  7520. if (options.preserveDrawingBuffer === undefined) {
  7521. options.preserveDrawingBuffer = false;
  7522. }
  7523. if (options.audioEngine === undefined) {
  7524. options.audioEngine = true;
  7525. }
  7526. if (options.stencil === undefined) {
  7527. options.stencil = true;
  7528. }
  7529. this._deterministicLockstep = options.deterministicLockstep;
  7530. this._lockstepMaxSteps = options.lockstepMaxSteps;
  7531. this._doNotHandleContextLost = options.doNotHandleContextLost;
  7532. // GL
  7533. if (!options.disableWebGL2Support) {
  7534. try {
  7535. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  7536. if (this._gl) {
  7537. this._webGLVersion = 2.0;
  7538. }
  7539. }
  7540. catch (e) {
  7541. // Do nothing
  7542. }
  7543. }
  7544. if (!this._gl) {
  7545. if (!canvas) {
  7546. throw new Error("The provided canvas is null or undefined.");
  7547. }
  7548. try {
  7549. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  7550. }
  7551. catch (e) {
  7552. throw new Error("WebGL not supported");
  7553. }
  7554. }
  7555. if (!this._gl) {
  7556. throw new Error("WebGL not supported");
  7557. }
  7558. this._onBlur = function () {
  7559. if (_this.disablePerformanceMonitorInBackground) {
  7560. _this._performanceMonitor.disable();
  7561. }
  7562. _this._windowIsBackground = true;
  7563. };
  7564. this._onFocus = function () {
  7565. if (_this.disablePerformanceMonitorInBackground) {
  7566. _this._performanceMonitor.enable();
  7567. }
  7568. _this._windowIsBackground = false;
  7569. };
  7570. this._onCanvasBlur = function () {
  7571. _this.onCanvasBlurObservable.notifyObservers(_this);
  7572. };
  7573. window.addEventListener("blur", this._onBlur);
  7574. window.addEventListener("focus", this._onFocus);
  7575. canvas.addEventListener("pointerout", this._onCanvasBlur);
  7576. }
  7577. else {
  7578. this._gl = canvasOrContext;
  7579. this._renderingCanvas = this._gl.canvas;
  7580. if (this._gl.renderbufferStorageMultisample) {
  7581. this._webGLVersion = 2.0;
  7582. }
  7583. options.stencil = this._gl.getContextAttributes().stencil;
  7584. }
  7585. // Context lost
  7586. if (!this._doNotHandleContextLost) {
  7587. this._onContextLost = function (evt) {
  7588. evt.preventDefault();
  7589. _this._contextWasLost = true;
  7590. BABYLON.Tools.Warn("WebGL context lost.");
  7591. };
  7592. this._onContextRestored = function (evt) {
  7593. // Rebuild gl context
  7594. _this._initGLContext();
  7595. // Rebuild effects
  7596. _this._rebuildEffects();
  7597. // Rebuild textures
  7598. _this._rebuildInternalTextures();
  7599. // Rebuild buffers
  7600. _this._rebuildBuffers();
  7601. // Cache
  7602. _this.wipeCaches(true);
  7603. BABYLON.Tools.Warn("WebGL context successfully restored.");
  7604. _this._contextWasLost = false;
  7605. };
  7606. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  7607. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  7608. }
  7609. // Viewport
  7610. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  7611. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  7612. this.resize();
  7613. this._isStencilEnable = options.stencil;
  7614. this._initGLContext();
  7615. if (canvas) {
  7616. // Fullscreen
  7617. this._onFullscreenChange = function () {
  7618. if (document.fullscreen !== undefined) {
  7619. _this.isFullscreen = document.fullscreen;
  7620. }
  7621. else if (document.mozFullScreen !== undefined) {
  7622. _this.isFullscreen = document.mozFullScreen;
  7623. }
  7624. else if (document.webkitIsFullScreen !== undefined) {
  7625. _this.isFullscreen = document.webkitIsFullScreen;
  7626. }
  7627. else if (document.msIsFullScreen !== undefined) {
  7628. _this.isFullscreen = document.msIsFullScreen;
  7629. }
  7630. // Pointer lock
  7631. if (_this.isFullscreen && _this._pointerLockRequested) {
  7632. canvas.requestPointerLock = canvas.requestPointerLock ||
  7633. canvas.msRequestPointerLock ||
  7634. canvas.mozRequestPointerLock ||
  7635. canvas.webkitRequestPointerLock;
  7636. if (canvas.requestPointerLock) {
  7637. canvas.requestPointerLock();
  7638. }
  7639. }
  7640. };
  7641. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  7642. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  7643. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  7644. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  7645. // Pointer lock
  7646. this._onPointerLockChange = function () {
  7647. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  7648. document.webkitPointerLockElement === canvas ||
  7649. document.msPointerLockElement === canvas ||
  7650. document.pointerLockElement === canvas);
  7651. };
  7652. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  7653. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  7654. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  7655. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  7656. this._onVRDisplayPointerRestricted = function () {
  7657. canvas.requestPointerLock();
  7658. };
  7659. this._onVRDisplayPointerUnrestricted = function () {
  7660. document.exitPointerLock();
  7661. };
  7662. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  7663. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  7664. }
  7665. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  7666. Engine.audioEngine = new BABYLON.AudioEngine();
  7667. }
  7668. // Prepare buffer pointers
  7669. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  7670. this._currentBufferPointers[i] = new BufferPointer();
  7671. }
  7672. // Load WebVR Devices
  7673. if (options.autoEnableWebVR) {
  7674. this.initWebVR();
  7675. }
  7676. // Detect if we are running on a faulty buggy OS.
  7677. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  7678. // Detect if we are running on a faulty buggy desktop OS.
  7679. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  7680. BABYLON.Tools.Log("Babylon.js engine (v" + Engine.Version + ") launched");
  7681. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  7682. }
  7683. Object.defineProperty(Engine, "LastCreatedEngine", {
  7684. get: function () {
  7685. if (Engine.Instances.length === 0) {
  7686. return null;
  7687. }
  7688. return Engine.Instances[Engine.Instances.length - 1];
  7689. },
  7690. enumerable: true,
  7691. configurable: true
  7692. });
  7693. Object.defineProperty(Engine, "LastCreatedScene", {
  7694. get: function () {
  7695. var lastCreatedEngine = Engine.LastCreatedEngine;
  7696. if (!lastCreatedEngine) {
  7697. return null;
  7698. }
  7699. if (lastCreatedEngine.scenes.length === 0) {
  7700. return null;
  7701. }
  7702. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  7703. },
  7704. enumerable: true,
  7705. configurable: true
  7706. });
  7707. /**
  7708. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  7709. */
  7710. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  7711. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  7712. var engine = Engine.Instances[engineIndex];
  7713. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  7714. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  7715. }
  7716. }
  7717. };
  7718. Object.defineProperty(Engine, "NEVER", {
  7719. get: function () {
  7720. return Engine._NEVER;
  7721. },
  7722. enumerable: true,
  7723. configurable: true
  7724. });
  7725. Object.defineProperty(Engine, "ALWAYS", {
  7726. get: function () {
  7727. return Engine._ALWAYS;
  7728. },
  7729. enumerable: true,
  7730. configurable: true
  7731. });
  7732. Object.defineProperty(Engine, "LESS", {
  7733. get: function () {
  7734. return Engine._LESS;
  7735. },
  7736. enumerable: true,
  7737. configurable: true
  7738. });
  7739. Object.defineProperty(Engine, "EQUAL", {
  7740. get: function () {
  7741. return Engine._EQUAL;
  7742. },
  7743. enumerable: true,
  7744. configurable: true
  7745. });
  7746. Object.defineProperty(Engine, "LEQUAL", {
  7747. get: function () {
  7748. return Engine._LEQUAL;
  7749. },
  7750. enumerable: true,
  7751. configurable: true
  7752. });
  7753. Object.defineProperty(Engine, "GREATER", {
  7754. get: function () {
  7755. return Engine._GREATER;
  7756. },
  7757. enumerable: true,
  7758. configurable: true
  7759. });
  7760. Object.defineProperty(Engine, "GEQUAL", {
  7761. get: function () {
  7762. return Engine._GEQUAL;
  7763. },
  7764. enumerable: true,
  7765. configurable: true
  7766. });
  7767. Object.defineProperty(Engine, "NOTEQUAL", {
  7768. get: function () {
  7769. return Engine._NOTEQUAL;
  7770. },
  7771. enumerable: true,
  7772. configurable: true
  7773. });
  7774. Object.defineProperty(Engine, "KEEP", {
  7775. get: function () {
  7776. return Engine._KEEP;
  7777. },
  7778. enumerable: true,
  7779. configurable: true
  7780. });
  7781. Object.defineProperty(Engine, "REPLACE", {
  7782. get: function () {
  7783. return Engine._REPLACE;
  7784. },
  7785. enumerable: true,
  7786. configurable: true
  7787. });
  7788. Object.defineProperty(Engine, "INCR", {
  7789. get: function () {
  7790. return Engine._INCR;
  7791. },
  7792. enumerable: true,
  7793. configurable: true
  7794. });
  7795. Object.defineProperty(Engine, "DECR", {
  7796. get: function () {
  7797. return Engine._DECR;
  7798. },
  7799. enumerable: true,
  7800. configurable: true
  7801. });
  7802. Object.defineProperty(Engine, "INVERT", {
  7803. get: function () {
  7804. return Engine._INVERT;
  7805. },
  7806. enumerable: true,
  7807. configurable: true
  7808. });
  7809. Object.defineProperty(Engine, "INCR_WRAP", {
  7810. get: function () {
  7811. return Engine._INCR_WRAP;
  7812. },
  7813. enumerable: true,
  7814. configurable: true
  7815. });
  7816. Object.defineProperty(Engine, "DECR_WRAP", {
  7817. get: function () {
  7818. return Engine._DECR_WRAP;
  7819. },
  7820. enumerable: true,
  7821. configurable: true
  7822. });
  7823. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  7824. get: function () {
  7825. return Engine._ALPHA_DISABLE;
  7826. },
  7827. enumerable: true,
  7828. configurable: true
  7829. });
  7830. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  7831. get: function () {
  7832. return Engine._ALPHA_ONEONE;
  7833. },
  7834. enumerable: true,
  7835. configurable: true
  7836. });
  7837. Object.defineProperty(Engine, "ALPHA_ADD", {
  7838. get: function () {
  7839. return Engine._ALPHA_ADD;
  7840. },
  7841. enumerable: true,
  7842. configurable: true
  7843. });
  7844. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  7845. get: function () {
  7846. return Engine._ALPHA_COMBINE;
  7847. },
  7848. enumerable: true,
  7849. configurable: true
  7850. });
  7851. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  7852. get: function () {
  7853. return Engine._ALPHA_SUBTRACT;
  7854. },
  7855. enumerable: true,
  7856. configurable: true
  7857. });
  7858. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  7859. get: function () {
  7860. return Engine._ALPHA_MULTIPLY;
  7861. },
  7862. enumerable: true,
  7863. configurable: true
  7864. });
  7865. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  7866. get: function () {
  7867. return Engine._ALPHA_MAXIMIZED;
  7868. },
  7869. enumerable: true,
  7870. configurable: true
  7871. });
  7872. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  7873. get: function () {
  7874. return Engine._ALPHA_PREMULTIPLIED;
  7875. },
  7876. enumerable: true,
  7877. configurable: true
  7878. });
  7879. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  7880. get: function () {
  7881. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  7882. },
  7883. enumerable: true,
  7884. configurable: true
  7885. });
  7886. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  7887. get: function () {
  7888. return Engine._ALPHA_INTERPOLATE;
  7889. },
  7890. enumerable: true,
  7891. configurable: true
  7892. });
  7893. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  7894. get: function () {
  7895. return Engine._ALPHA_SCREENMODE;
  7896. },
  7897. enumerable: true,
  7898. configurable: true
  7899. });
  7900. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  7901. get: function () {
  7902. return Engine._DELAYLOADSTATE_NONE;
  7903. },
  7904. enumerable: true,
  7905. configurable: true
  7906. });
  7907. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  7908. get: function () {
  7909. return Engine._DELAYLOADSTATE_LOADED;
  7910. },
  7911. enumerable: true,
  7912. configurable: true
  7913. });
  7914. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  7915. get: function () {
  7916. return Engine._DELAYLOADSTATE_LOADING;
  7917. },
  7918. enumerable: true,
  7919. configurable: true
  7920. });
  7921. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  7922. get: function () {
  7923. return Engine._DELAYLOADSTATE_NOTLOADED;
  7924. },
  7925. enumerable: true,
  7926. configurable: true
  7927. });
  7928. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  7929. get: function () {
  7930. return Engine._TEXTUREFORMAT_ALPHA;
  7931. },
  7932. enumerable: true,
  7933. configurable: true
  7934. });
  7935. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  7936. get: function () {
  7937. return Engine._TEXTUREFORMAT_LUMINANCE;
  7938. },
  7939. enumerable: true,
  7940. configurable: true
  7941. });
  7942. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  7943. get: function () {
  7944. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  7945. },
  7946. enumerable: true,
  7947. configurable: true
  7948. });
  7949. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  7950. get: function () {
  7951. return Engine._TEXTUREFORMAT_RGB;
  7952. },
  7953. enumerable: true,
  7954. configurable: true
  7955. });
  7956. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  7957. get: function () {
  7958. return Engine._TEXTUREFORMAT_RGBA;
  7959. },
  7960. enumerable: true,
  7961. configurable: true
  7962. });
  7963. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  7964. get: function () {
  7965. return Engine._TEXTURETYPE_UNSIGNED_INT;
  7966. },
  7967. enumerable: true,
  7968. configurable: true
  7969. });
  7970. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  7971. get: function () {
  7972. return Engine._TEXTURETYPE_FLOAT;
  7973. },
  7974. enumerable: true,
  7975. configurable: true
  7976. });
  7977. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  7978. get: function () {
  7979. return Engine._TEXTURETYPE_HALF_FLOAT;
  7980. },
  7981. enumerable: true,
  7982. configurable: true
  7983. });
  7984. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  7985. get: function () {
  7986. return Engine._SCALEMODE_FLOOR;
  7987. },
  7988. enumerable: true,
  7989. configurable: true
  7990. });
  7991. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  7992. get: function () {
  7993. return Engine._SCALEMODE_NEAREST;
  7994. },
  7995. enumerable: true,
  7996. configurable: true
  7997. });
  7998. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  7999. get: function () {
  8000. return Engine._SCALEMODE_CEILING;
  8001. },
  8002. enumerable: true,
  8003. configurable: true
  8004. });
  8005. Object.defineProperty(Engine, "Version", {
  8006. get: function () {
  8007. return "3.1-alpha";
  8008. },
  8009. enumerable: true,
  8010. configurable: true
  8011. });
  8012. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  8013. get: function () {
  8014. return this._webGLVersion < 2 || this.forcePOTTextures;
  8015. },
  8016. enumerable: true,
  8017. configurable: true
  8018. });
  8019. Object.defineProperty(Engine.prototype, "badOS", {
  8020. get: function () {
  8021. return this._badOS;
  8022. },
  8023. enumerable: true,
  8024. configurable: true
  8025. });
  8026. Object.defineProperty(Engine.prototype, "badDesktopOS", {
  8027. get: function () {
  8028. return this._badDesktopOS;
  8029. },
  8030. enumerable: true,
  8031. configurable: true
  8032. });
  8033. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  8034. get: function () {
  8035. return this._performanceMonitor;
  8036. },
  8037. enumerable: true,
  8038. configurable: true
  8039. });
  8040. Object.defineProperty(Engine.prototype, "texturesSupported", {
  8041. get: function () {
  8042. return this._texturesSupported;
  8043. },
  8044. enumerable: true,
  8045. configurable: true
  8046. });
  8047. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  8048. get: function () {
  8049. return this._textureFormatInUse;
  8050. },
  8051. enumerable: true,
  8052. configurable: true
  8053. });
  8054. Object.defineProperty(Engine.prototype, "emptyTexture", {
  8055. // Empty texture
  8056. get: function () {
  8057. if (!this._emptyTexture) {
  8058. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8059. }
  8060. return this._emptyTexture;
  8061. },
  8062. enumerable: true,
  8063. configurable: true
  8064. });
  8065. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  8066. get: function () {
  8067. if (!this._emptyCubeTexture) {
  8068. var faceData = new Uint8Array(4);
  8069. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  8070. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  8071. }
  8072. return this._emptyCubeTexture;
  8073. },
  8074. enumerable: true,
  8075. configurable: true
  8076. });
  8077. Engine.prototype._rebuildInternalTextures = function () {
  8078. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  8079. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  8080. var internalTexture = currentState_1[_i];
  8081. internalTexture._rebuild();
  8082. }
  8083. };
  8084. Engine.prototype._rebuildEffects = function () {
  8085. for (var key in this._compiledEffects) {
  8086. var effect = this._compiledEffects[key];
  8087. effect._prepareEffect();
  8088. }
  8089. BABYLON.Effect.ResetCache();
  8090. };
  8091. Engine.prototype._rebuildBuffers = function () {
  8092. // Index / Vertex
  8093. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  8094. var scene = _a[_i];
  8095. scene.resetCachedMaterial();
  8096. scene._rebuildGeometries();
  8097. scene._rebuildTextures();
  8098. }
  8099. for (var _b = 0, _c = this.postProcesses; _b < _c.length; _b++) {
  8100. var postprocess = _c[_b];
  8101. postprocess._rebuild();
  8102. }
  8103. // Uniforms
  8104. for (var _d = 0, _e = this._uniformBuffers; _d < _e.length; _d++) {
  8105. var uniformBuffer = _e[_d];
  8106. uniformBuffer._rebuild();
  8107. }
  8108. };
  8109. Engine.prototype._initGLContext = function () {
  8110. // Caps
  8111. this._caps = new EngineCapabilities();
  8112. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  8113. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  8114. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  8115. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  8116. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  8117. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  8118. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  8119. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  8120. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  8121. // Infos
  8122. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  8123. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  8124. if (rendererInfo != null) {
  8125. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  8126. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  8127. }
  8128. if (!this._glVendor) {
  8129. this._glVendor = "Unknown vendor";
  8130. }
  8131. if (!this._glRenderer) {
  8132. this._glRenderer = "Unknown renderer";
  8133. }
  8134. // Constants
  8135. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  8136. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  8137. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  8138. this._gl.DEPTH24_STENCIL8 = 35056;
  8139. // Extensions
  8140. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  8141. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  8142. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  8143. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  8144. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  8145. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  8146. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  8147. 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');
  8148. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  8149. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  8150. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  8151. this._caps.highPrecisionShaderSupported = true;
  8152. this._caps.drawBuffersExtension = this._webGLVersion > 1 || this._gl.getExtension('WEBGL_draw_buffers');
  8153. // Checks if some of the format renders first to allow the use of webgl inspector.
  8154. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  8155. this._caps.textureFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float');
  8156. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear');
  8157. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer();
  8158. this._caps.textureHalfFloat = this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float');
  8159. this._caps.textureHalfFloatLinearFiltering = this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'));
  8160. if (this._webGLVersion > 1) {
  8161. this._gl.HALF_FLOAT_OES = 0x140B;
  8162. }
  8163. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  8164. this._caps.textureLOD = this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod');
  8165. // Vertex array object
  8166. if (this._webGLVersion > 1) {
  8167. this._caps.vertexArrayObject = true;
  8168. }
  8169. else {
  8170. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  8171. if (vertexArrayObjectExtension != null) {
  8172. this._caps.vertexArrayObject = true;
  8173. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  8174. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  8175. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  8176. }
  8177. else {
  8178. this._caps.vertexArrayObject = false;
  8179. }
  8180. }
  8181. // Instances count
  8182. if (this._webGLVersion > 1) {
  8183. this._caps.instancedArrays = true;
  8184. }
  8185. else {
  8186. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  8187. if (instanceExtension != null) {
  8188. this._caps.instancedArrays = true;
  8189. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  8190. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  8191. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  8192. }
  8193. else {
  8194. this._caps.instancedArrays = false;
  8195. }
  8196. }
  8197. // Intelligently add supported compressed formats in order to check for.
  8198. // Check for ASTC support first as it is most powerful and to be very cross platform.
  8199. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  8200. // Likely no hardware which supports both PVR & DXT, so order matters little.
  8201. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  8202. if (this._caps.astc)
  8203. this.texturesSupported.push('-astc.ktx');
  8204. if (this._caps.s3tc)
  8205. this.texturesSupported.push('-dxt.ktx');
  8206. if (this._caps.pvrtc)
  8207. this.texturesSupported.push('-pvrtc.ktx');
  8208. if (this._caps.etc2)
  8209. this.texturesSupported.push('-etc2.ktx');
  8210. if (this._caps.etc1)
  8211. this.texturesSupported.push('-etc1.ktx');
  8212. if (this._gl.getShaderPrecisionFormat) {
  8213. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  8214. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  8215. }
  8216. // Depth buffer
  8217. this.setDepthBuffer(true);
  8218. this.setDepthFunctionToLessOrEqual();
  8219. this.setDepthWrite(true);
  8220. };
  8221. Object.defineProperty(Engine.prototype, "webGLVersion", {
  8222. get: function () {
  8223. return this._webGLVersion;
  8224. },
  8225. enumerable: true,
  8226. configurable: true
  8227. });
  8228. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  8229. /**
  8230. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  8231. */
  8232. get: function () {
  8233. return this._isStencilEnable;
  8234. },
  8235. enumerable: true,
  8236. configurable: true
  8237. });
  8238. Engine.prototype._prepareWorkingCanvas = function () {
  8239. if (this._workingCanvas) {
  8240. return;
  8241. }
  8242. this._workingCanvas = document.createElement("canvas");
  8243. this._workingContext = this._workingCanvas.getContext("2d");
  8244. };
  8245. Engine.prototype.resetTextureCache = function () {
  8246. for (var key in this._activeTexturesCache) {
  8247. this._activeTexturesCache[key] = null;
  8248. }
  8249. };
  8250. Engine.prototype.isDeterministicLockStep = function () {
  8251. return this._deterministicLockstep;
  8252. };
  8253. Engine.prototype.getLockstepMaxSteps = function () {
  8254. return this._lockstepMaxSteps;
  8255. };
  8256. Engine.prototype.getGlInfo = function () {
  8257. return {
  8258. vendor: this._glVendor,
  8259. renderer: this._glRenderer,
  8260. version: this._glVersion
  8261. };
  8262. };
  8263. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  8264. if (useScreen === void 0) { useScreen = false; }
  8265. var viewport = camera.viewport;
  8266. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  8267. };
  8268. Engine.prototype.getRenderWidth = function (useScreen) {
  8269. if (useScreen === void 0) { useScreen = false; }
  8270. if (!useScreen && this._currentRenderTarget) {
  8271. return this._currentRenderTarget.width;
  8272. }
  8273. return this._gl.drawingBufferWidth;
  8274. };
  8275. Engine.prototype.getRenderHeight = function (useScreen) {
  8276. if (useScreen === void 0) { useScreen = false; }
  8277. if (!useScreen && this._currentRenderTarget) {
  8278. return this._currentRenderTarget.height;
  8279. }
  8280. return this._gl.drawingBufferHeight;
  8281. };
  8282. Engine.prototype.getRenderingCanvas = function () {
  8283. return this._renderingCanvas;
  8284. };
  8285. Engine.prototype.getRenderingCanvasClientRect = function () {
  8286. return this._renderingCanvas.getBoundingClientRect();
  8287. };
  8288. Engine.prototype.setHardwareScalingLevel = function (level) {
  8289. this._hardwareScalingLevel = level;
  8290. this.resize();
  8291. };
  8292. Engine.prototype.getHardwareScalingLevel = function () {
  8293. return this._hardwareScalingLevel;
  8294. };
  8295. Engine.prototype.getLoadedTexturesCache = function () {
  8296. return this._internalTexturesCache;
  8297. };
  8298. Engine.prototype.getCaps = function () {
  8299. return this._caps;
  8300. };
  8301. Object.defineProperty(Engine.prototype, "drawCalls", {
  8302. /** The number of draw calls submitted last frame */
  8303. get: function () {
  8304. return this._drawCalls.current;
  8305. },
  8306. enumerable: true,
  8307. configurable: true
  8308. });
  8309. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  8310. get: function () {
  8311. return this._drawCalls;
  8312. },
  8313. enumerable: true,
  8314. configurable: true
  8315. });
  8316. Engine.prototype.getDepthFunction = function () {
  8317. return this._depthCullingState.depthFunc;
  8318. };
  8319. Engine.prototype.setDepthFunction = function (depthFunc) {
  8320. this._depthCullingState.depthFunc = depthFunc;
  8321. };
  8322. Engine.prototype.setDepthFunctionToGreater = function () {
  8323. this._depthCullingState.depthFunc = this._gl.GREATER;
  8324. };
  8325. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  8326. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  8327. };
  8328. Engine.prototype.setDepthFunctionToLess = function () {
  8329. this._depthCullingState.depthFunc = this._gl.LESS;
  8330. };
  8331. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  8332. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  8333. };
  8334. Engine.prototype.getStencilBuffer = function () {
  8335. return this._stencilState.stencilTest;
  8336. };
  8337. Engine.prototype.setStencilBuffer = function (enable) {
  8338. this._stencilState.stencilTest = enable;
  8339. };
  8340. Engine.prototype.getStencilMask = function () {
  8341. return this._stencilState.stencilMask;
  8342. };
  8343. Engine.prototype.setStencilMask = function (mask) {
  8344. this._stencilState.stencilMask = mask;
  8345. };
  8346. Engine.prototype.getStencilFunction = function () {
  8347. return this._stencilState.stencilFunc;
  8348. };
  8349. Engine.prototype.getStencilFunctionReference = function () {
  8350. return this._stencilState.stencilFuncRef;
  8351. };
  8352. Engine.prototype.getStencilFunctionMask = function () {
  8353. return this._stencilState.stencilFuncMask;
  8354. };
  8355. Engine.prototype.setStencilFunction = function (stencilFunc) {
  8356. this._stencilState.stencilFunc = stencilFunc;
  8357. };
  8358. Engine.prototype.setStencilFunctionReference = function (reference) {
  8359. this._stencilState.stencilFuncRef = reference;
  8360. };
  8361. Engine.prototype.setStencilFunctionMask = function (mask) {
  8362. this._stencilState.stencilFuncMask = mask;
  8363. };
  8364. Engine.prototype.getStencilOperationFail = function () {
  8365. return this._stencilState.stencilOpStencilFail;
  8366. };
  8367. Engine.prototype.getStencilOperationDepthFail = function () {
  8368. return this._stencilState.stencilOpDepthFail;
  8369. };
  8370. Engine.prototype.getStencilOperationPass = function () {
  8371. return this._stencilState.stencilOpStencilDepthPass;
  8372. };
  8373. Engine.prototype.setStencilOperationFail = function (operation) {
  8374. this._stencilState.stencilOpStencilFail = operation;
  8375. };
  8376. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  8377. this._stencilState.stencilOpDepthFail = operation;
  8378. };
  8379. Engine.prototype.setStencilOperationPass = function (operation) {
  8380. this._stencilState.stencilOpStencilDepthPass = operation;
  8381. };
  8382. Engine.prototype.setDitheringState = function (value) {
  8383. if (value) {
  8384. this._gl.enable(this._gl.DITHER);
  8385. }
  8386. else {
  8387. this._gl.disable(this._gl.DITHER);
  8388. }
  8389. };
  8390. /**
  8391. * stop executing a render loop function and remove it from the execution array
  8392. * @param {Function} [renderFunction] the function to be removed. If not provided all functions will be removed.
  8393. */
  8394. Engine.prototype.stopRenderLoop = function (renderFunction) {
  8395. if (!renderFunction) {
  8396. this._activeRenderLoops = [];
  8397. return;
  8398. }
  8399. var index = this._activeRenderLoops.indexOf(renderFunction);
  8400. if (index >= 0) {
  8401. this._activeRenderLoops.splice(index, 1);
  8402. }
  8403. };
  8404. Engine.prototype._renderLoop = function () {
  8405. if (this._contextWasLost) {
  8406. return;
  8407. }
  8408. var shouldRender = true;
  8409. if (!this.renderEvenInBackground && this._windowIsBackground) {
  8410. shouldRender = false;
  8411. }
  8412. if (shouldRender) {
  8413. // Start new frame
  8414. this.beginFrame();
  8415. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  8416. var renderFunction = this._activeRenderLoops[index];
  8417. renderFunction();
  8418. }
  8419. // Present
  8420. this.endFrame();
  8421. }
  8422. if (this._activeRenderLoops.length > 0) {
  8423. // Register new frame
  8424. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, this._vrDisplayEnabled);
  8425. }
  8426. else {
  8427. this._renderingQueueLaunched = false;
  8428. }
  8429. };
  8430. /**
  8431. * Register and execute a render loop. The engine can have more than one render function.
  8432. * @param {Function} renderFunction - the function to continuously execute starting the next render loop.
  8433. * @example
  8434. * engine.runRenderLoop(function () {
  8435. * scene.render()
  8436. * })
  8437. */
  8438. Engine.prototype.runRenderLoop = function (renderFunction) {
  8439. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  8440. return;
  8441. }
  8442. this._activeRenderLoops.push(renderFunction);
  8443. if (!this._renderingQueueLaunched) {
  8444. this._renderingQueueLaunched = true;
  8445. this._bindedRenderFunction = this._renderLoop.bind(this);
  8446. BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  8447. }
  8448. };
  8449. /**
  8450. * Toggle full screen mode.
  8451. * @param {boolean} requestPointerLock - should a pointer lock be requested from the user
  8452. * @param {any} options - an options object to be sent to the requestFullscreen function
  8453. */
  8454. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  8455. if (this.isFullscreen) {
  8456. BABYLON.Tools.ExitFullscreen();
  8457. }
  8458. else {
  8459. this._pointerLockRequested = requestPointerLock;
  8460. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  8461. }
  8462. };
  8463. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  8464. if (stencil === void 0) { stencil = false; }
  8465. this.applyStates();
  8466. var mode = 0;
  8467. if (backBuffer && color) {
  8468. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  8469. mode |= this._gl.COLOR_BUFFER_BIT;
  8470. }
  8471. if (depth) {
  8472. this._gl.clearDepth(1.0);
  8473. mode |= this._gl.DEPTH_BUFFER_BIT;
  8474. }
  8475. if (stencil) {
  8476. this._gl.clearStencil(0);
  8477. mode |= this._gl.STENCIL_BUFFER_BIT;
  8478. }
  8479. this._gl.clear(mode);
  8480. };
  8481. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  8482. var gl = this._gl;
  8483. // Save state
  8484. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  8485. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  8486. // Change state
  8487. gl.enable(gl.SCISSOR_TEST);
  8488. gl.scissor(x, y, width, height);
  8489. // Clear
  8490. this.clear(clearColor, true, true, true);
  8491. // Restore state
  8492. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  8493. if (curScissor === true) {
  8494. gl.enable(gl.SCISSOR_TEST);
  8495. }
  8496. else {
  8497. gl.disable(gl.SCISSOR_TEST);
  8498. }
  8499. };
  8500. /**
  8501. * Set the WebGL's viewport
  8502. * @param {BABYLON.Viewport} viewport - the viewport element to be used.
  8503. * @param {number} [requiredWidth] - the width required for rendering. If not provided the rendering canvas' width is used.
  8504. * @param {number} [requiredHeight] - the height required for rendering. If not provided the rendering canvas' height is used.
  8505. */
  8506. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  8507. var width = requiredWidth || this.getRenderWidth();
  8508. var height = requiredHeight || this.getRenderHeight();
  8509. var x = viewport.x || 0;
  8510. var y = viewport.y || 0;
  8511. this._cachedViewport = viewport;
  8512. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  8513. };
  8514. /**
  8515. * Directly set the WebGL Viewport
  8516. * The x, y, width & height are directly passed to the WebGL call
  8517. * @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.
  8518. */
  8519. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  8520. var currentViewport = this._cachedViewport;
  8521. this._cachedViewport = null;
  8522. this._gl.viewport(x, y, width, height);
  8523. return currentViewport;
  8524. };
  8525. Engine.prototype.beginFrame = function () {
  8526. this._measureFps();
  8527. };
  8528. Engine.prototype.endFrame = function () {
  8529. //force a flush in case we are using a bad OS.
  8530. if (this._badOS) {
  8531. this.flushFramebuffer();
  8532. }
  8533. //submit frame to the vr device, if enabled
  8534. if (this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting) {
  8535. this._vrDisplayEnabled.submitFrame();
  8536. }
  8537. };
  8538. /**
  8539. * resize the view according to the canvas' size.
  8540. * @example
  8541. * window.addEventListener("resize", function () {
  8542. * engine.resize();
  8543. * });
  8544. */
  8545. Engine.prototype.resize = function () {
  8546. // We're not resizing the size of the canvas while in VR mode & presenting
  8547. if (!(this._vrDisplayEnabled && this._vrDisplayEnabled.isPresenting)) {
  8548. var width = navigator.isCocoonJS ? window.innerWidth : this._renderingCanvas.clientWidth;
  8549. var height = navigator.isCocoonJS ? window.innerHeight : this._renderingCanvas.clientHeight;
  8550. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  8551. }
  8552. };
  8553. /**
  8554. * force a specific size of the canvas
  8555. * @param {number} width - the new canvas' width
  8556. * @param {number} height - the new canvas' height
  8557. */
  8558. Engine.prototype.setSize = function (width, height) {
  8559. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  8560. return;
  8561. }
  8562. this._renderingCanvas.width = width;
  8563. this._renderingCanvas.height = height;
  8564. for (var index = 0; index < this.scenes.length; index++) {
  8565. var scene = this.scenes[index];
  8566. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  8567. var cam = scene.cameras[camIndex];
  8568. cam._currentRenderId = 0;
  8569. }
  8570. }
  8571. if (this.onResizeObservable.hasObservers) {
  8572. this.onResizeObservable.notifyObservers(this);
  8573. }
  8574. };
  8575. //WebVR functions
  8576. Engine.prototype.isVRDevicePresent = function (callback) {
  8577. this.getVRDevice(null, function (device) {
  8578. callback(device !== null);
  8579. });
  8580. };
  8581. Engine.prototype.getVRDevice = function (name, callback) {
  8582. if (!this.vrDisplaysPromise) {
  8583. callback(null);
  8584. return;
  8585. }
  8586. this.vrDisplaysPromise.then(function (devices) {
  8587. if (devices.length > 0) {
  8588. if (name) {
  8589. var found = devices.some(function (device) {
  8590. if (device.displayName === name) {
  8591. callback(device);
  8592. return true;
  8593. }
  8594. else {
  8595. return false;
  8596. }
  8597. });
  8598. if (!found) {
  8599. BABYLON.Tools.Warn("Display " + name + " was not found. Using " + devices[0].displayName);
  8600. callback(devices[0]);
  8601. }
  8602. }
  8603. else {
  8604. //choose the first one
  8605. callback(devices[0]);
  8606. }
  8607. }
  8608. else {
  8609. BABYLON.Tools.Error("No WebVR devices found!");
  8610. callback(null);
  8611. }
  8612. });
  8613. };
  8614. Engine.prototype.initWebVR = function () {
  8615. if (!this.vrDisplaysPromise) {
  8616. this._getVRDisplays();
  8617. }
  8618. };
  8619. Engine.prototype.enableVR = function (vrDevice) {
  8620. this._vrDisplayEnabled = vrDevice;
  8621. this._vrDisplayEnabled.requestPresent([{ source: this.getRenderingCanvas() }]).then(this._onVRFullScreenTriggered);
  8622. };
  8623. Engine.prototype.disableVR = function () {
  8624. if (this._vrDisplayEnabled) {
  8625. this._vrDisplayEnabled.exitPresent().then(this._onVRFullScreenTriggered);
  8626. }
  8627. };
  8628. Engine.prototype._getVRDisplays = function () {
  8629. var _this = this;
  8630. var getWebVRDevices = function (devices) {
  8631. _this._vrDisplays = devices.filter(function (device) {
  8632. return device instanceof VRDisplay;
  8633. });
  8634. return _this._vrDisplays;
  8635. };
  8636. if (navigator.getVRDisplays) {
  8637. this.vrDisplaysPromise = navigator.getVRDisplays().then(getWebVRDevices);
  8638. }
  8639. };
  8640. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  8641. if (this._currentRenderTarget) {
  8642. this.unBindFramebuffer(this._currentRenderTarget);
  8643. }
  8644. this._currentRenderTarget = texture;
  8645. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  8646. var gl = this._gl;
  8647. if (texture.isCube) {
  8648. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  8649. }
  8650. if (this._cachedViewport && !forceFullscreenViewport) {
  8651. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  8652. }
  8653. else {
  8654. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  8655. }
  8656. this.wipeCaches();
  8657. };
  8658. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  8659. if (this._currentFramebuffer !== framebuffer) {
  8660. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  8661. this._currentFramebuffer = framebuffer;
  8662. }
  8663. };
  8664. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  8665. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  8666. this._currentRenderTarget = null;
  8667. // If MSAA, we need to bitblt back to main texture
  8668. var gl = this._gl;
  8669. if (texture._MSAAFramebuffer) {
  8670. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  8671. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  8672. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  8673. }
  8674. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  8675. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  8676. gl.generateMipmap(gl.TEXTURE_2D);
  8677. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  8678. }
  8679. if (onBeforeUnbind) {
  8680. if (texture._MSAAFramebuffer) {
  8681. // Bind the correct framebuffer
  8682. this.bindUnboundFramebuffer(texture._framebuffer);
  8683. }
  8684. onBeforeUnbind();
  8685. }
  8686. this.bindUnboundFramebuffer(null);
  8687. };
  8688. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  8689. if (texture.generateMipMaps) {
  8690. var gl = this._gl;
  8691. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  8692. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  8693. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  8694. }
  8695. };
  8696. Engine.prototype.flushFramebuffer = function () {
  8697. this._gl.flush();
  8698. };
  8699. Engine.prototype.restoreDefaultFramebuffer = function () {
  8700. if (this._currentRenderTarget) {
  8701. this.unBindFramebuffer(this._currentRenderTarget);
  8702. }
  8703. else {
  8704. this.bindUnboundFramebuffer(null);
  8705. }
  8706. if (this._cachedViewport) {
  8707. this.setViewport(this._cachedViewport);
  8708. }
  8709. this.wipeCaches();
  8710. };
  8711. // UBOs
  8712. Engine.prototype.createUniformBuffer = function (elements) {
  8713. var ubo = this._gl.createBuffer();
  8714. this.bindUniformBuffer(ubo);
  8715. if (elements instanceof Float32Array) {
  8716. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  8717. }
  8718. else {
  8719. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  8720. }
  8721. this.bindUniformBuffer(null);
  8722. ubo.references = 1;
  8723. return ubo;
  8724. };
  8725. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  8726. var ubo = this._gl.createBuffer();
  8727. this.bindUniformBuffer(ubo);
  8728. if (elements instanceof Float32Array) {
  8729. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  8730. }
  8731. else {
  8732. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  8733. }
  8734. this.bindUniformBuffer(null);
  8735. ubo.references = 1;
  8736. return ubo;
  8737. };
  8738. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  8739. this.bindUniformBuffer(uniformBuffer);
  8740. if (offset === undefined) {
  8741. offset = 0;
  8742. }
  8743. if (count === undefined) {
  8744. if (elements instanceof Float32Array) {
  8745. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  8746. }
  8747. else {
  8748. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  8749. }
  8750. }
  8751. else {
  8752. if (elements instanceof Float32Array) {
  8753. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  8754. }
  8755. else {
  8756. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  8757. }
  8758. }
  8759. this.bindUniformBuffer(null);
  8760. };
  8761. // VBOs
  8762. Engine.prototype._resetVertexBufferBinding = function () {
  8763. this.bindArrayBuffer(null);
  8764. this._cachedVertexBuffers = null;
  8765. };
  8766. Engine.prototype.createVertexBuffer = function (vertices) {
  8767. var vbo = this._gl.createBuffer();
  8768. this.bindArrayBuffer(vbo);
  8769. if (vertices instanceof Float32Array) {
  8770. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.STATIC_DRAW);
  8771. }
  8772. else {
  8773. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.STATIC_DRAW);
  8774. }
  8775. this._resetVertexBufferBinding();
  8776. vbo.references = 1;
  8777. return vbo;
  8778. };
  8779. Engine.prototype.createDynamicVertexBuffer = function (vertices) {
  8780. var vbo = this._gl.createBuffer();
  8781. this.bindArrayBuffer(vbo);
  8782. if (vertices instanceof Float32Array) {
  8783. this._gl.bufferData(this._gl.ARRAY_BUFFER, vertices, this._gl.DYNAMIC_DRAW);
  8784. }
  8785. else {
  8786. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(vertices), this._gl.DYNAMIC_DRAW);
  8787. }
  8788. this._resetVertexBufferBinding();
  8789. vbo.references = 1;
  8790. return vbo;
  8791. };
  8792. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, offset, count) {
  8793. this.bindArrayBuffer(vertexBuffer);
  8794. if (offset === undefined) {
  8795. offset = 0;
  8796. }
  8797. if (count === undefined) {
  8798. if (vertices instanceof Float32Array) {
  8799. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, vertices);
  8800. }
  8801. else {
  8802. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, offset, new Float32Array(vertices));
  8803. }
  8804. }
  8805. else {
  8806. if (vertices instanceof Float32Array) {
  8807. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, vertices.subarray(offset, offset + count));
  8808. }
  8809. else {
  8810. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(vertices).subarray(offset, offset + count));
  8811. }
  8812. }
  8813. this._resetVertexBufferBinding();
  8814. };
  8815. Engine.prototype._resetIndexBufferBinding = function () {
  8816. this.bindIndexBuffer(null);
  8817. this._cachedIndexBuffer = null;
  8818. };
  8819. Engine.prototype.createIndexBuffer = function (indices) {
  8820. var vbo = this._gl.createBuffer();
  8821. this.bindIndexBuffer(vbo);
  8822. // Check for 32 bits indices
  8823. var arrayBuffer;
  8824. var need32Bits = false;
  8825. if (indices instanceof Uint16Array) {
  8826. arrayBuffer = indices;
  8827. }
  8828. else {
  8829. //check 32 bit support
  8830. if (this._caps.uintIndices) {
  8831. if (indices instanceof Uint32Array) {
  8832. arrayBuffer = indices;
  8833. need32Bits = true;
  8834. }
  8835. else {
  8836. //number[] or Int32Array, check if 32 bit is necessary
  8837. for (var index = 0; index < indices.length; index++) {
  8838. if (indices[index] > 65535) {
  8839. need32Bits = true;
  8840. break;
  8841. }
  8842. }
  8843. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  8844. }
  8845. }
  8846. else {
  8847. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  8848. arrayBuffer = new Uint16Array(indices);
  8849. }
  8850. }
  8851. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.STATIC_DRAW);
  8852. this._resetIndexBufferBinding();
  8853. vbo.references = 1;
  8854. vbo.is32Bits = need32Bits;
  8855. return vbo;
  8856. };
  8857. Engine.prototype.bindArrayBuffer = function (buffer) {
  8858. if (!this._vaoRecordInProgress) {
  8859. this._unbindVertexArrayObject();
  8860. }
  8861. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  8862. };
  8863. Engine.prototype.bindUniformBuffer = function (buffer) {
  8864. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  8865. };
  8866. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  8867. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  8868. };
  8869. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  8870. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  8871. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  8872. };
  8873. ;
  8874. Engine.prototype.bindIndexBuffer = function (buffer) {
  8875. if (!this._vaoRecordInProgress) {
  8876. this._unbindVertexArrayObject();
  8877. }
  8878. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  8879. };
  8880. Engine.prototype.bindBuffer = function (buffer, target) {
  8881. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  8882. this._gl.bindBuffer(target, buffer);
  8883. this._currentBoundBuffer[target] = buffer;
  8884. }
  8885. };
  8886. Engine.prototype.updateArrayBuffer = function (data) {
  8887. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  8888. };
  8889. Engine.prototype.vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  8890. var pointer = this._currentBufferPointers[indx];
  8891. var changed = false;
  8892. if (!pointer.active) {
  8893. changed = true;
  8894. pointer.active = true;
  8895. pointer.index = indx;
  8896. pointer.size = size;
  8897. pointer.type = type;
  8898. pointer.normalized = normalized;
  8899. pointer.stride = stride;
  8900. pointer.offset = offset;
  8901. pointer.buffer = buffer;
  8902. }
  8903. else {
  8904. if (pointer.buffer !== buffer) {
  8905. pointer.buffer = buffer;
  8906. changed = true;
  8907. }
  8908. if (pointer.size !== size) {
  8909. pointer.size = size;
  8910. changed = true;
  8911. }
  8912. if (pointer.type !== type) {
  8913. pointer.type = type;
  8914. changed = true;
  8915. }
  8916. if (pointer.normalized !== normalized) {
  8917. pointer.normalized = normalized;
  8918. changed = true;
  8919. }
  8920. if (pointer.stride !== stride) {
  8921. pointer.stride = stride;
  8922. changed = true;
  8923. }
  8924. if (pointer.offset !== offset) {
  8925. pointer.offset = offset;
  8926. changed = true;
  8927. }
  8928. }
  8929. if (changed || this._vaoRecordInProgress) {
  8930. this.bindArrayBuffer(buffer);
  8931. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  8932. }
  8933. };
  8934. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  8935. if (indexBuffer == null) {
  8936. return;
  8937. }
  8938. if (this._cachedIndexBuffer !== indexBuffer) {
  8939. this._cachedIndexBuffer = indexBuffer;
  8940. this.bindIndexBuffer(indexBuffer);
  8941. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  8942. }
  8943. };
  8944. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  8945. var attributes = effect.getAttributesNames();
  8946. if (!this._vaoRecordInProgress) {
  8947. this._unbindVertexArrayObject();
  8948. }
  8949. this.unbindAllAttributes();
  8950. for (var index = 0; index < attributes.length; index++) {
  8951. var order = effect.getAttributeLocation(index);
  8952. if (order >= 0) {
  8953. var vertexBuffer = vertexBuffers[attributes[index]];
  8954. if (!vertexBuffer) {
  8955. continue;
  8956. }
  8957. this._gl.enableVertexAttribArray(order);
  8958. if (!this._vaoRecordInProgress) {
  8959. this._vertexAttribArraysEnabled[order] = true;
  8960. }
  8961. var buffer = vertexBuffer.getBuffer();
  8962. this.vertexAttribPointer(buffer, order, vertexBuffer.getSize(), this._gl.FLOAT, false, vertexBuffer.getStrideSize() * 4, vertexBuffer.getOffset() * 4);
  8963. if (vertexBuffer.getIsInstanced()) {
  8964. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  8965. if (!this._vaoRecordInProgress) {
  8966. this._currentInstanceLocations.push(order);
  8967. this._currentInstanceBuffers.push(buffer);
  8968. }
  8969. }
  8970. }
  8971. }
  8972. };
  8973. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  8974. var vao = this._gl.createVertexArray();
  8975. this._vaoRecordInProgress = true;
  8976. this._gl.bindVertexArray(vao);
  8977. this._mustWipeVertexAttributes = true;
  8978. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  8979. this.bindIndexBuffer(indexBuffer);
  8980. this._vaoRecordInProgress = false;
  8981. this._gl.bindVertexArray(null);
  8982. return vao;
  8983. };
  8984. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  8985. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  8986. this._cachedVertexArrayObject = vertexArrayObject;
  8987. this._gl.bindVertexArray(vertexArrayObject);
  8988. this._cachedVertexBuffers = null;
  8989. this._cachedIndexBuffer = null;
  8990. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  8991. this._mustWipeVertexAttributes = true;
  8992. }
  8993. };
  8994. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  8995. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  8996. this._cachedVertexBuffers = vertexBuffer;
  8997. this._cachedEffectForVertexBuffers = effect;
  8998. var attributesCount = effect.getAttributesCount();
  8999. this._unbindVertexArrayObject();
  9000. this.unbindAllAttributes();
  9001. var offset = 0;
  9002. for (var index = 0; index < attributesCount; index++) {
  9003. if (index < vertexDeclaration.length) {
  9004. var order = effect.getAttributeLocation(index);
  9005. if (order >= 0) {
  9006. this._gl.enableVertexAttribArray(order);
  9007. this._vertexAttribArraysEnabled[order] = true;
  9008. this.vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  9009. }
  9010. offset += vertexDeclaration[index] * 4;
  9011. }
  9012. }
  9013. }
  9014. this._bindIndexBufferWithCache(indexBuffer);
  9015. };
  9016. Engine.prototype._unbindVertexArrayObject = function () {
  9017. if (!this._cachedVertexArrayObject) {
  9018. return;
  9019. }
  9020. this._cachedVertexArrayObject = null;
  9021. this._gl.bindVertexArray(null);
  9022. };
  9023. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  9024. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  9025. this._cachedVertexBuffers = vertexBuffers;
  9026. this._cachedEffectForVertexBuffers = effect;
  9027. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  9028. }
  9029. this._bindIndexBufferWithCache(indexBuffer);
  9030. };
  9031. Engine.prototype.unbindInstanceAttributes = function () {
  9032. var boundBuffer;
  9033. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  9034. var instancesBuffer = this._currentInstanceBuffers[i];
  9035. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  9036. boundBuffer = instancesBuffer;
  9037. this.bindArrayBuffer(instancesBuffer);
  9038. }
  9039. var offsetLocation = this._currentInstanceLocations[i];
  9040. this._gl.vertexAttribDivisor(offsetLocation, 0);
  9041. }
  9042. this._currentInstanceBuffers.length = 0;
  9043. this._currentInstanceLocations.length = 0;
  9044. };
  9045. Engine.prototype.releaseVertexArrayObject = function (vao) {
  9046. this._gl.deleteVertexArray(vao);
  9047. };
  9048. Engine.prototype._releaseBuffer = function (buffer) {
  9049. buffer.references--;
  9050. if (buffer.references === 0) {
  9051. this._gl.deleteBuffer(buffer);
  9052. return true;
  9053. }
  9054. return false;
  9055. };
  9056. Engine.prototype.createInstancesBuffer = function (capacity) {
  9057. var buffer = this._gl.createBuffer();
  9058. buffer.capacity = capacity;
  9059. this.bindArrayBuffer(buffer);
  9060. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  9061. return buffer;
  9062. };
  9063. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  9064. this._gl.deleteBuffer(buffer);
  9065. };
  9066. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  9067. this.bindArrayBuffer(instancesBuffer);
  9068. if (data) {
  9069. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  9070. }
  9071. if (offsetLocations[0].index !== undefined) {
  9072. var stride = 0;
  9073. for (var i = 0; i < offsetLocations.length; i++) {
  9074. var ai = offsetLocations[i];
  9075. stride += ai.attributeSize * 4;
  9076. }
  9077. for (var i = 0; i < offsetLocations.length; i++) {
  9078. var ai = offsetLocations[i];
  9079. if (!this._vertexAttribArraysEnabled[ai.index]) {
  9080. this._gl.enableVertexAttribArray(ai.index);
  9081. this._vertexAttribArraysEnabled[ai.index] = true;
  9082. }
  9083. this.vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  9084. this._gl.vertexAttribDivisor(ai.index, 1);
  9085. this._currentInstanceLocations.push(ai.index);
  9086. this._currentInstanceBuffers.push(instancesBuffer);
  9087. }
  9088. }
  9089. else {
  9090. for (var index = 0; index < 4; index++) {
  9091. var offsetLocation = offsetLocations[index];
  9092. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  9093. this._gl.enableVertexAttribArray(offsetLocation);
  9094. this._vertexAttribArraysEnabled[offsetLocation] = true;
  9095. }
  9096. this.vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  9097. this._gl.vertexAttribDivisor(offsetLocation, 1);
  9098. this._currentInstanceLocations.push(offsetLocation);
  9099. this._currentInstanceBuffers.push(instancesBuffer);
  9100. }
  9101. }
  9102. };
  9103. Engine.prototype.applyStates = function () {
  9104. this._depthCullingState.apply(this._gl);
  9105. this._stencilState.apply(this._gl);
  9106. this._alphaState.apply(this._gl);
  9107. };
  9108. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  9109. // Apply states
  9110. this.applyStates();
  9111. this._drawCalls.addCount(1, false);
  9112. // Render
  9113. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  9114. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  9115. if (instancesCount) {
  9116. this._gl.drawElementsInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult, instancesCount);
  9117. return;
  9118. }
  9119. this._gl.drawElements(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, indexCount, indexFormat, indexStart * mult);
  9120. };
  9121. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  9122. // Apply states
  9123. this.applyStates();
  9124. this._drawCalls.addCount(1, false);
  9125. if (instancesCount) {
  9126. this._gl.drawArraysInstanced(this._gl.POINTS, verticesStart, verticesCount, instancesCount);
  9127. return;
  9128. }
  9129. this._gl.drawArrays(this._gl.POINTS, verticesStart, verticesCount);
  9130. };
  9131. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  9132. // Apply states
  9133. this.applyStates();
  9134. this._drawCalls.addCount(1, false);
  9135. if (instancesCount) {
  9136. this._gl.drawArraysInstanced(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount, instancesCount);
  9137. return;
  9138. }
  9139. this._gl.drawArrays(useTriangles ? this._gl.TRIANGLES : this._gl.LINES, verticesStart, verticesCount);
  9140. };
  9141. // Shaders
  9142. Engine.prototype._releaseEffect = function (effect) {
  9143. if (this._compiledEffects[effect._key]) {
  9144. delete this._compiledEffects[effect._key];
  9145. if (effect.getProgram()) {
  9146. this._gl.deleteProgram(effect.getProgram());
  9147. }
  9148. }
  9149. };
  9150. /**
  9151. * @param baseName The base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  9152. * @param samplers An array of string used to represent textures
  9153. */
  9154. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  9155. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  9156. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  9157. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  9158. if (this._compiledEffects[name]) {
  9159. var compiledEffect = this._compiledEffects[name];
  9160. if (onCompiled && compiledEffect.isReady()) {
  9161. onCompiled(compiledEffect);
  9162. }
  9163. return compiledEffect;
  9164. }
  9165. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  9166. effect._key = name;
  9167. this._compiledEffects[name] = effect;
  9168. return effect;
  9169. };
  9170. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  9171. if (uniformsNames === void 0) { uniformsNames = []; }
  9172. if (samplers === void 0) { samplers = []; }
  9173. if (defines === void 0) { defines = ""; }
  9174. return this.createEffect({
  9175. vertex: "particles",
  9176. fragmentElement: fragmentName
  9177. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  9178. };
  9179. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  9180. context = context || this._gl;
  9181. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n" : "";
  9182. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  9183. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  9184. var shaderProgram = context.createProgram();
  9185. context.attachShader(shaderProgram, vertexShader);
  9186. context.attachShader(shaderProgram, fragmentShader);
  9187. context.linkProgram(shaderProgram);
  9188. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  9189. if (!linked) {
  9190. context.validateProgram(shaderProgram);
  9191. var error = context.getProgramInfoLog(shaderProgram);
  9192. if (error) {
  9193. throw new Error(error);
  9194. }
  9195. }
  9196. context.deleteShader(vertexShader);
  9197. context.deleteShader(fragmentShader);
  9198. return shaderProgram;
  9199. };
  9200. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  9201. var results = [];
  9202. for (var index = 0; index < uniformsNames.length; index++) {
  9203. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  9204. }
  9205. return results;
  9206. };
  9207. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  9208. var results = [];
  9209. for (var index = 0; index < attributesNames.length; index++) {
  9210. try {
  9211. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  9212. }
  9213. catch (e) {
  9214. results.push(-1);
  9215. }
  9216. }
  9217. return results;
  9218. };
  9219. Engine.prototype.enableEffect = function (effect) {
  9220. // Use program
  9221. this.setProgram(effect.getProgram());
  9222. this._currentEffect = effect;
  9223. if (effect.onBind) {
  9224. effect.onBind(effect);
  9225. }
  9226. effect.onBindObservable.notifyObservers(effect);
  9227. };
  9228. Engine.prototype.setIntArray = function (uniform, array) {
  9229. if (!uniform)
  9230. return;
  9231. this._gl.uniform1iv(uniform, array);
  9232. };
  9233. Engine.prototype.setIntArray2 = function (uniform, array) {
  9234. if (!uniform || array.length % 2 !== 0)
  9235. return;
  9236. this._gl.uniform2iv(uniform, array);
  9237. };
  9238. Engine.prototype.setIntArray3 = function (uniform, array) {
  9239. if (!uniform || array.length % 3 !== 0)
  9240. return;
  9241. this._gl.uniform3iv(uniform, array);
  9242. };
  9243. Engine.prototype.setIntArray4 = function (uniform, array) {
  9244. if (!uniform || array.length % 4 !== 0)
  9245. return;
  9246. this._gl.uniform4iv(uniform, array);
  9247. };
  9248. Engine.prototype.setFloatArray = function (uniform, array) {
  9249. if (!uniform)
  9250. return;
  9251. this._gl.uniform1fv(uniform, array);
  9252. };
  9253. Engine.prototype.setFloatArray2 = function (uniform, array) {
  9254. if (!uniform || array.length % 2 !== 0)
  9255. return;
  9256. this._gl.uniform2fv(uniform, array);
  9257. };
  9258. Engine.prototype.setFloatArray3 = function (uniform, array) {
  9259. if (!uniform || array.length % 3 !== 0)
  9260. return;
  9261. this._gl.uniform3fv(uniform, array);
  9262. };
  9263. Engine.prototype.setFloatArray4 = function (uniform, array) {
  9264. if (!uniform || array.length % 4 !== 0)
  9265. return;
  9266. this._gl.uniform4fv(uniform, array);
  9267. };
  9268. Engine.prototype.setArray = function (uniform, array) {
  9269. if (!uniform)
  9270. return;
  9271. this._gl.uniform1fv(uniform, array);
  9272. };
  9273. Engine.prototype.setArray2 = function (uniform, array) {
  9274. if (!uniform || array.length % 2 !== 0)
  9275. return;
  9276. this._gl.uniform2fv(uniform, array);
  9277. };
  9278. Engine.prototype.setArray3 = function (uniform, array) {
  9279. if (!uniform || array.length % 3 !== 0)
  9280. return;
  9281. this._gl.uniform3fv(uniform, array);
  9282. };
  9283. Engine.prototype.setArray4 = function (uniform, array) {
  9284. if (!uniform || array.length % 4 !== 0)
  9285. return;
  9286. this._gl.uniform4fv(uniform, array);
  9287. };
  9288. Engine.prototype.setMatrices = function (uniform, matrices) {
  9289. if (!uniform)
  9290. return;
  9291. this._gl.uniformMatrix4fv(uniform, false, matrices);
  9292. };
  9293. Engine.prototype.setMatrix = function (uniform, matrix) {
  9294. if (!uniform)
  9295. return;
  9296. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  9297. };
  9298. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  9299. if (!uniform)
  9300. return;
  9301. this._gl.uniformMatrix3fv(uniform, false, matrix);
  9302. };
  9303. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  9304. if (!uniform)
  9305. return;
  9306. this._gl.uniformMatrix2fv(uniform, false, matrix);
  9307. };
  9308. Engine.prototype.setFloat = function (uniform, value) {
  9309. if (!uniform)
  9310. return;
  9311. this._gl.uniform1f(uniform, value);
  9312. };
  9313. Engine.prototype.setFloat2 = function (uniform, x, y) {
  9314. if (!uniform)
  9315. return;
  9316. this._gl.uniform2f(uniform, x, y);
  9317. };
  9318. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  9319. if (!uniform)
  9320. return;
  9321. this._gl.uniform3f(uniform, x, y, z);
  9322. };
  9323. Engine.prototype.setBool = function (uniform, bool) {
  9324. if (!uniform)
  9325. return;
  9326. this._gl.uniform1i(uniform, bool);
  9327. };
  9328. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  9329. if (!uniform)
  9330. return;
  9331. this._gl.uniform4f(uniform, x, y, z, w);
  9332. };
  9333. Engine.prototype.setColor3 = function (uniform, color3) {
  9334. if (!uniform)
  9335. return;
  9336. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  9337. };
  9338. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  9339. if (!uniform)
  9340. return;
  9341. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  9342. };
  9343. // States
  9344. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  9345. if (zOffset === void 0) { zOffset = 0; }
  9346. if (reverseSide === void 0) { reverseSide = false; }
  9347. // Culling
  9348. var showSide = reverseSide ? this._gl.FRONT : this._gl.BACK;
  9349. var hideSide = reverseSide ? this._gl.BACK : this._gl.FRONT;
  9350. var cullFace = this.cullBackFaces ? showSide : hideSide;
  9351. if (this._depthCullingState.cull !== culling || force || this._depthCullingState.cullFace !== cullFace) {
  9352. if (culling) {
  9353. this._depthCullingState.cullFace = cullFace;
  9354. this._depthCullingState.cull = true;
  9355. }
  9356. else {
  9357. this._depthCullingState.cull = false;
  9358. }
  9359. }
  9360. // Z offset
  9361. this.setZOffset(zOffset);
  9362. };
  9363. Engine.prototype.setZOffset = function (value) {
  9364. this._depthCullingState.zOffset = value;
  9365. };
  9366. Engine.prototype.getZOffset = function () {
  9367. return this._depthCullingState.zOffset;
  9368. };
  9369. Engine.prototype.setDepthBuffer = function (enable) {
  9370. this._depthCullingState.depthTest = enable;
  9371. };
  9372. Engine.prototype.getDepthWrite = function () {
  9373. return this._depthCullingState.depthMask;
  9374. };
  9375. Engine.prototype.setDepthWrite = function (enable) {
  9376. this._depthCullingState.depthMask = enable;
  9377. };
  9378. Engine.prototype.setColorWrite = function (enable) {
  9379. this._gl.colorMask(enable, enable, enable, enable);
  9380. };
  9381. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  9382. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  9383. };
  9384. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  9385. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  9386. if (this._alphaMode === mode) {
  9387. return;
  9388. }
  9389. switch (mode) {
  9390. case Engine.ALPHA_DISABLE:
  9391. this._alphaState.alphaBlend = false;
  9392. break;
  9393. case Engine.ALPHA_PREMULTIPLIED:
  9394. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9395. this._alphaState.alphaBlend = true;
  9396. break;
  9397. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  9398. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9399. this._alphaState.alphaBlend = true;
  9400. break;
  9401. case Engine.ALPHA_COMBINE:
  9402. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  9403. this._alphaState.alphaBlend = true;
  9404. break;
  9405. case Engine.ALPHA_ONEONE:
  9406. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9407. this._alphaState.alphaBlend = true;
  9408. break;
  9409. case Engine.ALPHA_ADD:
  9410. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  9411. this._alphaState.alphaBlend = true;
  9412. break;
  9413. case Engine.ALPHA_SUBTRACT:
  9414. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9415. this._alphaState.alphaBlend = true;
  9416. break;
  9417. case Engine.ALPHA_MULTIPLY:
  9418. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  9419. this._alphaState.alphaBlend = true;
  9420. break;
  9421. case Engine.ALPHA_MAXIMIZED:
  9422. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  9423. this._alphaState.alphaBlend = true;
  9424. break;
  9425. case Engine.ALPHA_INTERPOLATE:
  9426. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  9427. this._alphaState.alphaBlend = true;
  9428. break;
  9429. case Engine.ALPHA_SCREENMODE:
  9430. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  9431. this._alphaState.alphaBlend = true;
  9432. break;
  9433. }
  9434. if (!noDepthWriteChange) {
  9435. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  9436. }
  9437. this._alphaMode = mode;
  9438. };
  9439. Engine.prototype.getAlphaMode = function () {
  9440. return this._alphaMode;
  9441. };
  9442. Engine.prototype.setAlphaTesting = function (enable) {
  9443. this._alphaTest = enable;
  9444. };
  9445. Engine.prototype.getAlphaTesting = function () {
  9446. return !!this._alphaTest;
  9447. };
  9448. // Textures
  9449. Engine.prototype.wipeCaches = function (bruteForce) {
  9450. if (this.preventCacheWipeBetweenFrames) {
  9451. return;
  9452. }
  9453. this.resetTextureCache();
  9454. this._currentEffect = null;
  9455. // 6/8/2017: deltakosh: Should not be required anymore.
  9456. // This message is then mostly for the future myself which will scream out loud when seeing that actually it was required :)
  9457. if (bruteForce) {
  9458. this._currentProgram = null;
  9459. this._stencilState.reset();
  9460. this._depthCullingState.reset();
  9461. this.setDepthFunctionToLessOrEqual();
  9462. this._alphaState.reset();
  9463. }
  9464. this._cachedVertexBuffers = null;
  9465. this._cachedIndexBuffer = null;
  9466. this._cachedEffectForVertexBuffers = null;
  9467. this._unbindVertexArrayObject();
  9468. this.bindIndexBuffer(null);
  9469. this.bindArrayBuffer(null);
  9470. };
  9471. /**
  9472. * Set the compressed texture format to use, based on the formats you have, and the formats
  9473. * supported by the hardware / browser.
  9474. *
  9475. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  9476. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  9477. * to API arguments needed to compressed textures. This puts the burden on the container
  9478. * generator to house the arcane code for determining these for current & future formats.
  9479. *
  9480. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  9481. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  9482. *
  9483. * Note: The result of this call is not taken into account when a texture is base64.
  9484. *
  9485. * @param {Array<string>} formatsAvailable- The list of those format families you have created
  9486. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  9487. *
  9488. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  9489. * @returns The extension selected.
  9490. */
  9491. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  9492. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  9493. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  9494. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  9495. return this._textureFormatInUse = this._texturesSupported[i];
  9496. }
  9497. }
  9498. }
  9499. // actively set format to nothing, to allow this to be called more than once
  9500. // and possibly fail the 2nd time
  9501. return this._textureFormatInUse = null;
  9502. };
  9503. Engine.prototype._createTexture = function () {
  9504. return this._gl.createTexture();
  9505. };
  9506. /**
  9507. * Usually called from BABYLON.Texture.ts. Passed information to create a WebGLTexture.
  9508. * @param {string} urlArg- This contains one of the following:
  9509. * 1. A conventional http URL, e.g. 'http://...' or 'file://...'
  9510. * 2. A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  9511. * 3. An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  9512. *
  9513. * @param {boolean} noMipmap- When true, no mipmaps shall be generated. Ignored for compressed textures. They must be in the file.
  9514. * @param {boolean} invertY- When true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file.
  9515. * @param {Scene} scene- Needed for loading to the correct scene.
  9516. * @param {number} samplingMode- Mode with should be used sample / access the texture. Default: TRILINEAR
  9517. * @param {callback} onLoad- Optional callback to be called upon successful completion.
  9518. * @param {callback} onError- Optional callback to be called upon failure.
  9519. * @param {ArrayBuffer | HTMLImageElement} buffer- A source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  9520. * @param {WebGLTexture} fallback- An internal argument in case the function must be called again, due to etc1 not having alpha capabilities.
  9521. * @param {number} format- Internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures.
  9522. *
  9523. * @returns {WebGLTexture} for assignment back into BABYLON.Texture
  9524. */
  9525. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  9526. var _this = this;
  9527. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  9528. if (onLoad === void 0) { onLoad = null; }
  9529. if (onError === void 0) { onError = null; }
  9530. if (buffer === void 0) { buffer = null; }
  9531. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  9532. var fromData = url.substr(0, 5) === "data:";
  9533. var fromBlob = url.substr(0, 5) === "blob:";
  9534. var isBase64 = fromData && url.indexOf("base64") !== -1;
  9535. var texture = fallBack ? fallBack : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  9536. // establish the file extension, if possible
  9537. var lastDot = url.lastIndexOf('.');
  9538. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  9539. var isDDS = this.getCaps().s3tc && (extension === ".dds");
  9540. var isTGA = (extension === ".tga");
  9541. // determine if a ktx file should be substituted
  9542. var isKTX = false;
  9543. if (this._textureFormatInUse && !isBase64 && !fallBack) {
  9544. url = url.substring(0, lastDot) + this._textureFormatInUse;
  9545. isKTX = true;
  9546. }
  9547. if (scene) {
  9548. scene._addPendingData(texture);
  9549. }
  9550. texture.url = url;
  9551. texture.generateMipMaps = !noMipmap;
  9552. texture.samplingMode = samplingMode;
  9553. texture.invertY = invertY;
  9554. if (!this._doNotHandleContextLost) {
  9555. // Keep a link to the buffer only if we plan to handle context lost
  9556. texture._buffer = buffer;
  9557. }
  9558. if (onLoad) {
  9559. texture.onLoadedObservable.add(onLoad);
  9560. }
  9561. if (!fallBack)
  9562. this._internalTexturesCache.push(texture);
  9563. var onerror = function () {
  9564. if (scene) {
  9565. scene._removePendingData(texture);
  9566. }
  9567. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  9568. if (isKTX) {
  9569. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  9570. }
  9571. else if (onError) {
  9572. onError();
  9573. }
  9574. };
  9575. var callback;
  9576. // processing for non-image formats
  9577. if (isKTX || isTGA || isDDS) {
  9578. if (isKTX) {
  9579. callback = function (data) {
  9580. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 1);
  9581. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  9582. ktx.uploadLevels(_this._gl, !noMipmap);
  9583. return false;
  9584. }, samplingMode);
  9585. };
  9586. }
  9587. else if (isTGA) {
  9588. callback = function (arrayBuffer) {
  9589. var data = new Uint8Array(arrayBuffer);
  9590. var header = BABYLON.Internals.TGATools.GetTGAHeader(data);
  9591. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  9592. BABYLON.Internals.TGATools.UploadContent(_this._gl, data);
  9593. return false;
  9594. }, samplingMode);
  9595. };
  9596. }
  9597. else if (isDDS) {
  9598. callback = function (data) {
  9599. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  9600. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  9601. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  9602. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  9603. return false;
  9604. }, samplingMode);
  9605. };
  9606. }
  9607. if (!buffer) {
  9608. BABYLON.Tools.LoadFile(url, function (data) {
  9609. callback(data);
  9610. }, null, scene ? scene.database : null, true, onerror);
  9611. }
  9612. else {
  9613. callback(buffer);
  9614. }
  9615. // image format processing
  9616. }
  9617. else {
  9618. var onload = function (img) {
  9619. if (fromBlob && !_this._doNotHandleContextLost) {
  9620. // We need to store the image if we need to rebuild the texture
  9621. // in case of a webgl context lost
  9622. texture._buffer = img;
  9623. }
  9624. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  9625. var gl = _this._gl;
  9626. var isPot = (img.width === potWidth && img.height === potHeight);
  9627. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  9628. if (isPot) {
  9629. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9630. return false;
  9631. }
  9632. // Using shaders to rescale because canvas.drawImage is lossy
  9633. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  9634. _this._bindTextureDirectly(gl.TEXTURE_2D, source);
  9635. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  9636. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  9637. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  9638. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9639. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9640. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  9641. _this._releaseTexture(source);
  9642. _this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9643. continuationCallback();
  9644. });
  9645. return true;
  9646. }, samplingMode);
  9647. };
  9648. if (!fromData || isBase64)
  9649. if (buffer instanceof HTMLImageElement) {
  9650. onload(buffer);
  9651. }
  9652. else {
  9653. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  9654. }
  9655. else if (buffer instanceof Array || typeof buffer === "string")
  9656. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  9657. else
  9658. onload(buffer);
  9659. }
  9660. return texture;
  9661. };
  9662. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  9663. var _this = this;
  9664. var rtt = this.createRenderTargetTexture({
  9665. width: destination.width,
  9666. height: destination.height,
  9667. }, {
  9668. generateMipMaps: false,
  9669. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  9670. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  9671. generateDepthBuffer: false,
  9672. generateStencilBuffer: false
  9673. });
  9674. if (!this._rescalePostProcess) {
  9675. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  9676. }
  9677. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  9678. _this._rescalePostProcess.onApply = function (effect) {
  9679. effect._bindTexture("textureSampler", source);
  9680. };
  9681. scene.postProcessManager.directRender([_this._rescalePostProcess], rtt);
  9682. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination);
  9683. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  9684. _this.unBindFramebuffer(rtt);
  9685. _this._releaseTexture(rtt);
  9686. if (onComplete) {
  9687. onComplete();
  9688. }
  9689. });
  9690. };
  9691. Engine.prototype._getInternalFormat = function (format) {
  9692. var internalFormat = this._gl.RGBA;
  9693. switch (format) {
  9694. case Engine.TEXTUREFORMAT_ALPHA:
  9695. internalFormat = this._gl.ALPHA;
  9696. break;
  9697. case Engine.TEXTUREFORMAT_LUMINANCE:
  9698. internalFormat = this._gl.LUMINANCE;
  9699. break;
  9700. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  9701. internalFormat = this._gl.LUMINANCE_ALPHA;
  9702. break;
  9703. case Engine.TEXTUREFORMAT_RGB:
  9704. internalFormat = this._gl.RGB;
  9705. break;
  9706. case Engine.TEXTUREFORMAT_RGBA:
  9707. internalFormat = this._gl.RGBA;
  9708. break;
  9709. }
  9710. return internalFormat;
  9711. };
  9712. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression) {
  9713. if (compression === void 0) { compression = null; }
  9714. var internalFormat = this._getInternalFormat(format);
  9715. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9716. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  9717. if (!this._doNotHandleContextLost) {
  9718. texture._bufferView = data;
  9719. texture.format = format;
  9720. texture.invertY = invertY;
  9721. texture._compression = compression;
  9722. }
  9723. if (texture.width % 4 !== 0) {
  9724. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  9725. }
  9726. if (compression) {
  9727. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  9728. }
  9729. else {
  9730. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, texture.width, texture.height, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  9731. }
  9732. if (texture.generateMipMaps) {
  9733. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9734. }
  9735. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9736. this.resetTextureCache();
  9737. texture.isReady = true;
  9738. };
  9739. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression) {
  9740. if (compression === void 0) { compression = null; }
  9741. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  9742. texture.baseWidth = width;
  9743. texture.baseHeight = height;
  9744. texture.width = width;
  9745. texture.height = height;
  9746. texture.format = format;
  9747. texture.generateMipMaps = generateMipMaps;
  9748. texture.samplingMode = samplingMode;
  9749. texture.invertY = invertY;
  9750. texture._compression = compression;
  9751. if (!this._doNotHandleContextLost) {
  9752. texture._bufferView = data;
  9753. }
  9754. this.updateRawTexture(texture, data, format, invertY, compression);
  9755. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9756. // Filters
  9757. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  9758. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9759. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9760. if (generateMipMaps) {
  9761. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9762. }
  9763. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9764. this._internalTexturesCache.push(texture);
  9765. return texture;
  9766. };
  9767. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  9768. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  9769. texture.baseWidth = width;
  9770. texture.baseHeight = height;
  9771. if (generateMipMaps) {
  9772. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  9773. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  9774. }
  9775. this.resetTextureCache();
  9776. texture.width = width;
  9777. texture.height = height;
  9778. texture.isReady = false;
  9779. texture.generateMipMaps = generateMipMaps;
  9780. texture.samplingMode = samplingMode;
  9781. this.updateTextureSamplingMode(samplingMode, texture);
  9782. this._internalTexturesCache.push(texture);
  9783. return texture;
  9784. };
  9785. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  9786. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  9787. if (texture.isCube) {
  9788. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  9789. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9790. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9791. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  9792. }
  9793. else {
  9794. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9795. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  9796. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  9797. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9798. }
  9799. texture.samplingMode = samplingMode;
  9800. };
  9801. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  9802. if (premulAlpha === void 0) { premulAlpha = false; }
  9803. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9804. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  9805. if (premulAlpha) {
  9806. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  9807. }
  9808. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  9809. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  9810. if (texture.generateMipMaps) {
  9811. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9812. }
  9813. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9814. if (premulAlpha) {
  9815. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  9816. }
  9817. this.resetTextureCache();
  9818. texture.isReady = true;
  9819. };
  9820. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  9821. if (texture._isDisabled) {
  9822. return;
  9823. }
  9824. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  9825. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  9826. try {
  9827. // Testing video texture support
  9828. if (this._videoTextureSupported === undefined) {
  9829. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9830. if (this._gl.getError() !== 0) {
  9831. this._videoTextureSupported = false;
  9832. }
  9833. else {
  9834. this._videoTextureSupported = true;
  9835. }
  9836. }
  9837. // Copy video through the current working canvas if video texture is not supported
  9838. if (!this._videoTextureSupported) {
  9839. if (!texture._workingCanvas) {
  9840. texture._workingCanvas = document.createElement("canvas");
  9841. texture._workingContext = texture._workingCanvas.getContext("2d");
  9842. texture._workingCanvas.width = texture.width;
  9843. texture._workingCanvas.height = texture.height;
  9844. }
  9845. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  9846. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  9847. }
  9848. else {
  9849. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  9850. }
  9851. if (texture.generateMipMaps) {
  9852. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9853. }
  9854. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  9855. this.resetTextureCache();
  9856. texture.isReady = true;
  9857. }
  9858. catch (ex) {
  9859. // Something unexpected
  9860. // Let's disable the texture
  9861. texture._isDisabled = true;
  9862. }
  9863. };
  9864. Engine.prototype.createRenderTargetTexture = function (size, options) {
  9865. var fullOptions = new RenderTargetCreationOptions();
  9866. if (options !== undefined && typeof options === "object") {
  9867. fullOptions.generateMipMaps = options.generateMipMaps;
  9868. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9869. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  9870. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  9871. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  9872. }
  9873. else {
  9874. fullOptions.generateMipMaps = options;
  9875. fullOptions.generateDepthBuffer = true;
  9876. fullOptions.generateStencilBuffer = false;
  9877. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9878. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9879. }
  9880. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9881. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9882. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9883. }
  9884. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9885. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9886. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9887. }
  9888. var gl = this._gl;
  9889. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  9890. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  9891. var width = size.width || size;
  9892. var height = size.height || size;
  9893. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  9894. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9895. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9896. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9897. }
  9898. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9899. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9900. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9901. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9902. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type), width, height, 0, gl.RGBA, this._getWebGLTextureType(fullOptions.type), null);
  9903. // Create the framebuffer
  9904. var framebuffer = gl.createFramebuffer();
  9905. this.bindUnboundFramebuffer(framebuffer);
  9906. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9907. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, width, height);
  9908. if (fullOptions.generateMipMaps) {
  9909. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9910. }
  9911. // Unbind
  9912. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9913. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  9914. this.bindUnboundFramebuffer(null);
  9915. texture._framebuffer = framebuffer;
  9916. texture.baseWidth = width;
  9917. texture.baseHeight = height;
  9918. texture.width = width;
  9919. texture.height = height;
  9920. texture.isReady = true;
  9921. texture.samples = 1;
  9922. texture.generateMipMaps = fullOptions.generateMipMaps;
  9923. texture.samplingMode = fullOptions.samplingMode;
  9924. texture.type = fullOptions.type;
  9925. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  9926. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  9927. this.resetTextureCache();
  9928. this._internalTexturesCache.push(texture);
  9929. return texture;
  9930. };
  9931. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  9932. var generateMipMaps = false;
  9933. var generateDepthBuffer = true;
  9934. var generateStencilBuffer = false;
  9935. var generateDepthTexture = false;
  9936. var textureCount = 1;
  9937. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  9938. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  9939. var types = [], samplingModes = [];
  9940. if (options !== undefined) {
  9941. generateMipMaps = options.generateMipMaps;
  9942. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  9943. generateStencilBuffer = options.generateStencilBuffer;
  9944. generateDepthTexture = options.generateDepthTexture;
  9945. textureCount = options.textureCount || 1;
  9946. if (options.types) {
  9947. types = options.types;
  9948. }
  9949. if (options.samplingModes) {
  9950. samplingModes = options.samplingModes;
  9951. }
  9952. }
  9953. var gl = this._gl;
  9954. // Create the framebuffer
  9955. var framebuffer = gl.createFramebuffer();
  9956. this.bindUnboundFramebuffer(framebuffer);
  9957. var width = size.width || size;
  9958. var height = size.height || size;
  9959. var textures = [];
  9960. var attachments = [];
  9961. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  9962. for (var i = 0; i < textureCount; i++) {
  9963. var samplingMode = samplingModes[i] || defaultSamplingMode;
  9964. var type = types[i] || defaultType;
  9965. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  9966. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  9967. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9968. }
  9969. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  9970. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  9971. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  9972. }
  9973. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  9974. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  9975. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  9976. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  9977. }
  9978. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  9979. var attachment = gl["COLOR_ATTACHMENT" + i];
  9980. textures.push(texture);
  9981. attachments.push(attachment);
  9982. gl.activeTexture(gl["TEXTURE" + i]);
  9983. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  9984. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  9985. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  9986. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  9987. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  9988. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  9989. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  9990. if (generateMipMaps) {
  9991. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  9992. }
  9993. // Unbind
  9994. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  9995. texture._framebuffer = framebuffer;
  9996. texture._depthStencilBuffer = depthStencilBuffer;
  9997. texture.baseWidth = width;
  9998. texture.baseHeight = height;
  9999. texture.width = width;
  10000. texture.height = height;
  10001. texture.isReady = true;
  10002. texture.samples = 1;
  10003. texture.generateMipMaps = generateMipMaps;
  10004. texture.samplingMode = samplingMode;
  10005. texture.type = type;
  10006. texture._generateDepthBuffer = generateDepthBuffer;
  10007. texture._generateStencilBuffer = generateStencilBuffer;
  10008. this._internalTexturesCache.push(texture);
  10009. }
  10010. if (generateDepthTexture) {
  10011. // Depth texture
  10012. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  10013. gl.activeTexture(gl.TEXTURE0);
  10014. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  10015. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10016. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10017. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10018. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10019. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT16, width, height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_SHORT, null);
  10020. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  10021. depthTexture._framebuffer = framebuffer;
  10022. depthTexture.baseWidth = width;
  10023. depthTexture.baseHeight = height;
  10024. depthTexture.width = width;
  10025. depthTexture.height = height;
  10026. depthTexture.isReady = true;
  10027. depthTexture.samples = 1;
  10028. depthTexture.generateMipMaps = generateMipMaps;
  10029. depthTexture.samplingMode = gl.NEAREST;
  10030. depthTexture._generateDepthBuffer = generateDepthBuffer;
  10031. depthTexture._generateStencilBuffer = generateStencilBuffer;
  10032. textures.push(depthTexture);
  10033. this._internalTexturesCache.push(depthTexture);
  10034. }
  10035. gl.drawBuffers(attachments);
  10036. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10037. this.bindUnboundFramebuffer(null);
  10038. this.resetTextureCache();
  10039. return textures;
  10040. };
  10041. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  10042. if (samples === void 0) { samples = 1; }
  10043. var depthStencilBuffer = null;
  10044. var gl = this._gl;
  10045. // Create the depth/stencil buffer
  10046. if (generateStencilBuffer) {
  10047. depthStencilBuffer = gl.createRenderbuffer();
  10048. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10049. if (samples > 1) {
  10050. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  10051. }
  10052. else {
  10053. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  10054. }
  10055. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10056. }
  10057. else if (generateDepthBuffer) {
  10058. depthStencilBuffer = gl.createRenderbuffer();
  10059. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  10060. if (samples > 1) {
  10061. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  10062. }
  10063. else {
  10064. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  10065. }
  10066. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  10067. }
  10068. return depthStencilBuffer;
  10069. };
  10070. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  10071. if (this.webGLVersion < 2) {
  10072. return 1;
  10073. }
  10074. if (texture.samples === samples) {
  10075. return samples;
  10076. }
  10077. var gl = this._gl;
  10078. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  10079. // Dispose previous render buffers
  10080. if (texture._depthStencilBuffer) {
  10081. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10082. }
  10083. if (texture._MSAAFramebuffer) {
  10084. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10085. }
  10086. if (texture._MSAARenderBuffer) {
  10087. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10088. }
  10089. if (samples > 1) {
  10090. texture._MSAAFramebuffer = gl.createFramebuffer();
  10091. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  10092. var colorRenderbuffer = gl.createRenderbuffer();
  10093. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  10094. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.RGBA8, texture.width, texture.height);
  10095. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  10096. texture._MSAARenderBuffer = colorRenderbuffer;
  10097. }
  10098. else {
  10099. this.bindUnboundFramebuffer(texture._framebuffer);
  10100. }
  10101. texture.samples = samples;
  10102. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  10103. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10104. this.bindUnboundFramebuffer(null);
  10105. return samples;
  10106. };
  10107. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  10108. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  10109. };
  10110. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  10111. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  10112. };
  10113. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  10114. var gl = this._gl;
  10115. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  10116. var generateMipMaps = true;
  10117. var generateDepthBuffer = true;
  10118. var generateStencilBuffer = false;
  10119. var samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  10120. if (options !== undefined) {
  10121. generateMipMaps = options.generateMipMaps === undefined ? true : options.generateMipMaps;
  10122. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  10123. generateStencilBuffer = generateDepthBuffer && options.generateStencilBuffer;
  10124. if (options.samplingMode !== undefined) {
  10125. samplingMode = options.samplingMode;
  10126. }
  10127. }
  10128. texture.isCube = true;
  10129. texture.generateMipMaps = generateMipMaps;
  10130. texture.samples = 1;
  10131. texture.samplingMode = samplingMode;
  10132. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10133. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10134. for (var face = 0; face < 6; face++) {
  10135. gl.texImage2D((gl.TEXTURE_CUBE_MAP_POSITIVE_X + face), 0, gl.RGBA, size, size, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
  10136. }
  10137. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10138. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10139. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10140. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10141. // Create the framebuffer
  10142. var framebuffer = gl.createFramebuffer();
  10143. this.bindUnboundFramebuffer(framebuffer);
  10144. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, size, size);
  10145. // Mipmaps
  10146. if (texture.generateMipMaps) {
  10147. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10149. }
  10150. // Unbind
  10151. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10152. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  10153. this.bindUnboundFramebuffer(null);
  10154. texture._framebuffer = framebuffer;
  10155. texture.width = size;
  10156. texture.height = size;
  10157. texture.isReady = true;
  10158. this.resetTextureCache();
  10159. this._internalTexturesCache.push(texture);
  10160. return texture;
  10161. };
  10162. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  10163. var _this = this;
  10164. if (onError === void 0) { onError = null; }
  10165. if (forcedExtension === void 0) { forcedExtension = null; }
  10166. var callback = function (loadData) {
  10167. if (!loadData) {
  10168. if (onLoad) {
  10169. onLoad(null);
  10170. }
  10171. return;
  10172. }
  10173. var texture = loadData.texture;
  10174. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  10175. texture._lodGenerationScale = scale;
  10176. texture._lodGenerationOffset = offset;
  10177. if (_this._caps.textureLOD) {
  10178. // Do not add extra process if texture lod is supported.
  10179. if (onLoad) {
  10180. onLoad(texture);
  10181. }
  10182. return;
  10183. }
  10184. var mipSlices = 3;
  10185. var gl = _this._gl;
  10186. var width = loadData.width;
  10187. if (!width) {
  10188. return;
  10189. }
  10190. var textures = [];
  10191. for (var i = 0; i < mipSlices; i++) {
  10192. //compute LOD from even spacing in smoothness (matching shader calculation)
  10193. var smoothness = i / (mipSlices - 1);
  10194. var roughness = 1 - smoothness;
  10195. var minLODIndex = offset; // roughness = 0
  10196. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  10197. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  10198. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  10199. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  10200. glTextureFromLod.isCube = true;
  10201. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod);
  10202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10203. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  10204. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10206. if (loadData.isDDS) {
  10207. var info = loadData.info;
  10208. var data = loadData.data;
  10209. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10210. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  10211. }
  10212. else {
  10213. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  10214. }
  10215. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10216. // Wrap in a base texture for easy binding.
  10217. var lodTexture = new BABYLON.BaseTexture(scene);
  10218. lodTexture.isCube = true;
  10219. lodTexture._texture = glTextureFromLod;
  10220. glTextureFromLod.isReady = true;
  10221. textures.push(lodTexture);
  10222. }
  10223. texture._lodTextureHigh = textures[2];
  10224. texture._lodTextureMid = textures[1];
  10225. texture._lodTextureLow = textures[0];
  10226. if (onLoad) {
  10227. onLoad(texture);
  10228. }
  10229. };
  10230. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension);
  10231. };
  10232. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension) {
  10233. var _this = this;
  10234. if (onLoad === void 0) { onLoad = null; }
  10235. if (onError === void 0) { onError = null; }
  10236. if (forcedExtension === void 0) { forcedExtension = null; }
  10237. var gl = this._gl;
  10238. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  10239. texture.isCube = true;
  10240. texture.url = rootUrl;
  10241. texture.generateMipMaps = !noMipmap;
  10242. if (!this._doNotHandleContextLost) {
  10243. texture._extension = forcedExtension;
  10244. texture._files = files;
  10245. }
  10246. var isKTX = false;
  10247. var isDDS = false;
  10248. var lastDot = rootUrl.lastIndexOf('.');
  10249. var extension = forcedExtension ? forcedExtension : rootUrl.substring(lastDot).toLowerCase();
  10250. if (this._textureFormatInUse) {
  10251. extension = this._textureFormatInUse;
  10252. rootUrl = rootUrl.substring(0, lastDot) + this._textureFormatInUse;
  10253. isKTX = true;
  10254. }
  10255. else {
  10256. isDDS = (extension === ".dds");
  10257. }
  10258. if (isKTX) {
  10259. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10260. var ktx = new BABYLON.Internals.KhronosTextureContainer(data, 6);
  10261. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  10262. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10263. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  10264. ktx.uploadLevels(_this._gl, !noMipmap);
  10265. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10266. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10267. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10268. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10269. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10270. _this.resetTextureCache();
  10271. texture.width = ktx.pixelWidth;
  10272. texture.height = ktx.pixelHeight;
  10273. texture.isReady = true;
  10274. }, null, null, true, onError);
  10275. }
  10276. else if (isDDS) {
  10277. BABYLON.Tools.LoadFile(rootUrl, function (data) {
  10278. var info = BABYLON.Internals.DDSTools.GetDDSInfo(data);
  10279. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  10280. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10281. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  10282. BABYLON.Internals.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  10283. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  10284. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10285. }
  10286. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10287. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  10288. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10289. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10290. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10291. _this.resetTextureCache();
  10292. texture.width = info.width;
  10293. texture.height = info.height;
  10294. texture.isReady = true;
  10295. texture.type = info.textureType;
  10296. if (onLoad) {
  10297. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  10298. }
  10299. }, null, null, true, onError);
  10300. }
  10301. else {
  10302. cascadeLoad(rootUrl, scene, function (imgs) {
  10303. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  10304. var height = width;
  10305. _this._prepareWorkingCanvas();
  10306. _this._workingCanvas.width = width;
  10307. _this._workingCanvas.height = height;
  10308. var faces = [
  10309. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  10310. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  10311. ];
  10312. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10313. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10314. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  10315. for (var index = 0; index < faces.length; index++) {
  10316. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  10317. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  10318. }
  10319. if (!noMipmap) {
  10320. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  10321. }
  10322. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  10323. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, noMipmap ? gl.LINEAR : gl.LINEAR_MIPMAP_LINEAR);
  10324. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10325. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10326. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10327. _this.resetTextureCache();
  10328. texture.width = width;
  10329. texture.height = height;
  10330. texture.isReady = true;
  10331. texture.format = format;
  10332. texture.onLoadedObservable.notifyObservers(texture);
  10333. texture.onLoadedObservable.clear();
  10334. if (onLoad) {
  10335. onLoad();
  10336. }
  10337. }, files, onError);
  10338. }
  10339. this._internalTexturesCache.push(texture);
  10340. return texture;
  10341. };
  10342. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  10343. if (compression === void 0) { compression = null; }
  10344. if (level === void 0) { level = 0; }
  10345. var gl = this._gl;
  10346. var textureType = this._getWebGLTextureType(type);
  10347. var internalFormat = this._getInternalFormat(format);
  10348. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10349. var needConversion = false;
  10350. if (internalFormat === gl.RGB) {
  10351. internalFormat = gl.RGBA;
  10352. needConversion = true;
  10353. }
  10354. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10355. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10356. if (texture.width % 4 !== 0) {
  10357. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  10358. }
  10359. // Data are known to be in +X +Y +Z -X -Y -Z
  10360. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10361. var faceData = data[faceIndex];
  10362. if (compression) {
  10363. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, this.getCaps().s3tc[compression], texture.width, texture.height, 0, faceData);
  10364. }
  10365. else {
  10366. if (needConversion) {
  10367. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  10368. }
  10369. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  10370. }
  10371. }
  10372. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10373. if (isPot && texture.generateMipMaps && level === 0) {
  10374. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10375. }
  10376. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10377. this.resetTextureCache();
  10378. texture.isReady = true;
  10379. };
  10380. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  10381. if (compression === void 0) { compression = null; }
  10382. var gl = this._gl;
  10383. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  10384. texture.isCube = true;
  10385. texture.generateMipMaps = generateMipMaps;
  10386. texture.format = format;
  10387. texture.type = type;
  10388. var textureType = this._getWebGLTextureType(type);
  10389. var internalFormat = this._getInternalFormat(format);
  10390. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  10391. var needConversion = false;
  10392. if (internalFormat === gl.RGB) {
  10393. internalFormat = gl.RGBA;
  10394. needConversion = true;
  10395. }
  10396. var width = size;
  10397. var height = width;
  10398. texture.width = width;
  10399. texture.height = height;
  10400. // Double check on POT to generate Mips.
  10401. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  10402. if (!isPot) {
  10403. generateMipMaps = false;
  10404. }
  10405. // Upload data if needed. The texture won t be ready until then.
  10406. if (data) {
  10407. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  10408. }
  10409. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture);
  10410. // Filters
  10411. if (data && generateMipMaps) {
  10412. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  10413. }
  10414. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  10415. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10416. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10417. }
  10418. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  10419. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  10420. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  10421. }
  10422. else {
  10423. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  10424. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  10425. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  10426. }
  10427. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  10428. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  10429. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10430. return texture;
  10431. };
  10432. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmmapGenerator, onLoad, onError, samplingMode, invertY) {
  10433. var _this = this;
  10434. if (onLoad === void 0) { onLoad = null; }
  10435. if (onError === void 0) { onError = null; }
  10436. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10437. if (invertY === void 0) { invertY = false; }
  10438. var gl = this._gl;
  10439. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  10440. scene._addPendingData(texture);
  10441. texture.url = url;
  10442. this._internalTexturesCache.push(texture);
  10443. var onerror = function () {
  10444. scene._removePendingData(texture);
  10445. if (onError) {
  10446. onError();
  10447. }
  10448. };
  10449. var internalCallback = function (data) {
  10450. var width = texture.width;
  10451. var height = texture.height;
  10452. var faceDataArrays = callback(data);
  10453. if (mipmmapGenerator) {
  10454. var textureType = _this._getWebGLTextureType(type);
  10455. var internalFormat = _this._getInternalFormat(format);
  10456. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  10457. var needConversion = false;
  10458. if (internalFormat === gl.RGB) {
  10459. internalFormat = gl.RGBA;
  10460. needConversion = true;
  10461. }
  10462. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture);
  10463. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  10464. var mipData = mipmmapGenerator(faceDataArrays);
  10465. for (var level = 0; level < mipData.length; level++) {
  10466. var mipSize = width >> level;
  10467. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  10468. var mipFaceData = mipData[level][faceIndex];
  10469. if (needConversion) {
  10470. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  10471. }
  10472. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  10473. }
  10474. }
  10475. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  10476. }
  10477. else {
  10478. texture.generateMipMaps = !noMipmap;
  10479. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  10480. }
  10481. texture.isReady = true;
  10482. _this.resetTextureCache();
  10483. scene._removePendingData(texture);
  10484. if (onLoad) {
  10485. onLoad();
  10486. }
  10487. };
  10488. BABYLON.Tools.LoadFile(url, function (data) {
  10489. internalCallback(data);
  10490. }, onerror, scene.database, true);
  10491. return texture;
  10492. };
  10493. ;
  10494. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  10495. var gl = this._gl;
  10496. if (!gl) {
  10497. return;
  10498. }
  10499. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  10500. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  10501. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  10502. if (!noMipmap && !isCompressed) {
  10503. gl.generateMipmap(gl.TEXTURE_2D);
  10504. }
  10505. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  10506. this.resetTextureCache();
  10507. if (scene) {
  10508. scene._removePendingData(texture);
  10509. }
  10510. texture.onLoadedObservable.notifyObservers(texture);
  10511. texture.onLoadedObservable.clear();
  10512. };
  10513. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  10514. var _this = this;
  10515. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  10516. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  10517. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  10518. var gl = this._gl;
  10519. if (!gl) {
  10520. return;
  10521. }
  10522. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  10523. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  10524. texture.baseWidth = width;
  10525. texture.baseHeight = height;
  10526. texture.width = potWidth;
  10527. texture.height = potHeight;
  10528. texture.isReady = true;
  10529. if (processFunction(potWidth, potHeight, function () {
  10530. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10531. })) {
  10532. // Returning as texture needs extra async steps
  10533. return;
  10534. }
  10535. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  10536. };
  10537. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  10538. // Create new RGBA data container.
  10539. var rgbaData;
  10540. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  10541. rgbaData = new Float32Array(width * height * 4);
  10542. }
  10543. else {
  10544. rgbaData = new Uint32Array(width * height * 4);
  10545. }
  10546. // Convert each pixel.
  10547. for (var x = 0; x < width; x++) {
  10548. for (var y = 0; y < height; y++) {
  10549. var index = (y * width + x) * 3;
  10550. var newIndex = (y * width + x) * 4;
  10551. // Map Old Value to new value.
  10552. rgbaData[newIndex + 0] = rgbData[index + 0];
  10553. rgbaData[newIndex + 1] = rgbData[index + 1];
  10554. rgbaData[newIndex + 2] = rgbData[index + 2];
  10555. // Add fully opaque alpha channel.
  10556. rgbaData[newIndex + 3] = 1;
  10557. }
  10558. }
  10559. return rgbaData;
  10560. };
  10561. Engine.prototype._releaseFramebufferObjects = function (texture) {
  10562. var gl = this._gl;
  10563. if (texture._framebuffer) {
  10564. gl.deleteFramebuffer(texture._framebuffer);
  10565. texture._framebuffer = null;
  10566. }
  10567. if (texture._depthStencilBuffer) {
  10568. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  10569. texture._depthStencilBuffer = null;
  10570. }
  10571. if (texture._MSAAFramebuffer) {
  10572. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  10573. texture._MSAAFramebuffer = null;
  10574. }
  10575. if (texture._MSAARenderBuffer) {
  10576. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  10577. texture._MSAARenderBuffer = null;
  10578. }
  10579. };
  10580. Engine.prototype._releaseTexture = function (texture) {
  10581. var gl = this._gl;
  10582. this._releaseFramebufferObjects(texture);
  10583. gl.deleteTexture(texture._webGLTexture);
  10584. // Unbind channels
  10585. this.unbindAllTextures();
  10586. var index = this._internalTexturesCache.indexOf(texture);
  10587. if (index !== -1) {
  10588. this._internalTexturesCache.splice(index, 1);
  10589. }
  10590. // Integrated fixed lod samplers.
  10591. if (texture._lodTextureHigh) {
  10592. texture._lodTextureHigh.dispose();
  10593. }
  10594. if (texture._lodTextureMid) {
  10595. texture._lodTextureMid.dispose();
  10596. }
  10597. if (texture._lodTextureLow) {
  10598. texture._lodTextureLow.dispose();
  10599. }
  10600. };
  10601. Engine.prototype.setProgram = function (program) {
  10602. if (this._currentProgram !== program) {
  10603. this._gl.useProgram(program);
  10604. this._currentProgram = program;
  10605. }
  10606. };
  10607. Engine.prototype.bindSamplers = function (effect) {
  10608. this.setProgram(effect.getProgram());
  10609. var samplers = effect.getSamplers();
  10610. for (var index = 0; index < samplers.length; index++) {
  10611. var uniform = effect.getUniform(samplers[index]);
  10612. this._gl.uniform1i(uniform, index);
  10613. }
  10614. this._currentEffect = null;
  10615. };
  10616. Engine.prototype.activateTexture = function (texture) {
  10617. if (this._activeTexture !== texture) {
  10618. this._gl.activeTexture(texture);
  10619. this._activeTexture = texture;
  10620. }
  10621. };
  10622. Engine.prototype._bindTextureDirectly = function (target, texture) {
  10623. if (this._activeTexturesCache[this._activeTexture] !== texture) {
  10624. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  10625. this._activeTexturesCache[this._activeTexture] = texture;
  10626. }
  10627. };
  10628. Engine.prototype._bindTexture = function (channel, texture) {
  10629. if (channel < 0) {
  10630. return;
  10631. }
  10632. this.activateTexture(this._gl.TEXTURE0 + channel);
  10633. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  10634. };
  10635. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  10636. this._bindTexture(channel, postProcess._textures.data[postProcess._currentRenderTextureInd]);
  10637. };
  10638. Engine.prototype.unbindAllTextures = function () {
  10639. for (var channel = 0; channel < this._caps.maxTexturesImageUnits; channel++) {
  10640. this.activateTexture(this._gl["TEXTURE" + channel]);
  10641. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10642. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10643. }
  10644. };
  10645. Engine.prototype.setTexture = function (channel, uniform, texture) {
  10646. if (channel < 0) {
  10647. return;
  10648. }
  10649. this._gl.uniform1i(uniform, channel);
  10650. this._setTexture(channel, texture);
  10651. };
  10652. Engine.prototype._setTexture = function (channel, texture) {
  10653. // Not ready?
  10654. if (!texture) {
  10655. if (this._activeTexturesCache[channel] != null) {
  10656. this.activateTexture(this._gl["TEXTURE" + channel]);
  10657. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  10658. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  10659. }
  10660. return;
  10661. }
  10662. // Video
  10663. var alreadyActivated = false;
  10664. if (texture.video) {
  10665. this.activateTexture(this._gl["TEXTURE" + channel]);
  10666. alreadyActivated = true;
  10667. texture.update();
  10668. }
  10669. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) {
  10670. texture.delayLoad();
  10671. return;
  10672. }
  10673. var internalTexture = texture.isReady() ? texture.getInternalTexture() :
  10674. (texture.isCube ? this.emptyCubeTexture : this.emptyTexture);
  10675. if (this._activeTexturesCache[channel] === internalTexture) {
  10676. return;
  10677. }
  10678. if (!alreadyActivated) {
  10679. this.activateTexture(this._gl["TEXTURE" + channel]);
  10680. }
  10681. if (internalTexture.isCube) {
  10682. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture);
  10683. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  10684. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  10685. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  10686. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  10687. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode);
  10688. this._gl.texParameteri(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  10689. }
  10690. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  10691. }
  10692. else {
  10693. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture);
  10694. if (internalTexture._cachedWrapU !== texture.wrapU) {
  10695. internalTexture._cachedWrapU = texture.wrapU;
  10696. switch (texture.wrapU) {
  10697. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10698. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.REPEAT);
  10699. break;
  10700. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10701. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.CLAMP_TO_EDGE);
  10702. break;
  10703. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10704. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._gl.MIRRORED_REPEAT);
  10705. break;
  10706. }
  10707. }
  10708. if (internalTexture._cachedWrapV !== texture.wrapV) {
  10709. internalTexture._cachedWrapV = texture.wrapV;
  10710. switch (texture.wrapV) {
  10711. case BABYLON.Texture.WRAP_ADDRESSMODE:
  10712. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.REPEAT);
  10713. break;
  10714. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  10715. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.CLAMP_TO_EDGE);
  10716. break;
  10717. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  10718. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._gl.MIRRORED_REPEAT);
  10719. break;
  10720. }
  10721. }
  10722. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  10723. }
  10724. };
  10725. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  10726. if (channel < 0) {
  10727. return;
  10728. }
  10729. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  10730. this._textureUnits = new Int32Array(textures.length);
  10731. }
  10732. for (var i = 0; i < textures.length; i++) {
  10733. this._textureUnits[i] = channel + i;
  10734. }
  10735. this._gl.uniform1iv(uniform, this._textureUnits);
  10736. for (var index = 0; index < textures.length; index++) {
  10737. this._setTexture(channel + index, textures[index]);
  10738. }
  10739. };
  10740. Engine.prototype._setAnisotropicLevel = function (key, texture) {
  10741. var internalTexture = texture.getInternalTexture();
  10742. if (!internalTexture) {
  10743. return;
  10744. }
  10745. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  10746. var value = texture.anisotropicFilteringLevel;
  10747. if (internalTexture.samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  10748. value = 1;
  10749. }
  10750. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  10751. this._gl.texParameterf(key, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy));
  10752. internalTexture._cachedAnisotropicFilteringLevel = value;
  10753. }
  10754. };
  10755. Engine.prototype.readPixels = function (x, y, width, height) {
  10756. var data = new Uint8Array(height * width * 4);
  10757. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  10758. return data;
  10759. };
  10760. /**
  10761. * Add an externaly attached data from its key.
  10762. * This method call will fail and return false, if such key already exists.
  10763. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  10764. * @param key the unique key that identifies the data
  10765. * @param data the data object to associate to the key for this Engine instance
  10766. * @return true if no such key were already present and the data was added successfully, false otherwise
  10767. */
  10768. Engine.prototype.addExternalData = function (key, data) {
  10769. if (!this._externalData) {
  10770. this._externalData = new BABYLON.StringDictionary();
  10771. }
  10772. return this._externalData.add(key, data);
  10773. };
  10774. /**
  10775. * Get an externaly attached data from its key
  10776. * @param key the unique key that identifies the data
  10777. * @return the associated data, if present (can be null), or undefined if not present
  10778. */
  10779. Engine.prototype.getExternalData = function (key) {
  10780. if (!this._externalData) {
  10781. this._externalData = new BABYLON.StringDictionary();
  10782. }
  10783. return this._externalData.get(key);
  10784. };
  10785. /**
  10786. * Get an externaly attached data from its key, create it using a factory if it's not already present
  10787. * @param key the unique key that identifies the data
  10788. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  10789. * @return the associated data, can be null if the factory returned null.
  10790. */
  10791. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  10792. if (!this._externalData) {
  10793. this._externalData = new BABYLON.StringDictionary();
  10794. }
  10795. return this._externalData.getOrAddWithFactory(key, factory);
  10796. };
  10797. /**
  10798. * Remove an externaly attached data from the Engine instance
  10799. * @param key the unique key that identifies the data
  10800. * @return true if the data was successfully removed, false if it doesn't exist
  10801. */
  10802. Engine.prototype.removeExternalData = function (key) {
  10803. if (!this._externalData) {
  10804. this._externalData = new BABYLON.StringDictionary();
  10805. }
  10806. return this._externalData.remove(key);
  10807. };
  10808. Engine.prototype.unbindAllAttributes = function () {
  10809. if (this._mustWipeVertexAttributes) {
  10810. this._mustWipeVertexAttributes = false;
  10811. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  10812. this._gl.disableVertexAttribArray(i);
  10813. this._vertexAttribArraysEnabled[i] = false;
  10814. this._currentBufferPointers[i].active = false;
  10815. }
  10816. return;
  10817. }
  10818. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  10819. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  10820. continue;
  10821. }
  10822. this._gl.disableVertexAttribArray(i);
  10823. this._vertexAttribArraysEnabled[i] = false;
  10824. this._currentBufferPointers[i].active = false;
  10825. }
  10826. };
  10827. Engine.prototype.releaseEffects = function () {
  10828. for (var name in this._compiledEffects) {
  10829. this._gl.deleteProgram(this._compiledEffects[name]._program);
  10830. }
  10831. this._compiledEffects = {};
  10832. };
  10833. // Dispose
  10834. Engine.prototype.dispose = function () {
  10835. this.hideLoadingUI();
  10836. this.stopRenderLoop();
  10837. // Release postProcesses
  10838. while (this.postProcesses.length) {
  10839. this.postProcesses[0].dispose();
  10840. }
  10841. // Empty texture
  10842. if (this._emptyTexture) {
  10843. this._releaseTexture(this._emptyTexture);
  10844. this._emptyTexture = null;
  10845. }
  10846. if (this._emptyCubeTexture) {
  10847. this._releaseTexture(this._emptyCubeTexture);
  10848. this._emptyCubeTexture = null;
  10849. }
  10850. // Rescale PP
  10851. if (this._rescalePostProcess) {
  10852. this._rescalePostProcess.dispose();
  10853. }
  10854. // Release scenes
  10855. while (this.scenes.length) {
  10856. this.scenes[0].dispose();
  10857. }
  10858. // Release audio engine
  10859. if (Engine.audioEngine) {
  10860. Engine.audioEngine.dispose();
  10861. }
  10862. // Release effects
  10863. this.releaseEffects();
  10864. // Unbind
  10865. this.unbindAllAttributes();
  10866. if (this._dummyFramebuffer) {
  10867. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  10868. }
  10869. this._gl = null;
  10870. //WebVR
  10871. this.disableVR();
  10872. // Events
  10873. window.removeEventListener("blur", this._onBlur);
  10874. window.removeEventListener("focus", this._onFocus);
  10875. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  10876. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  10877. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasBlur);
  10878. if (!this._doNotHandleContextLost) {
  10879. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  10880. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  10881. }
  10882. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  10883. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  10884. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  10885. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  10886. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  10887. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  10888. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  10889. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  10890. // Remove from Instances
  10891. var index = Engine.Instances.indexOf(this);
  10892. if (index >= 0) {
  10893. Engine.Instances.splice(index, 1);
  10894. }
  10895. this._workingCanvas = null;
  10896. this._workingContext = null;
  10897. this._currentBufferPointers = null;
  10898. this._renderingCanvas = null;
  10899. this._currentProgram = null;
  10900. this.onResizeObservable.clear();
  10901. this.onCanvasBlurObservable.clear();
  10902. BABYLON.Effect.ResetCache();
  10903. };
  10904. // Loading screen
  10905. Engine.prototype.displayLoadingUI = function () {
  10906. var loadingScreen = this.loadingScreen;
  10907. if (loadingScreen) {
  10908. loadingScreen.displayLoadingUI();
  10909. }
  10910. };
  10911. Engine.prototype.hideLoadingUI = function () {
  10912. var loadingScreen = this.loadingScreen;
  10913. if (loadingScreen) {
  10914. loadingScreen.hideLoadingUI();
  10915. }
  10916. };
  10917. Object.defineProperty(Engine.prototype, "loadingScreen", {
  10918. get: function () {
  10919. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen)
  10920. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  10921. return this._loadingScreen;
  10922. },
  10923. set: function (loadingScreen) {
  10924. this._loadingScreen = loadingScreen;
  10925. },
  10926. enumerable: true,
  10927. configurable: true
  10928. });
  10929. Object.defineProperty(Engine.prototype, "loadingUIText", {
  10930. set: function (text) {
  10931. this.loadingScreen.loadingUIText = text;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  10937. set: function (color) {
  10938. this.loadingScreen.loadingUIBackgroundColor = color;
  10939. },
  10940. enumerable: true,
  10941. configurable: true
  10942. });
  10943. Engine.prototype.attachContextLostEvent = function (callback) {
  10944. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  10945. };
  10946. Engine.prototype.attachContextRestoredEvent = function (callback) {
  10947. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  10948. };
  10949. Engine.prototype.getVertexShaderSource = function (program) {
  10950. var shaders = this._gl.getAttachedShaders(program);
  10951. return this._gl.getShaderSource(shaders[0]);
  10952. };
  10953. Engine.prototype.getFragmentShaderSource = function (program) {
  10954. var shaders = this._gl.getAttachedShaders(program);
  10955. return this._gl.getShaderSource(shaders[1]);
  10956. };
  10957. Engine.prototype.getError = function () {
  10958. return this._gl.getError();
  10959. };
  10960. // FPS
  10961. Engine.prototype.getFps = function () {
  10962. return this._fps;
  10963. };
  10964. Engine.prototype.getDeltaTime = function () {
  10965. return this._deltaTime;
  10966. };
  10967. Engine.prototype._measureFps = function () {
  10968. this._performanceMonitor.sampleFrame();
  10969. this._fps = this._performanceMonitor.averageFPS;
  10970. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  10971. };
  10972. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  10973. if (faceIndex === void 0) { faceIndex = -1; }
  10974. var gl = this._gl;
  10975. if (!this._dummyFramebuffer) {
  10976. this._dummyFramebuffer = gl.createFramebuffer();
  10977. }
  10978. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  10979. if (faceIndex > -1) {
  10980. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  10981. }
  10982. else {
  10983. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  10984. }
  10985. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  10986. var buffer;
  10987. switch (readType) {
  10988. case gl.UNSIGNED_BYTE:
  10989. buffer = new Uint8Array(4 * width * height);
  10990. readType = gl.UNSIGNED_BYTE;
  10991. break;
  10992. default:
  10993. buffer = new Float32Array(4 * width * height);
  10994. readType = gl.FLOAT;
  10995. break;
  10996. }
  10997. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  10998. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  10999. return buffer;
  11000. };
  11001. Engine.prototype._canRenderToFloatFramebuffer = function () {
  11002. if (this._webGLVersion > 1) {
  11003. return this._caps.colorBufferFloat;
  11004. }
  11005. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_FLOAT);
  11006. };
  11007. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  11008. if (this._webGLVersion > 1) {
  11009. return this._caps.colorBufferFloat;
  11010. }
  11011. return this._canRenderToFramebuffer(BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  11012. };
  11013. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  11014. Engine.prototype._canRenderToFramebuffer = function (type) {
  11015. var gl = this._gl;
  11016. //clear existing errors
  11017. while (gl.getError() !== gl.NO_ERROR) { }
  11018. var successful = true;
  11019. var texture = gl.createTexture();
  11020. gl.bindTexture(gl.TEXTURE_2D, texture);
  11021. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  11022. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  11023. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  11024. var fb = gl.createFramebuffer();
  11025. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  11026. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  11027. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  11028. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  11029. successful = successful && (gl.getError() === gl.NO_ERROR);
  11030. //try render by clearing frame buffer's color buffer
  11031. if (successful) {
  11032. gl.clear(gl.COLOR_BUFFER_BIT);
  11033. successful = successful && (gl.getError() === gl.NO_ERROR);
  11034. }
  11035. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  11036. if (successful) {
  11037. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  11038. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11039. var readFormat = gl.RGBA;
  11040. var readType = gl.UNSIGNED_BYTE;
  11041. var buffer = new Uint8Array(4);
  11042. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  11043. successful = successful && (gl.getError() === gl.NO_ERROR);
  11044. }
  11045. //clean up
  11046. gl.deleteTexture(texture);
  11047. gl.deleteFramebuffer(fb);
  11048. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  11049. //clear accumulated errors
  11050. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  11051. return successful;
  11052. };
  11053. Engine.prototype._getWebGLTextureType = function (type) {
  11054. if (type === Engine.TEXTURETYPE_FLOAT) {
  11055. return this._gl.FLOAT;
  11056. }
  11057. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11058. // Add Half Float Constant.
  11059. return this._gl.HALF_FLOAT_OES;
  11060. }
  11061. return this._gl.UNSIGNED_BYTE;
  11062. };
  11063. ;
  11064. Engine.prototype._getRGBABufferInternalSizedFormat = function (type) {
  11065. if (this._webGLVersion === 1) {
  11066. return this._gl.RGBA;
  11067. }
  11068. if (type === Engine.TEXTURETYPE_FLOAT) {
  11069. return this._gl.RGBA32F;
  11070. }
  11071. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  11072. return this._gl.RGBA16F;
  11073. }
  11074. return this._gl.RGBA;
  11075. };
  11076. ;
  11077. Engine.prototype.createQuery = function () {
  11078. return this._gl.createQuery();
  11079. };
  11080. Engine.prototype.deleteQuery = function (query) {
  11081. this._gl.deleteQuery(query);
  11082. return this;
  11083. };
  11084. Engine.prototype.isQueryResultAvailable = function (query) {
  11085. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  11086. };
  11087. Engine.prototype.getQueryResult = function (query) {
  11088. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  11089. };
  11090. Engine.prototype.beginQuery = function (algorithmType, query) {
  11091. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11092. this._gl.beginQuery(glAlgorithm, query);
  11093. };
  11094. Engine.prototype.endQuery = function (algorithmType) {
  11095. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  11096. this._gl.endQuery(glAlgorithm);
  11097. return this;
  11098. };
  11099. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  11100. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  11101. };
  11102. // Statics
  11103. Engine.isSupported = function () {
  11104. try {
  11105. // Avoid creating an unsized context for CocoonJS, since size determined on first creation. Is not resizable
  11106. if (navigator.isCocoonJS) {
  11107. return true;
  11108. }
  11109. var tempcanvas = document.createElement("canvas");
  11110. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  11111. return gl != null && !!window.WebGLRenderingContext;
  11112. }
  11113. catch (e) {
  11114. return false;
  11115. }
  11116. };
  11117. Engine.Instances = new Array();
  11118. // Const statics
  11119. Engine._ALPHA_DISABLE = 0;
  11120. Engine._ALPHA_ADD = 1;
  11121. Engine._ALPHA_COMBINE = 2;
  11122. Engine._ALPHA_SUBTRACT = 3;
  11123. Engine._ALPHA_MULTIPLY = 4;
  11124. Engine._ALPHA_MAXIMIZED = 5;
  11125. Engine._ALPHA_ONEONE = 6;
  11126. Engine._ALPHA_PREMULTIPLIED = 7;
  11127. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  11128. Engine._ALPHA_INTERPOLATE = 9;
  11129. Engine._ALPHA_SCREENMODE = 10;
  11130. Engine._DELAYLOADSTATE_NONE = 0;
  11131. Engine._DELAYLOADSTATE_LOADED = 1;
  11132. Engine._DELAYLOADSTATE_LOADING = 2;
  11133. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  11134. Engine._TEXTUREFORMAT_ALPHA = 0;
  11135. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  11136. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  11137. Engine._TEXTUREFORMAT_RGB = 4;
  11138. Engine._TEXTUREFORMAT_RGBA = 5;
  11139. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  11140. Engine._TEXTURETYPE_FLOAT = 1;
  11141. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  11142. // Depht or Stencil test Constants.
  11143. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  11144. 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.
  11145. 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.
  11146. 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.
  11147. 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.
  11148. 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.
  11149. 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.
  11150. 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.
  11151. // Stencil Actions Constants.
  11152. Engine._KEEP = 0x1E00;
  11153. Engine._REPLACE = 0x1E01;
  11154. Engine._INCR = 0x1E02;
  11155. Engine._DECR = 0x1E03;
  11156. Engine._INVERT = 0x150A;
  11157. Engine._INCR_WRAP = 0x8507;
  11158. Engine._DECR_WRAP = 0x8508;
  11159. // Texture rescaling mode
  11160. Engine._SCALEMODE_FLOOR = 1;
  11161. Engine._SCALEMODE_NEAREST = 2;
  11162. Engine._SCALEMODE_CEILING = 3;
  11163. // Updatable statics so stick with vars here
  11164. Engine.CollisionsEpsilon = 0.001;
  11165. Engine.CodeRepository = "src/";
  11166. Engine.ShadersRepository = "src/Shaders/";
  11167. return Engine;
  11168. }());
  11169. BABYLON.Engine = Engine;
  11170. })(BABYLON || (BABYLON = {}));
  11171. //# sourceMappingURL=babylon.engine.js.map
  11172. /// <reference path="Tools\babylon.decorators.ts" />
  11173. var BABYLON;
  11174. (function (BABYLON) {
  11175. /**
  11176. * Node is the basic class for all scene objects (Mesh, Light Camera).
  11177. */
  11178. var Node = (function () {
  11179. /**
  11180. * @constructor
  11181. * @param {string} name - the name and id to be given to this node
  11182. * @param {BABYLON.Scene} the scene this node will be added to
  11183. */
  11184. function Node(name, scene) {
  11185. this.state = "";
  11186. this.metadata = null;
  11187. this.doNotSerialize = false;
  11188. this.animations = new Array();
  11189. this._ranges = {};
  11190. this._childrenFlag = -1;
  11191. this._isEnabled = true;
  11192. this._isReady = true;
  11193. this._currentRenderId = -1;
  11194. this._parentRenderId = -1;
  11195. /**
  11196. * An event triggered when the mesh is disposed.
  11197. * @type {BABYLON.Observable}
  11198. */
  11199. this.onDisposeObservable = new BABYLON.Observable();
  11200. // Behaviors
  11201. this._behaviors = new Array();
  11202. this.name = name;
  11203. this.id = name;
  11204. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  11205. this._initCache();
  11206. }
  11207. Object.defineProperty(Node.prototype, "parent", {
  11208. get: function () {
  11209. return this._parentNode;
  11210. },
  11211. set: function (parent) {
  11212. if (this._parentNode === parent) {
  11213. return;
  11214. }
  11215. if (this._parentNode) {
  11216. var index = this._parentNode._children.indexOf(this);
  11217. if (index !== -1) {
  11218. this._parentNode._children.splice(index, 1);
  11219. }
  11220. }
  11221. this._parentNode = parent;
  11222. if (this._parentNode) {
  11223. if (!this._parentNode._children) {
  11224. this._parentNode._children = new Array();
  11225. }
  11226. this._parentNode._children.push(this);
  11227. }
  11228. },
  11229. enumerable: true,
  11230. configurable: true
  11231. });
  11232. Node.prototype.getClassName = function () {
  11233. return "Node";
  11234. };
  11235. Object.defineProperty(Node.prototype, "onDispose", {
  11236. set: function (callback) {
  11237. if (this._onDisposeObserver) {
  11238. this.onDisposeObservable.remove(this._onDisposeObserver);
  11239. }
  11240. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  11241. },
  11242. enumerable: true,
  11243. configurable: true
  11244. });
  11245. Node.prototype.getScene = function () {
  11246. return this._scene;
  11247. };
  11248. Node.prototype.getEngine = function () {
  11249. return this._scene.getEngine();
  11250. };
  11251. Node.prototype.addBehavior = function (behavior) {
  11252. var index = this._behaviors.indexOf(behavior);
  11253. if (index !== -1) {
  11254. return;
  11255. }
  11256. behavior.attach(this);
  11257. this._behaviors.push(behavior);
  11258. return this;
  11259. };
  11260. Node.prototype.removeBehavior = function (behavior) {
  11261. var index = this._behaviors.indexOf(behavior);
  11262. if (index === -1) {
  11263. return;
  11264. }
  11265. this._behaviors[index].detach();
  11266. this._behaviors.splice(index, 1);
  11267. return this;
  11268. };
  11269. Object.defineProperty(Node.prototype, "behaviors", {
  11270. get: function () {
  11271. return this._behaviors;
  11272. },
  11273. enumerable: true,
  11274. configurable: true
  11275. });
  11276. Node.prototype.getBehaviorByName = function (name) {
  11277. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11278. var behavior = _a[_i];
  11279. if (behavior.name === name) {
  11280. return behavior;
  11281. }
  11282. }
  11283. return null;
  11284. };
  11285. // override it in derived class
  11286. Node.prototype.getWorldMatrix = function () {
  11287. return BABYLON.Matrix.Identity();
  11288. };
  11289. // override it in derived class if you add new variables to the cache
  11290. // and call the parent class method
  11291. Node.prototype._initCache = function () {
  11292. this._cache = {};
  11293. this._cache.parent = undefined;
  11294. };
  11295. Node.prototype.updateCache = function (force) {
  11296. if (!force && this.isSynchronized())
  11297. return;
  11298. this._cache.parent = this.parent;
  11299. this._updateCache();
  11300. };
  11301. // override it in derived class if you add new variables to the cache
  11302. // and call the parent class method if !ignoreParentClass
  11303. Node.prototype._updateCache = function (ignoreParentClass) {
  11304. };
  11305. // override it in derived class if you add new variables to the cache
  11306. Node.prototype._isSynchronized = function () {
  11307. return true;
  11308. };
  11309. Node.prototype._markSyncedWithParent = function () {
  11310. this._parentRenderId = this.parent._currentRenderId;
  11311. };
  11312. Node.prototype.isSynchronizedWithParent = function () {
  11313. if (!this.parent) {
  11314. return true;
  11315. }
  11316. if (this._parentRenderId !== this.parent._currentRenderId) {
  11317. return false;
  11318. }
  11319. return this.parent.isSynchronized();
  11320. };
  11321. Node.prototype.isSynchronized = function (updateCache) {
  11322. var check = this.hasNewParent();
  11323. check = check || !this.isSynchronizedWithParent();
  11324. check = check || !this._isSynchronized();
  11325. if (updateCache)
  11326. this.updateCache(true);
  11327. return !check;
  11328. };
  11329. Node.prototype.hasNewParent = function (update) {
  11330. if (this._cache.parent === this.parent)
  11331. return false;
  11332. if (update)
  11333. this._cache.parent = this.parent;
  11334. return true;
  11335. };
  11336. /**
  11337. * Is this node ready to be used/rendered
  11338. * @return {boolean} is it ready
  11339. */
  11340. Node.prototype.isReady = function () {
  11341. return this._isReady;
  11342. };
  11343. /**
  11344. * Is this node enabled.
  11345. * If the node has a parent and is enabled, the parent will be inspected as well.
  11346. * @return {boolean} whether this node (and its parent) is enabled.
  11347. * @see setEnabled
  11348. */
  11349. Node.prototype.isEnabled = function () {
  11350. if (!this._isEnabled) {
  11351. return false;
  11352. }
  11353. if (this.parent) {
  11354. return this.parent.isEnabled();
  11355. }
  11356. return true;
  11357. };
  11358. /**
  11359. * Set the enabled state of this node.
  11360. * @param {boolean} value - the new enabled state
  11361. * @see isEnabled
  11362. */
  11363. Node.prototype.setEnabled = function (value) {
  11364. this._isEnabled = value;
  11365. };
  11366. /**
  11367. * Is this node a descendant of the given node.
  11368. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined.
  11369. * @param {BABYLON.Node} ancestor - The parent node to inspect
  11370. * @see parent
  11371. */
  11372. Node.prototype.isDescendantOf = function (ancestor) {
  11373. if (this.parent) {
  11374. if (this.parent === ancestor) {
  11375. return true;
  11376. }
  11377. return this.parent.isDescendantOf(ancestor);
  11378. }
  11379. return false;
  11380. };
  11381. /**
  11382. * Evaluate the list of children and determine if they should be considered as descendants considering the given criterias
  11383. * @param {BABYLON.Node[]} results the result array containing the nodes matching the given criterias
  11384. * @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.
  11385. * @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.
  11386. */
  11387. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  11388. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  11389. if (!this._children) {
  11390. return;
  11391. }
  11392. for (var index = 0; index < this._children.length; index++) {
  11393. var item = this._children[index];
  11394. if (!predicate || predicate(item)) {
  11395. results.push(item);
  11396. }
  11397. if (!directDescendantsOnly) {
  11398. item._getDescendants(results, false, predicate);
  11399. }
  11400. }
  11401. };
  11402. /**
  11403. * Will return all nodes that have this node as ascendant.
  11404. * @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.
  11405. * @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.
  11406. * @return {BABYLON.Node[]} all children nodes of all types.
  11407. */
  11408. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  11409. var results = [];
  11410. this._getDescendants(results, directDescendantsOnly, predicate);
  11411. return results;
  11412. };
  11413. /**
  11414. * Get all child-meshes of this node.
  11415. */
  11416. Node.prototype.getChildMeshes = function (directDecendantsOnly, predicate) {
  11417. var results = [];
  11418. this._getDescendants(results, directDecendantsOnly, function (node) {
  11419. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  11420. });
  11421. return results;
  11422. };
  11423. /**
  11424. * Get all direct children of this node.
  11425. */
  11426. Node.prototype.getChildren = function (predicate) {
  11427. return this.getDescendants(true, predicate);
  11428. };
  11429. Node.prototype._setReady = function (state) {
  11430. if (state === this._isReady) {
  11431. return;
  11432. }
  11433. if (!state) {
  11434. this._isReady = false;
  11435. return;
  11436. }
  11437. this._isReady = true;
  11438. if (this.onReady) {
  11439. this.onReady(this);
  11440. }
  11441. };
  11442. Node.prototype.getAnimationByName = function (name) {
  11443. for (var i = 0; i < this.animations.length; i++) {
  11444. var animation = this.animations[i];
  11445. if (animation.name === name) {
  11446. return animation;
  11447. }
  11448. }
  11449. return null;
  11450. };
  11451. Node.prototype.createAnimationRange = function (name, from, to) {
  11452. // check name not already in use
  11453. if (!this._ranges[name]) {
  11454. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  11455. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11456. if (this.animations[i]) {
  11457. this.animations[i].createRange(name, from, to);
  11458. }
  11459. }
  11460. }
  11461. };
  11462. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  11463. if (deleteFrames === void 0) { deleteFrames = true; }
  11464. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  11465. if (this.animations[i]) {
  11466. this.animations[i].deleteRange(name, deleteFrames);
  11467. }
  11468. }
  11469. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  11470. };
  11471. Node.prototype.getAnimationRange = function (name) {
  11472. return this._ranges[name];
  11473. };
  11474. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  11475. var range = this.getAnimationRange(name);
  11476. if (!range) {
  11477. return null;
  11478. }
  11479. this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  11480. };
  11481. Node.prototype.serializeAnimationRanges = function () {
  11482. var serializationRanges = [];
  11483. for (var name in this._ranges) {
  11484. var range = {};
  11485. range.name = name;
  11486. range.from = this._ranges[name].from;
  11487. range.to = this._ranges[name].to;
  11488. serializationRanges.push(range);
  11489. }
  11490. return serializationRanges;
  11491. };
  11492. Node.prototype.dispose = function () {
  11493. this.parent = null;
  11494. // Callback
  11495. this.onDisposeObservable.notifyObservers(this);
  11496. this.onDisposeObservable.clear();
  11497. // Behaviors
  11498. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  11499. var behavior = _a[_i];
  11500. behavior.detach();
  11501. }
  11502. this._behaviors = [];
  11503. };
  11504. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  11505. if (parsedNode.ranges) {
  11506. for (var index = 0; index < parsedNode.ranges.length; index++) {
  11507. var data = parsedNode.ranges[index];
  11508. node.createAnimationRange(data.name, data.from, data.to);
  11509. }
  11510. }
  11511. };
  11512. __decorate([
  11513. BABYLON.serialize()
  11514. ], Node.prototype, "name", void 0);
  11515. __decorate([
  11516. BABYLON.serialize()
  11517. ], Node.prototype, "id", void 0);
  11518. __decorate([
  11519. BABYLON.serialize()
  11520. ], Node.prototype, "uniqueId", void 0);
  11521. __decorate([
  11522. BABYLON.serialize()
  11523. ], Node.prototype, "state", void 0);
  11524. __decorate([
  11525. BABYLON.serialize()
  11526. ], Node.prototype, "metadata", void 0);
  11527. return Node;
  11528. }());
  11529. BABYLON.Node = Node;
  11530. })(BABYLON || (BABYLON = {}));
  11531. //# sourceMappingURL=babylon.node.js.map
  11532. var BABYLON;
  11533. (function (BABYLON) {
  11534. var BoundingSphere = (function () {
  11535. function BoundingSphere(minimum, maximum) {
  11536. this.minimum = minimum;
  11537. this.maximum = maximum;
  11538. this._tempRadiusVector = BABYLON.Vector3.Zero();
  11539. var distance = BABYLON.Vector3.Distance(minimum, maximum);
  11540. this.center = BABYLON.Vector3.Lerp(minimum, maximum, 0.5);
  11541. this.radius = distance * 0.5;
  11542. this.centerWorld = BABYLON.Vector3.Zero();
  11543. this._update(BABYLON.Matrix.Identity());
  11544. }
  11545. // Methods
  11546. BoundingSphere.prototype._update = function (world) {
  11547. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  11548. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  11549. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  11550. };
  11551. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  11552. for (var i = 0; i < 6; i++) {
  11553. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  11554. return false;
  11555. }
  11556. return true;
  11557. };
  11558. BoundingSphere.prototype.intersectsPoint = function (point) {
  11559. var x = this.centerWorld.x - point.x;
  11560. var y = this.centerWorld.y - point.y;
  11561. var z = this.centerWorld.z - point.z;
  11562. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11563. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  11564. return false;
  11565. return true;
  11566. };
  11567. // Statics
  11568. BoundingSphere.Intersects = function (sphere0, sphere1) {
  11569. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  11570. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  11571. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  11572. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  11573. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  11574. return false;
  11575. return true;
  11576. };
  11577. return BoundingSphere;
  11578. }());
  11579. BABYLON.BoundingSphere = BoundingSphere;
  11580. })(BABYLON || (BABYLON = {}));
  11581. //# sourceMappingURL=babylon.boundingSphere.js.map
  11582. var BABYLON;
  11583. (function (BABYLON) {
  11584. var BoundingBox = (function () {
  11585. function BoundingBox(minimum, maximum) {
  11586. this.minimum = minimum;
  11587. this.maximum = maximum;
  11588. this.vectors = new Array();
  11589. this.vectorsWorld = new Array();
  11590. // Bounding vectors
  11591. this.vectors.push(this.minimum.clone());
  11592. this.vectors.push(this.maximum.clone());
  11593. this.vectors.push(this.minimum.clone());
  11594. this.vectors[2].x = this.maximum.x;
  11595. this.vectors.push(this.minimum.clone());
  11596. this.vectors[3].y = this.maximum.y;
  11597. this.vectors.push(this.minimum.clone());
  11598. this.vectors[4].z = this.maximum.z;
  11599. this.vectors.push(this.maximum.clone());
  11600. this.vectors[5].z = this.minimum.z;
  11601. this.vectors.push(this.maximum.clone());
  11602. this.vectors[6].x = this.minimum.x;
  11603. this.vectors.push(this.maximum.clone());
  11604. this.vectors[7].y = this.minimum.y;
  11605. // OBB
  11606. this.center = this.maximum.add(this.minimum).scale(0.5);
  11607. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  11608. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  11609. // World
  11610. for (var index = 0; index < this.vectors.length; index++) {
  11611. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  11612. }
  11613. this.minimumWorld = BABYLON.Vector3.Zero();
  11614. this.maximumWorld = BABYLON.Vector3.Zero();
  11615. this.centerWorld = BABYLON.Vector3.Zero();
  11616. this.extendSizeWorld = BABYLON.Vector3.Zero();
  11617. this._update(BABYLON.Matrix.Identity());
  11618. }
  11619. // Methods
  11620. BoundingBox.prototype.getWorldMatrix = function () {
  11621. return this._worldMatrix;
  11622. };
  11623. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  11624. this._worldMatrix.copyFrom(matrix);
  11625. return this;
  11626. };
  11627. BoundingBox.prototype._update = function (world) {
  11628. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  11629. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  11630. for (var index = 0; index < this.vectors.length; index++) {
  11631. var v = this.vectorsWorld[index];
  11632. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  11633. if (v.x < this.minimumWorld.x)
  11634. this.minimumWorld.x = v.x;
  11635. if (v.y < this.minimumWorld.y)
  11636. this.minimumWorld.y = v.y;
  11637. if (v.z < this.minimumWorld.z)
  11638. this.minimumWorld.z = v.z;
  11639. if (v.x > this.maximumWorld.x)
  11640. this.maximumWorld.x = v.x;
  11641. if (v.y > this.maximumWorld.y)
  11642. this.maximumWorld.y = v.y;
  11643. if (v.z > this.maximumWorld.z)
  11644. this.maximumWorld.z = v.z;
  11645. }
  11646. // Extend
  11647. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  11648. this.extendSizeWorld.scaleInPlace(0.5);
  11649. // OBB
  11650. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  11651. this.centerWorld.scaleInPlace(0.5);
  11652. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  11653. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  11654. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  11655. this._worldMatrix = world;
  11656. };
  11657. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  11658. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  11659. };
  11660. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11661. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  11662. };
  11663. BoundingBox.prototype.intersectsPoint = function (point) {
  11664. var delta = -BABYLON.Epsilon;
  11665. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  11666. return false;
  11667. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  11668. return false;
  11669. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  11670. return false;
  11671. return true;
  11672. };
  11673. BoundingBox.prototype.intersectsSphere = function (sphere) {
  11674. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  11675. };
  11676. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  11677. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  11678. return false;
  11679. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  11680. return false;
  11681. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  11682. return false;
  11683. return true;
  11684. };
  11685. // Statics
  11686. BoundingBox.Intersects = function (box0, box1) {
  11687. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  11688. return false;
  11689. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  11690. return false;
  11691. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  11692. return false;
  11693. return true;
  11694. };
  11695. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  11696. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  11697. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  11698. return (num <= (sphereRadius * sphereRadius));
  11699. };
  11700. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  11701. for (var p = 0; p < 6; p++) {
  11702. for (var i = 0; i < 8; i++) {
  11703. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11704. return false;
  11705. }
  11706. }
  11707. }
  11708. return true;
  11709. };
  11710. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  11711. for (var p = 0; p < 6; p++) {
  11712. var inCount = 8;
  11713. for (var i = 0; i < 8; i++) {
  11714. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  11715. --inCount;
  11716. }
  11717. else {
  11718. break;
  11719. }
  11720. }
  11721. if (inCount === 0)
  11722. return false;
  11723. }
  11724. return true;
  11725. };
  11726. return BoundingBox;
  11727. }());
  11728. BABYLON.BoundingBox = BoundingBox;
  11729. })(BABYLON || (BABYLON = {}));
  11730. //# sourceMappingURL=babylon.boundingBox.js.map
  11731. var BABYLON;
  11732. (function (BABYLON) {
  11733. var computeBoxExtents = function (axis, box) {
  11734. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  11735. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  11736. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  11737. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  11738. var r = r0 + r1 + r2;
  11739. return {
  11740. min: p - r,
  11741. max: p + r
  11742. };
  11743. };
  11744. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  11745. var axisOverlap = function (axis, box0, box1) {
  11746. var result0 = computeBoxExtents(axis, box0);
  11747. var result1 = computeBoxExtents(axis, box1);
  11748. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  11749. };
  11750. var BoundingInfo = (function () {
  11751. function BoundingInfo(minimum, maximum) {
  11752. this.minimum = minimum;
  11753. this.maximum = maximum;
  11754. this._isLocked = false;
  11755. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  11756. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  11757. }
  11758. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  11759. get: function () {
  11760. return this._isLocked;
  11761. },
  11762. set: function (value) {
  11763. this._isLocked = value;
  11764. },
  11765. enumerable: true,
  11766. configurable: true
  11767. });
  11768. // Methods
  11769. BoundingInfo.prototype.update = function (world) {
  11770. if (this._isLocked) {
  11771. return;
  11772. }
  11773. this.boundingBox._update(world);
  11774. this.boundingSphere._update(world);
  11775. };
  11776. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  11777. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  11778. return false;
  11779. return this.boundingBox.isInFrustum(frustumPlanes);
  11780. };
  11781. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  11782. /**
  11783. * Gets the world distance between the min and max points of the bounding box
  11784. */
  11785. get: function () {
  11786. var boundingBox = this.boundingBox;
  11787. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  11788. return size.length();
  11789. },
  11790. enumerable: true,
  11791. configurable: true
  11792. });
  11793. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  11794. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  11795. };
  11796. BoundingInfo.prototype._checkCollision = function (collider) {
  11797. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  11798. };
  11799. BoundingInfo.prototype.intersectsPoint = function (point) {
  11800. if (!this.boundingSphere.centerWorld) {
  11801. return false;
  11802. }
  11803. if (!this.boundingSphere.intersectsPoint(point)) {
  11804. return false;
  11805. }
  11806. if (!this.boundingBox.intersectsPoint(point)) {
  11807. return false;
  11808. }
  11809. return true;
  11810. };
  11811. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  11812. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  11813. return false;
  11814. }
  11815. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  11816. return false;
  11817. }
  11818. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  11819. return false;
  11820. }
  11821. if (!precise) {
  11822. return true;
  11823. }
  11824. var box0 = this.boundingBox;
  11825. var box1 = boundingInfo.boundingBox;
  11826. if (!axisOverlap(box0.directions[0], box0, box1))
  11827. return false;
  11828. if (!axisOverlap(box0.directions[1], box0, box1))
  11829. return false;
  11830. if (!axisOverlap(box0.directions[2], box0, box1))
  11831. return false;
  11832. if (!axisOverlap(box1.directions[0], box0, box1))
  11833. return false;
  11834. if (!axisOverlap(box1.directions[1], box0, box1))
  11835. return false;
  11836. if (!axisOverlap(box1.directions[2], box0, box1))
  11837. return false;
  11838. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  11839. return false;
  11840. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  11841. return false;
  11842. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  11843. return false;
  11844. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  11845. return false;
  11846. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  11847. return false;
  11848. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  11849. return false;
  11850. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  11851. return false;
  11852. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  11853. return false;
  11854. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  11855. return false;
  11856. return true;
  11857. };
  11858. return BoundingInfo;
  11859. }());
  11860. BABYLON.BoundingInfo = BoundingInfo;
  11861. })(BABYLON || (BABYLON = {}));
  11862. //# sourceMappingURL=babylon.boundingInfo.js.map
  11863. var BABYLON;
  11864. (function (BABYLON) {
  11865. var AbstractMesh = (function (_super) {
  11866. __extends(AbstractMesh, _super);
  11867. // Constructor
  11868. function AbstractMesh(name, scene) {
  11869. var _this = _super.call(this, name, scene) || this;
  11870. _this._facetNb = 0; // facet number
  11871. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  11872. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  11873. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  11874. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  11875. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  11876. _this._subDiv = {
  11877. max: 1,
  11878. X: 1,
  11879. Y: 1,
  11880. Z: 1
  11881. };
  11882. // Events
  11883. /**
  11884. * An event triggered when this mesh collides with another one
  11885. * @type {BABYLON.Observable}
  11886. */
  11887. _this.onCollideObservable = new BABYLON.Observable();
  11888. /**
  11889. * An event triggered when the collision's position changes
  11890. * @type {BABYLON.Observable}
  11891. */
  11892. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  11893. /**
  11894. * An event triggered after the world matrix is updated
  11895. * @type {BABYLON.Observable}
  11896. */
  11897. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  11898. /**
  11899. * An event triggered when material is changed
  11900. * @type {BABYLON.Observable}
  11901. */
  11902. _this.onMaterialChangedObservable = new BABYLON.Observable();
  11903. // Properties
  11904. _this.definedFacingForward = true; // orientation for POV movement & rotation
  11905. _this.position = BABYLON.Vector3.Zero();
  11906. /**
  11907. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  11908. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  11909. * or
  11910. * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE (Default Value) which is mapped to GL_ANY_SAMPLES_PASSED_CONSERVATIVE which is a false positive algorithm that is faster than GL_ANY_SAMPLES_PASSED but less accurate.
  11911. * for more info check WebGl documentations
  11912. */
  11913. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  11914. /**
  11915. * This property is responsible for starting the occlusion query within the Mesh or not, this property is also used to determine what should happen when the occlusionRetryCount is reached. It has supports 3 values:
  11916. * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  11917. * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  11918. * OCCLUSION_TYPE_STRICT: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken restore the last state of the mesh occlusion if the mesh was visible then show the mesh if was hidden then hide don't show.
  11919. */
  11920. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  11921. /**
  11922. * This number indicates the number of allowed retries before stop the occlusion query, this is useful if the occlusion query is taking long time before to the query result is retireved, the query result indicates if the object is visible within the scene or not and based on that Babylon.Js engine decideds to show or hide the object.
  11923. * The default value is -1 which means don't break the query and wait till the result.
  11924. */
  11925. _this.occlusionRetryCount = -1;
  11926. _this._occlusionInternalRetryCounter = 0;
  11927. _this._isOccluded = false;
  11928. _this._isOcclusionQueryInProgress = false;
  11929. _this._rotation = BABYLON.Vector3.Zero();
  11930. _this._scaling = BABYLON.Vector3.One();
  11931. _this.billboardMode = AbstractMesh.BILLBOARDMODE_NONE;
  11932. _this.visibility = 1.0;
  11933. _this.alphaIndex = Number.MAX_VALUE;
  11934. _this.infiniteDistance = false;
  11935. _this.isVisible = true;
  11936. _this.isPickable = true;
  11937. _this.showBoundingBox = false;
  11938. _this.showSubMeshesBoundingBox = false;
  11939. _this.isBlocker = false;
  11940. _this.enablePointerMoveEvents = false;
  11941. _this.renderingGroupId = 0;
  11942. _this._receiveShadows = false;
  11943. _this.renderOutline = false;
  11944. _this.outlineColor = BABYLON.Color3.Red();
  11945. _this.outlineWidth = 0.02;
  11946. _this.renderOverlay = false;
  11947. _this.overlayColor = BABYLON.Color3.Red();
  11948. _this.overlayAlpha = 0.5;
  11949. _this._hasVertexAlpha = false;
  11950. _this._useVertexColors = true;
  11951. _this._computeBonesUsingShaders = true;
  11952. _this._numBoneInfluencers = 4;
  11953. _this._applyFog = true;
  11954. _this.scalingDeterminant = 1;
  11955. _this.useOctreeForRenderingSelection = true;
  11956. _this.useOctreeForPicking = true;
  11957. _this.useOctreeForCollisions = true;
  11958. _this._layerMask = 0x0FFFFFFF;
  11959. /**
  11960. * True if the mesh must be rendered in any case.
  11961. */
  11962. _this.alwaysSelectAsActiveMesh = false;
  11963. // Collisions
  11964. _this._checkCollisions = false;
  11965. _this._collisionMask = -1;
  11966. _this._collisionGroup = -1;
  11967. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  11968. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  11969. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11970. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11971. _this._newPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  11972. // Edges
  11973. _this.edgesWidth = 1;
  11974. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  11975. // Cache
  11976. _this._localWorld = BABYLON.Matrix.Zero();
  11977. _this._worldMatrix = BABYLON.Matrix.Zero();
  11978. _this._absolutePosition = BABYLON.Vector3.Zero();
  11979. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  11980. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  11981. _this._isDirty = false;
  11982. _this._pivotMatrix = BABYLON.Matrix.Identity();
  11983. _this._isDisposed = false;
  11984. _this._renderId = 0;
  11985. _this._intersectionsInProgress = new Array();
  11986. _this._isWorldMatrixFrozen = false;
  11987. _this._unIndexed = false;
  11988. _this._lightSources = new Array();
  11989. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  11990. if (collidedMesh === void 0) { collidedMesh = null; }
  11991. //TODO move this to the collision coordinator!
  11992. if (_this.getScene().workerCollisions)
  11993. newPosition.multiplyInPlace(_this._collider.radius);
  11994. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  11995. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  11996. _this.position.addInPlace(_this._diffPositionForCollisions);
  11997. }
  11998. if (collidedMesh) {
  11999. _this.onCollideObservable.notifyObservers(collidedMesh);
  12000. }
  12001. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  12002. };
  12003. _this.getScene().addMesh(_this);
  12004. _this._resyncLightSources();
  12005. return _this;
  12006. }
  12007. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  12008. get: function () {
  12009. return AbstractMesh._BILLBOARDMODE_NONE;
  12010. },
  12011. enumerable: true,
  12012. configurable: true
  12013. });
  12014. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  12015. get: function () {
  12016. return AbstractMesh._BILLBOARDMODE_X;
  12017. },
  12018. enumerable: true,
  12019. configurable: true
  12020. });
  12021. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  12022. get: function () {
  12023. return AbstractMesh._BILLBOARDMODE_Y;
  12024. },
  12025. enumerable: true,
  12026. configurable: true
  12027. });
  12028. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  12029. get: function () {
  12030. return AbstractMesh._BILLBOARDMODE_Z;
  12031. },
  12032. enumerable: true,
  12033. configurable: true
  12034. });
  12035. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  12036. get: function () {
  12037. return AbstractMesh._BILLBOARDMODE_ALL;
  12038. },
  12039. enumerable: true,
  12040. configurable: true
  12041. });
  12042. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  12043. /**
  12044. * Read-only : the number of facets in the mesh
  12045. */
  12046. get: function () {
  12047. return this._facetNb;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  12053. /**
  12054. * The number (integer) of subdivisions per axis in the partioning space
  12055. */
  12056. get: function () {
  12057. return this._partitioningSubdivisions;
  12058. },
  12059. set: function (nb) {
  12060. this._partitioningSubdivisions = nb;
  12061. },
  12062. enumerable: true,
  12063. configurable: true
  12064. });
  12065. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  12066. /**
  12067. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  12068. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box.
  12069. */
  12070. get: function () {
  12071. return this._partitioningBBoxRatio;
  12072. },
  12073. set: function (ratio) {
  12074. this._partitioningBBoxRatio = ratio;
  12075. },
  12076. enumerable: true,
  12077. configurable: true
  12078. });
  12079. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  12080. /**
  12081. * Read-only boolean : is the feature facetData enabled ?
  12082. */
  12083. get: function () {
  12084. return this._facetDataEnabled;
  12085. },
  12086. enumerable: true,
  12087. configurable: true
  12088. });
  12089. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  12090. set: function (callback) {
  12091. if (this._onCollideObserver) {
  12092. this.onCollideObservable.remove(this._onCollideObserver);
  12093. }
  12094. this._onCollideObserver = this.onCollideObservable.add(callback);
  12095. },
  12096. enumerable: true,
  12097. configurable: true
  12098. });
  12099. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  12100. set: function (callback) {
  12101. if (this._onCollisionPositionChangeObserver) {
  12102. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  12103. }
  12104. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  12105. },
  12106. enumerable: true,
  12107. configurable: true
  12108. });
  12109. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  12110. /**
  12111. * Property isOccluded : Gets or sets whether the mesh is occluded or not, it is used also to set the intial state of the mesh to be occluded or not.
  12112. */
  12113. get: function () {
  12114. return this._isOccluded;
  12115. },
  12116. set: function (value) {
  12117. this._isOccluded = value;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  12123. /**
  12124. * Flag to check the progress status of the query
  12125. */
  12126. get: function () {
  12127. return this._isOcclusionQueryInProgress;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(AbstractMesh.prototype, "material", {
  12133. get: function () {
  12134. return this._material;
  12135. },
  12136. set: function (value) {
  12137. if (this._material === value) {
  12138. return;
  12139. }
  12140. this._material = value;
  12141. if (this.onMaterialChangedObservable.hasObservers) {
  12142. this.onMaterialChangedObservable.notifyObservers(this);
  12143. }
  12144. if (!this.subMeshes) {
  12145. return;
  12146. }
  12147. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12148. var subMesh = _a[_i];
  12149. subMesh.setEffect(null);
  12150. }
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  12156. get: function () {
  12157. return this._receiveShadows;
  12158. },
  12159. set: function (value) {
  12160. if (this._receiveShadows === value) {
  12161. return;
  12162. }
  12163. this._receiveShadows = value;
  12164. this._markSubMeshesAsLightDirty();
  12165. },
  12166. enumerable: true,
  12167. configurable: true
  12168. });
  12169. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  12170. get: function () {
  12171. return this._hasVertexAlpha;
  12172. },
  12173. set: function (value) {
  12174. if (this._hasVertexAlpha === value) {
  12175. return;
  12176. }
  12177. this._hasVertexAlpha = value;
  12178. this._markSubMeshesAsAttributesDirty();
  12179. },
  12180. enumerable: true,
  12181. configurable: true
  12182. });
  12183. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  12184. get: function () {
  12185. return this._useVertexColors;
  12186. },
  12187. set: function (value) {
  12188. if (this._useVertexColors === value) {
  12189. return;
  12190. }
  12191. this._useVertexColors = value;
  12192. this._markSubMeshesAsAttributesDirty();
  12193. },
  12194. enumerable: true,
  12195. configurable: true
  12196. });
  12197. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  12198. get: function () {
  12199. return this._computeBonesUsingShaders;
  12200. },
  12201. set: function (value) {
  12202. if (this._computeBonesUsingShaders === value) {
  12203. return;
  12204. }
  12205. this._computeBonesUsingShaders = value;
  12206. this._markSubMeshesAsAttributesDirty();
  12207. },
  12208. enumerable: true,
  12209. configurable: true
  12210. });
  12211. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  12212. get: function () {
  12213. return this._numBoneInfluencers;
  12214. },
  12215. set: function (value) {
  12216. if (this._numBoneInfluencers === value) {
  12217. return;
  12218. }
  12219. this._numBoneInfluencers = value;
  12220. this._markSubMeshesAsAttributesDirty();
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  12226. get: function () {
  12227. return this._applyFog;
  12228. },
  12229. set: function (value) {
  12230. if (this._applyFog === value) {
  12231. return;
  12232. }
  12233. this._applyFog = value;
  12234. this._markSubMeshesAsMiscDirty();
  12235. },
  12236. enumerable: true,
  12237. configurable: true
  12238. });
  12239. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  12240. get: function () {
  12241. return this._layerMask;
  12242. },
  12243. set: function (value) {
  12244. if (value === this._layerMask) {
  12245. return;
  12246. }
  12247. this._layerMask = value;
  12248. this._resyncLightSources();
  12249. },
  12250. enumerable: true,
  12251. configurable: true
  12252. });
  12253. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  12254. get: function () {
  12255. return this._collisionMask;
  12256. },
  12257. set: function (mask) {
  12258. this._collisionMask = !isNaN(mask) ? mask : -1;
  12259. },
  12260. enumerable: true,
  12261. configurable: true
  12262. });
  12263. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  12264. get: function () {
  12265. return this._collisionGroup;
  12266. },
  12267. set: function (mask) {
  12268. this._collisionGroup = !isNaN(mask) ? mask : -1;
  12269. },
  12270. enumerable: true,
  12271. configurable: true
  12272. });
  12273. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  12274. get: function () {
  12275. return null;
  12276. },
  12277. enumerable: true,
  12278. configurable: true
  12279. });
  12280. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  12281. get: function () {
  12282. return this._skeleton;
  12283. },
  12284. set: function (value) {
  12285. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  12286. this._skeleton._unregisterMeshWithPoseMatrix(this);
  12287. }
  12288. if (value && value.needInitialSkinMatrix) {
  12289. value._registerMeshWithPoseMatrix(this);
  12290. }
  12291. this._skeleton = value;
  12292. if (!this._skeleton) {
  12293. this._bonesTransformMatrices = null;
  12294. }
  12295. this._markSubMeshesAsAttributesDirty();
  12296. },
  12297. enumerable: true,
  12298. configurable: true
  12299. });
  12300. /**
  12301. * Boolean : true if the mesh has been disposed.
  12302. */
  12303. AbstractMesh.prototype.isDisposed = function () {
  12304. return this._isDisposed;
  12305. };
  12306. /**
  12307. * Returns the string "AbstractMesh"
  12308. */
  12309. AbstractMesh.prototype.getClassName = function () {
  12310. return "AbstractMesh";
  12311. };
  12312. /**
  12313. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  12314. */
  12315. AbstractMesh.prototype.toString = function (fullDetails) {
  12316. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  12317. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  12318. if (this._skeleton) {
  12319. ret += ", skeleton: " + this._skeleton.name;
  12320. }
  12321. if (fullDetails) {
  12322. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  12323. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  12324. }
  12325. return ret;
  12326. };
  12327. AbstractMesh.prototype._rebuild = function () {
  12328. if (this._occlusionQuery) {
  12329. this._occlusionQuery = null;
  12330. }
  12331. if (!this.subMeshes) {
  12332. return;
  12333. }
  12334. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12335. var subMesh = _a[_i];
  12336. subMesh._rebuild();
  12337. }
  12338. };
  12339. AbstractMesh.prototype._resyncLightSources = function () {
  12340. this._lightSources.length = 0;
  12341. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  12342. var light = _a[_i];
  12343. if (!light.isEnabled()) {
  12344. continue;
  12345. }
  12346. if (light.canAffectMesh(this)) {
  12347. this._lightSources.push(light);
  12348. }
  12349. }
  12350. this._markSubMeshesAsLightDirty();
  12351. };
  12352. AbstractMesh.prototype._resyncLighSource = function (light) {
  12353. var isIn = light.isEnabled() && light.canAffectMesh(this);
  12354. var index = this._lightSources.indexOf(light);
  12355. if (index === -1) {
  12356. if (!isIn) {
  12357. return;
  12358. }
  12359. this._lightSources.push(light);
  12360. }
  12361. else {
  12362. if (isIn) {
  12363. return;
  12364. }
  12365. this._lightSources.splice(index, 1);
  12366. }
  12367. this._markSubMeshesAsLightDirty();
  12368. };
  12369. AbstractMesh.prototype._removeLightSource = function (light) {
  12370. var index = this._lightSources.indexOf(light);
  12371. if (index === -1) {
  12372. return;
  12373. }
  12374. this._lightSources.splice(index, 1);
  12375. };
  12376. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  12377. if (!this.subMeshes) {
  12378. return;
  12379. }
  12380. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12381. var subMesh = _a[_i];
  12382. if (subMesh._materialDefines) {
  12383. func(subMesh._materialDefines);
  12384. }
  12385. }
  12386. };
  12387. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  12388. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  12389. };
  12390. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  12391. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  12392. };
  12393. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  12394. if (!this.subMeshes) {
  12395. return;
  12396. }
  12397. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  12398. var subMesh = _a[_i];
  12399. var material = subMesh.getMaterial();
  12400. if (material) {
  12401. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  12402. }
  12403. }
  12404. };
  12405. Object.defineProperty(AbstractMesh.prototype, "rotation", {
  12406. /**
  12407. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  12408. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  12409. * Default : (0.0, 0.0, 0.0)
  12410. */
  12411. get: function () {
  12412. return this._rotation;
  12413. },
  12414. set: function (newRotation) {
  12415. this._rotation = newRotation;
  12416. },
  12417. enumerable: true,
  12418. configurable: true
  12419. });
  12420. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  12421. /**
  12422. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  12423. * Default : (1.0, 1.0, 1.0)
  12424. */
  12425. get: function () {
  12426. return this._scaling;
  12427. },
  12428. set: function (newScaling) {
  12429. this._scaling = newScaling;
  12430. if (this.physicsImpostor) {
  12431. this.physicsImpostor.forceUpdate();
  12432. }
  12433. },
  12434. enumerable: true,
  12435. configurable: true
  12436. });
  12437. Object.defineProperty(AbstractMesh.prototype, "rotationQuaternion", {
  12438. /**
  12439. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  12440. * It's null by default.
  12441. * If set, only the rotationQuaternion is then used to compute the mesh rotation and its property `.rotation\ is then ignored and set to (0.0, 0.0, 0.0)
  12442. */
  12443. get: function () {
  12444. return this._rotationQuaternion;
  12445. },
  12446. set: function (quaternion) {
  12447. this._rotationQuaternion = quaternion;
  12448. //reset the rotation vector.
  12449. if (quaternion && this.rotation.length()) {
  12450. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  12451. }
  12452. },
  12453. enumerable: true,
  12454. configurable: true
  12455. });
  12456. // Methods
  12457. /**
  12458. * Copies the paramater passed Matrix into the mesh Pose matrix.
  12459. * Returns the AbstractMesh.
  12460. */
  12461. AbstractMesh.prototype.updatePoseMatrix = function (matrix) {
  12462. this._poseMatrix.copyFrom(matrix);
  12463. return this;
  12464. };
  12465. /**
  12466. * Returns the mesh Pose matrix.
  12467. * Returned object : Matrix
  12468. */
  12469. AbstractMesh.prototype.getPoseMatrix = function () {
  12470. return this._poseMatrix;
  12471. };
  12472. /**
  12473. * Disables the mesh edger rendering mode.
  12474. * Returns the AbstractMesh.
  12475. */
  12476. AbstractMesh.prototype.disableEdgesRendering = function () {
  12477. if (this._edgesRenderer !== undefined) {
  12478. this._edgesRenderer.dispose();
  12479. this._edgesRenderer = undefined;
  12480. }
  12481. return this;
  12482. };
  12483. /**
  12484. * Enables the edge rendering mode on the mesh.
  12485. * This mode makes the mesh edges visible.
  12486. * Returns the AbstractMesh.
  12487. */
  12488. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  12489. if (epsilon === void 0) { epsilon = 0.95; }
  12490. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  12491. this.disableEdgesRendering();
  12492. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  12493. return this;
  12494. };
  12495. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  12496. /**
  12497. * Returns true if the mesh is blocked. Used by the class Mesh.
  12498. * Returns the boolean `false` by default.
  12499. */
  12500. get: function () {
  12501. return false;
  12502. },
  12503. enumerable: true,
  12504. configurable: true
  12505. });
  12506. /**
  12507. * Returns the mesh itself by default, used by the class Mesh.
  12508. * Returned type : AbstractMesh
  12509. */
  12510. AbstractMesh.prototype.getLOD = function (camera) {
  12511. return this;
  12512. };
  12513. /**
  12514. * Returns 0 by default, used by the class Mesh.
  12515. * Returns an integer.
  12516. */
  12517. AbstractMesh.prototype.getTotalVertices = function () {
  12518. return 0;
  12519. };
  12520. /**
  12521. * Returns null by default, used by the class Mesh.
  12522. * Returned type : integer array
  12523. */
  12524. AbstractMesh.prototype.getIndices = function () {
  12525. return null;
  12526. };
  12527. /**
  12528. * Returns the array of the requested vertex data kind. Used by the class Mesh. Returns null here.
  12529. * Returned type : float array or Float32Array
  12530. */
  12531. AbstractMesh.prototype.getVerticesData = function (kind) {
  12532. return null;
  12533. };
  12534. /**
  12535. * Sets the vertex data of the mesh geometry for the requested `kind`.
  12536. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  12537. * The `data` are either a numeric array either a Float32Array.
  12538. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  12539. * 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).
  12540. * Note that a new underlying VertexBuffer object is created each call.
  12541. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  12542. *
  12543. * Possible `kind` values :
  12544. * - BABYLON.VertexBuffer.PositionKind
  12545. * - BABYLON.VertexBuffer.UVKind
  12546. * - BABYLON.VertexBuffer.UV2Kind
  12547. * - BABYLON.VertexBuffer.UV3Kind
  12548. * - BABYLON.VertexBuffer.UV4Kind
  12549. * - BABYLON.VertexBuffer.UV5Kind
  12550. * - BABYLON.VertexBuffer.UV6Kind
  12551. * - BABYLON.VertexBuffer.ColorKind
  12552. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12553. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12554. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12555. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12556. *
  12557. * Returns the Mesh.
  12558. */
  12559. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  12560. return null;
  12561. };
  12562. /**
  12563. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  12564. * If the mesh has no geometry, it is simply returned as it is.
  12565. * The `data` are either a numeric array either a Float32Array.
  12566. * No new underlying VertexBuffer object is created.
  12567. * 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.
  12568. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  12569. *
  12570. * Possible `kind` values :
  12571. * - BABYLON.VertexBuffer.PositionKind
  12572. * - BABYLON.VertexBuffer.UVKind
  12573. * - BABYLON.VertexBuffer.UV2Kind
  12574. * - BABYLON.VertexBuffer.UV3Kind
  12575. * - BABYLON.VertexBuffer.UV4Kind
  12576. * - BABYLON.VertexBuffer.UV5Kind
  12577. * - BABYLON.VertexBuffer.UV6Kind
  12578. * - BABYLON.VertexBuffer.ColorKind
  12579. * - BABYLON.VertexBuffer.MatricesIndicesKind
  12580. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  12581. * - BABYLON.VertexBuffer.MatricesWeightsKind
  12582. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  12583. *
  12584. * Returns the Mesh.
  12585. */
  12586. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  12587. return null;
  12588. };
  12589. /**
  12590. * Sets the mesh indices.
  12591. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  12592. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  12593. * This method creates a new index buffer each call.
  12594. * Returns the Mesh.
  12595. */
  12596. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  12597. return null;
  12598. };
  12599. /** Returns false by default, used by the class Mesh.
  12600. * Returns a boolean
  12601. */
  12602. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  12603. return false;
  12604. };
  12605. /**
  12606. * Returns the mesh BoundingInfo object or creates a new one and returns it if undefined.
  12607. * Returns a BoundingInfo
  12608. */
  12609. AbstractMesh.prototype.getBoundingInfo = function () {
  12610. if (this._masterMesh) {
  12611. return this._masterMesh.getBoundingInfo();
  12612. }
  12613. if (!this._boundingInfo) {
  12614. this._updateBoundingInfo();
  12615. }
  12616. return this._boundingInfo;
  12617. };
  12618. /**
  12619. * Sets a mesh new object BoundingInfo.
  12620. * Returns the AbstractMesh.
  12621. */
  12622. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  12623. this._boundingInfo = boundingInfo;
  12624. return this;
  12625. };
  12626. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  12627. get: function () {
  12628. return this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind);
  12629. },
  12630. enumerable: true,
  12631. configurable: true
  12632. });
  12633. AbstractMesh.prototype._preActivate = function () {
  12634. };
  12635. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  12636. };
  12637. AbstractMesh.prototype._activate = function (renderId) {
  12638. this._renderId = renderId;
  12639. };
  12640. /**
  12641. * Returns the last update of the World matrix
  12642. * Returns a Matrix.
  12643. */
  12644. AbstractMesh.prototype.getWorldMatrix = function () {
  12645. if (this._masterMesh) {
  12646. return this._masterMesh.getWorldMatrix();
  12647. }
  12648. if (this._currentRenderId !== this.getScene().getRenderId() || !this.isSynchronized()) {
  12649. this.computeWorldMatrix();
  12650. }
  12651. return this._worldMatrix;
  12652. };
  12653. Object.defineProperty(AbstractMesh.prototype, "worldMatrixFromCache", {
  12654. /**
  12655. * Returns directly the last state of the mesh World matrix.
  12656. * A Matrix is returned.
  12657. */
  12658. get: function () {
  12659. return this._worldMatrix;
  12660. },
  12661. enumerable: true,
  12662. configurable: true
  12663. });
  12664. Object.defineProperty(AbstractMesh.prototype, "absolutePosition", {
  12665. /**
  12666. * Returns the current mesh absolute position.
  12667. * Retuns a Vector3.
  12668. */
  12669. get: function () {
  12670. return this._absolutePosition;
  12671. },
  12672. enumerable: true,
  12673. configurable: true
  12674. });
  12675. /**
  12676. * Prevents the World matrix to be computed any longer.
  12677. * Returns the AbstractMesh.
  12678. */
  12679. AbstractMesh.prototype.freezeWorldMatrix = function () {
  12680. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  12681. this.computeWorldMatrix(true);
  12682. this._isWorldMatrixFrozen = true;
  12683. return this;
  12684. };
  12685. /**
  12686. * Allows back the World matrix computation.
  12687. * Returns the AbstractMesh.
  12688. */
  12689. AbstractMesh.prototype.unfreezeWorldMatrix = function () {
  12690. this._isWorldMatrixFrozen = false;
  12691. this.computeWorldMatrix(true);
  12692. return this;
  12693. };
  12694. Object.defineProperty(AbstractMesh.prototype, "isWorldMatrixFrozen", {
  12695. /**
  12696. * True if the World matrix has been frozen.
  12697. * Returns a boolean.
  12698. */
  12699. get: function () {
  12700. return this._isWorldMatrixFrozen;
  12701. },
  12702. enumerable: true,
  12703. configurable: true
  12704. });
  12705. /**
  12706. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  12707. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12708. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12709. * The passed axis is also normalized.
  12710. * Returns the AbstractMesh.
  12711. */
  12712. AbstractMesh.prototype.rotate = function (axis, amount, space) {
  12713. axis.normalize();
  12714. if (!this.rotationQuaternion) {
  12715. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12716. this.rotation = BABYLON.Vector3.Zero();
  12717. }
  12718. var rotationQuaternion;
  12719. if (!space || space === BABYLON.Space.LOCAL) {
  12720. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12721. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  12722. }
  12723. else {
  12724. if (this.parent) {
  12725. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12726. invertParentWorldMatrix.invert();
  12727. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  12728. }
  12729. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, AbstractMesh._rotationAxisCache);
  12730. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12731. }
  12732. return this;
  12733. };
  12734. /**
  12735. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  12736. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  12737. * The passed axis is also normalized.
  12738. * Returns the AbstractMesh.
  12739. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  12740. */
  12741. AbstractMesh.prototype.rotateAround = function (point, axis, amount) {
  12742. axis.normalize();
  12743. if (!this.rotationQuaternion) {
  12744. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12745. this.rotation.copyFromFloats(0, 0, 0);
  12746. }
  12747. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  12748. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  12749. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  12750. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  12751. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  12752. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  12753. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  12754. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  12755. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  12756. return this;
  12757. };
  12758. /**
  12759. * Translates the mesh along the axis vector for the passed distance in the given space.
  12760. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  12761. * Returns the AbstractMesh.
  12762. */
  12763. AbstractMesh.prototype.translate = function (axis, distance, space) {
  12764. var displacementVector = axis.scale(distance);
  12765. if (!space || space === BABYLON.Space.LOCAL) {
  12766. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  12767. this.setPositionWithLocalVector(tempV3);
  12768. }
  12769. else {
  12770. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  12771. }
  12772. return this;
  12773. };
  12774. /**
  12775. * Adds a rotation step to the mesh current rotation.
  12776. * x, y, z are Euler angles expressed in radians.
  12777. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  12778. * This means this rotation is made in the mesh local space only.
  12779. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  12780. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  12781. * ```javascript
  12782. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  12783. * ```
  12784. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  12785. * Under the hood, only quaternions are used. So it's a little faster is you use .rotationQuaternion because it doesn't need to translate them back to Euler angles.
  12786. * Returns the AbstractMesh.
  12787. */
  12788. AbstractMesh.prototype.addRotation = function (x, y, z) {
  12789. var rotationQuaternion;
  12790. if (this.rotationQuaternion) {
  12791. rotationQuaternion = this.rotationQuaternion;
  12792. }
  12793. else {
  12794. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  12795. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  12796. }
  12797. var accumulation = BABYLON.Tmp.Quaternion[0];
  12798. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  12799. rotationQuaternion.multiplyInPlace(accumulation);
  12800. if (!this.rotationQuaternion) {
  12801. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  12802. }
  12803. return this;
  12804. };
  12805. /**
  12806. * Retuns the mesh absolute position in the World.
  12807. * Returns a Vector3.
  12808. */
  12809. AbstractMesh.prototype.getAbsolutePosition = function () {
  12810. this.computeWorldMatrix();
  12811. return this._absolutePosition;
  12812. };
  12813. /**
  12814. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  12815. * Returns the AbstractMesh.
  12816. */
  12817. AbstractMesh.prototype.setAbsolutePosition = function (absolutePosition) {
  12818. if (!absolutePosition) {
  12819. return;
  12820. }
  12821. var absolutePositionX;
  12822. var absolutePositionY;
  12823. var absolutePositionZ;
  12824. if (absolutePosition.x === undefined) {
  12825. if (arguments.length < 3) {
  12826. return;
  12827. }
  12828. absolutePositionX = arguments[0];
  12829. absolutePositionY = arguments[1];
  12830. absolutePositionZ = arguments[2];
  12831. }
  12832. else {
  12833. absolutePositionX = absolutePosition.x;
  12834. absolutePositionY = absolutePosition.y;
  12835. absolutePositionZ = absolutePosition.z;
  12836. }
  12837. if (this.parent) {
  12838. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  12839. invertParentWorldMatrix.invert();
  12840. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  12841. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  12842. }
  12843. else {
  12844. this.position.x = absolutePositionX;
  12845. this.position.y = absolutePositionY;
  12846. this.position.z = absolutePositionZ;
  12847. }
  12848. return this;
  12849. };
  12850. // ================================== Point of View Movement =================================
  12851. /**
  12852. * Perform relative position change from the point of view of behind the front of the mesh.
  12853. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12854. * Supports definition of mesh facing forward or backward.
  12855. * @param {number} amountRight
  12856. * @param {number} amountUp
  12857. * @param {number} amountForward
  12858. *
  12859. * Returns the AbstractMesh.
  12860. */
  12861. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  12862. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  12863. return this;
  12864. };
  12865. /**
  12866. * Calculate relative position change from the point of view of behind the front of the mesh.
  12867. * This is performed taking into account the meshes current rotation, so you do not have to care.
  12868. * Supports definition of mesh facing forward or backward.
  12869. * @param {number} amountRight
  12870. * @param {number} amountUp
  12871. * @param {number} amountForward
  12872. *
  12873. * Returns a new Vector3.
  12874. */
  12875. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  12876. var rotMatrix = new BABYLON.Matrix();
  12877. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  12878. rotQuaternion.toRotationMatrix(rotMatrix);
  12879. var translationDelta = BABYLON.Vector3.Zero();
  12880. var defForwardMult = this.definedFacingForward ? -1 : 1;
  12881. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  12882. return translationDelta;
  12883. };
  12884. // ================================== Point of View Rotation =================================
  12885. /**
  12886. * Perform relative rotation change from the point of view of behind the front of the mesh.
  12887. * Supports definition of mesh facing forward or backward.
  12888. * @param {number} flipBack
  12889. * @param {number} twirlClockwise
  12890. * @param {number} tiltRight
  12891. *
  12892. * Returns the AbstractMesh.
  12893. */
  12894. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12895. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  12896. return this;
  12897. };
  12898. /**
  12899. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  12900. * Supports definition of mesh facing forward or backward.
  12901. * @param {number} flipBack
  12902. * @param {number} twirlClockwise
  12903. * @param {number} tiltRight
  12904. *
  12905. * Returns a new Vector3.
  12906. */
  12907. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  12908. var defForwardMult = this.definedFacingForward ? 1 : -1;
  12909. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  12910. };
  12911. /**
  12912. * Sets a new pivot matrix to the mesh.
  12913. * Returns the AbstractMesh.
  12914. */
  12915. AbstractMesh.prototype.setPivotMatrix = function (matrix) {
  12916. this._pivotMatrix = matrix;
  12917. this._cache.pivotMatrixUpdated = true;
  12918. return this;
  12919. };
  12920. /**
  12921. * Returns the mesh pivot matrix.
  12922. * Default : Identity.
  12923. * A Matrix is returned.
  12924. */
  12925. AbstractMesh.prototype.getPivotMatrix = function () {
  12926. return this._pivotMatrix;
  12927. };
  12928. AbstractMesh.prototype._isSynchronized = function () {
  12929. if (this._isDirty) {
  12930. return false;
  12931. }
  12932. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE)
  12933. return false;
  12934. if (this._cache.pivotMatrixUpdated) {
  12935. return false;
  12936. }
  12937. if (this.infiniteDistance) {
  12938. return false;
  12939. }
  12940. if (!this._cache.position.equals(this.position))
  12941. return false;
  12942. if (this.rotationQuaternion) {
  12943. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  12944. return false;
  12945. }
  12946. if (!this._cache.rotation.equals(this.rotation))
  12947. return false;
  12948. if (!this._cache.scaling.equals(this.scaling))
  12949. return false;
  12950. return true;
  12951. };
  12952. AbstractMesh.prototype._initCache = function () {
  12953. _super.prototype._initCache.call(this);
  12954. this._cache.localMatrixUpdated = false;
  12955. this._cache.position = BABYLON.Vector3.Zero();
  12956. this._cache.scaling = BABYLON.Vector3.Zero();
  12957. this._cache.rotation = BABYLON.Vector3.Zero();
  12958. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  12959. this._cache.billboardMode = -1;
  12960. };
  12961. AbstractMesh.prototype.markAsDirty = function (property) {
  12962. if (property === "rotation") {
  12963. this.rotationQuaternion = null;
  12964. }
  12965. this._currentRenderId = Number.MAX_VALUE;
  12966. this._isDirty = true;
  12967. return this;
  12968. };
  12969. /**
  12970. * Updates the mesh BoundingInfo object and all its children BoundingInfo objects also.
  12971. * Returns the AbstractMesh.
  12972. */
  12973. AbstractMesh.prototype._updateBoundingInfo = function () {
  12974. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  12975. this._boundingInfo.update(this.worldMatrixFromCache);
  12976. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  12977. return this;
  12978. };
  12979. /**
  12980. * Update a mesh's children BoundingInfo objects only.
  12981. * Returns the AbstractMesh.
  12982. */
  12983. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  12984. if (!this.subMeshes) {
  12985. return;
  12986. }
  12987. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  12988. var subMesh = this.subMeshes[subIndex];
  12989. if (!subMesh.IsGlobal) {
  12990. subMesh.updateBoundingInfo(matrix);
  12991. }
  12992. }
  12993. return this;
  12994. };
  12995. /**
  12996. * Computes the mesh World matrix and returns it.
  12997. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  12998. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  12999. * If the parameter `force`is set to `true`, the actual computation is done.
  13000. * Returns the mesh World Matrix.
  13001. */
  13002. AbstractMesh.prototype.computeWorldMatrix = function (force) {
  13003. if (this._isWorldMatrixFrozen) {
  13004. return this._worldMatrix;
  13005. }
  13006. if (!force && this.isSynchronized(true)) {
  13007. this._currentRenderId = this.getScene().getRenderId();
  13008. return this._worldMatrix;
  13009. }
  13010. this._cache.position.copyFrom(this.position);
  13011. this._cache.scaling.copyFrom(this.scaling);
  13012. this._cache.pivotMatrixUpdated = false;
  13013. this._cache.billboardMode = this.billboardMode;
  13014. this._currentRenderId = this.getScene().getRenderId();
  13015. this._isDirty = false;
  13016. // Scaling
  13017. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  13018. // Rotation
  13019. //rotate, if quaternion is set and rotation was used
  13020. if (this.rotationQuaternion) {
  13021. var len = this.rotation.length();
  13022. if (len) {
  13023. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  13024. this.rotation.copyFromFloats(0, 0, 0);
  13025. }
  13026. }
  13027. if (this.rotationQuaternion) {
  13028. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  13029. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  13030. }
  13031. else {
  13032. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  13033. this._cache.rotation.copyFrom(this.rotation);
  13034. }
  13035. // Translation
  13036. if (this.infiniteDistance && !this.parent) {
  13037. var camera = this.getScene().activeCamera;
  13038. if (camera) {
  13039. var cameraWorldMatrix = camera.getWorldMatrix();
  13040. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  13041. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  13042. }
  13043. }
  13044. else {
  13045. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  13046. }
  13047. // Composing transformations
  13048. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  13049. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13050. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  13051. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE && this.getScene().activeCamera) {
  13052. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_ALL) !== AbstractMesh.BILLBOARDMODE_ALL) {
  13053. // Need to decompose each rotation here
  13054. var currentPosition = BABYLON.Tmp.Vector3[3];
  13055. if (this.parent && this.parent.getWorldMatrix) {
  13056. if (this._meshToBoneReferal) {
  13057. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13058. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  13059. }
  13060. else {
  13061. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  13062. }
  13063. }
  13064. else {
  13065. currentPosition.copyFrom(this.position);
  13066. }
  13067. currentPosition.subtractInPlace(this.getScene().activeCamera.globalPosition);
  13068. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  13069. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_X) === AbstractMesh.BILLBOARDMODE_X) {
  13070. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  13071. }
  13072. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Y) === AbstractMesh.BILLBOARDMODE_Y) {
  13073. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  13074. }
  13075. if ((this.billboardMode & AbstractMesh.BILLBOARDMODE_Z) === AbstractMesh.BILLBOARDMODE_Z) {
  13076. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  13077. }
  13078. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  13079. }
  13080. else {
  13081. BABYLON.Tmp.Matrix[1].copyFrom(this.getScene().activeCamera.getViewMatrix());
  13082. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  13083. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  13084. }
  13085. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  13086. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  13087. }
  13088. // Local world
  13089. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  13090. // Parent
  13091. if (this.parent && this.parent.getWorldMatrix) {
  13092. if (this.billboardMode !== AbstractMesh.BILLBOARDMODE_NONE) {
  13093. if (this._meshToBoneReferal) {
  13094. this.parent.getWorldMatrix().multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13095. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  13096. }
  13097. else {
  13098. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  13099. }
  13100. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  13101. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  13102. this._worldMatrix.copyFrom(this._localWorld);
  13103. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  13104. }
  13105. else {
  13106. if (this._meshToBoneReferal) {
  13107. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  13108. BABYLON.Tmp.Matrix[6].multiplyToRef(this._meshToBoneReferal.getWorldMatrix(), this._worldMatrix);
  13109. }
  13110. else {
  13111. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  13112. }
  13113. }
  13114. this._markSyncedWithParent();
  13115. }
  13116. else {
  13117. this._worldMatrix.copyFrom(this._localWorld);
  13118. }
  13119. // Bounding info
  13120. this._updateBoundingInfo();
  13121. // Absolute position
  13122. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  13123. // Callbacks
  13124. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  13125. if (!this._poseMatrix) {
  13126. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  13127. }
  13128. return this._worldMatrix;
  13129. };
  13130. /**
  13131. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  13132. * @param func: callback function to add
  13133. *
  13134. * Returns the AbstractMesh.
  13135. */
  13136. AbstractMesh.prototype.registerAfterWorldMatrixUpdate = function (func) {
  13137. this.onAfterWorldMatrixUpdateObservable.add(func);
  13138. return this;
  13139. };
  13140. /**
  13141. * Removes a registered callback function.
  13142. * Returns the AbstractMesh.
  13143. */
  13144. AbstractMesh.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  13145. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  13146. return this;
  13147. };
  13148. /**
  13149. * Sets the mesh position in its local space.
  13150. * Returns the AbstractMesh.
  13151. */
  13152. AbstractMesh.prototype.setPositionWithLocalVector = function (vector3) {
  13153. this.computeWorldMatrix();
  13154. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  13155. return this;
  13156. };
  13157. /**
  13158. * Returns the mesh position in the local space from the current World matrix values.
  13159. * Returns a new Vector3.
  13160. */
  13161. AbstractMesh.prototype.getPositionExpressedInLocalSpace = function () {
  13162. this.computeWorldMatrix();
  13163. var invLocalWorldMatrix = this._localWorld.clone();
  13164. invLocalWorldMatrix.invert();
  13165. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  13166. };
  13167. /**
  13168. * Translates the mesh along the passed Vector3 in its local space.
  13169. * Returns the AbstractMesh.
  13170. */
  13171. AbstractMesh.prototype.locallyTranslate = function (vector3) {
  13172. this.computeWorldMatrix(true);
  13173. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  13174. return this;
  13175. };
  13176. AbstractMesh.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  13177. /// <summary>Orients a mesh towards a target point. Mesh must be drawn facing user.</summary>
  13178. /// <param name="targetPoint" type="Vector3">The position (must be in same space as current mesh) to look at</param>
  13179. /// <param name="yawCor" type="Number">optional yaw (y-axis) correction in radians</param>
  13180. /// <param name="pitchCor" type="Number">optional pitch (x-axis) correction in radians</param>
  13181. /// <param name="rollCor" type="Number">optional roll (z-axis) correction in radians</param>
  13182. /// <returns>Mesh oriented towards targetMesh</returns>
  13183. if (yawCor === void 0) { yawCor = 0; }
  13184. if (pitchCor === void 0) { pitchCor = 0; }
  13185. if (rollCor === void 0) { rollCor = 0; }
  13186. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13187. var dv = AbstractMesh._lookAtVectorCache;
  13188. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  13189. targetPoint.subtractToRef(pos, dv);
  13190. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  13191. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  13192. var pitch = Math.atan2(dv.y, len);
  13193. this.rotationQuaternion = this.rotationQuaternion || new BABYLON.Quaternion();
  13194. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  13195. return this;
  13196. };
  13197. AbstractMesh.prototype.attachToBone = function (bone, affectedMesh) {
  13198. this._meshToBoneReferal = affectedMesh;
  13199. this.parent = bone;
  13200. if (bone.getWorldMatrix().determinant() < 0) {
  13201. this.scalingDeterminant *= -1;
  13202. }
  13203. return this;
  13204. };
  13205. AbstractMesh.prototype.detachFromBone = function () {
  13206. if (this.parent.getWorldMatrix().determinant() < 0) {
  13207. this.scalingDeterminant *= -1;
  13208. }
  13209. this._meshToBoneReferal = null;
  13210. this.parent = null;
  13211. return this;
  13212. };
  13213. /**
  13214. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  13215. * A mesh is in the frustum if its bounding box intersects the frustum.
  13216. * Boolean returned.
  13217. */
  13218. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  13219. return this._boundingInfo.isInFrustum(frustumPlanes);
  13220. };
  13221. /**
  13222. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  13223. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  13224. * Boolean returned.
  13225. */
  13226. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  13227. return this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  13228. ;
  13229. };
  13230. /**
  13231. * True if the mesh intersects another mesh or a SolidParticle object.
  13232. * Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  13233. * Returns a boolean.
  13234. */
  13235. AbstractMesh.prototype.intersectsMesh = function (mesh, precise) {
  13236. if (!this._boundingInfo || !mesh._boundingInfo) {
  13237. return false;
  13238. }
  13239. return this._boundingInfo.intersects(mesh._boundingInfo, precise);
  13240. };
  13241. /**
  13242. * Returns true if the passed point (Vector3) is inside the mesh bounding box.
  13243. * Returns a boolean.
  13244. */
  13245. AbstractMesh.prototype.intersectsPoint = function (point) {
  13246. if (!this._boundingInfo) {
  13247. return false;
  13248. }
  13249. return this._boundingInfo.intersectsPoint(point);
  13250. };
  13251. AbstractMesh.prototype.getPhysicsImpostor = function () {
  13252. return this.physicsImpostor;
  13253. };
  13254. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  13255. if (!camera) {
  13256. camera = this.getScene().activeCamera;
  13257. }
  13258. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  13259. };
  13260. /**
  13261. * Returns the distance from the mesh to the active camera.
  13262. * Returns a float.
  13263. */
  13264. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  13265. if (!camera) {
  13266. camera = this.getScene().activeCamera;
  13267. }
  13268. return this.absolutePosition.subtract(camera.position).length();
  13269. };
  13270. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  13271. if (!this.physicsImpostor) {
  13272. return;
  13273. }
  13274. this.physicsImpostor.applyImpulse(force, contactPoint);
  13275. return this;
  13276. };
  13277. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  13278. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  13279. return;
  13280. }
  13281. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  13282. mainPivot: pivot1,
  13283. connectedPivot: pivot2,
  13284. nativeParams: options
  13285. });
  13286. return this;
  13287. };
  13288. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  13289. // Collisions
  13290. /**
  13291. * Property checkCollisions : Boolean, whether the camera should check the collisions against the mesh.
  13292. * Default `false`.
  13293. */
  13294. get: function () {
  13295. return this._checkCollisions;
  13296. },
  13297. set: function (collisionEnabled) {
  13298. this._checkCollisions = collisionEnabled;
  13299. if (this.getScene().workerCollisions) {
  13300. this.getScene().collisionCoordinator.onMeshUpdated(this);
  13301. }
  13302. },
  13303. enumerable: true,
  13304. configurable: true
  13305. });
  13306. AbstractMesh.prototype.moveWithCollisions = function (direction) {
  13307. var globalPosition = this.getAbsolutePosition();
  13308. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPositionForCollisions);
  13309. this._oldPositionForCollisions.addInPlace(this.ellipsoidOffset);
  13310. if (!this._collider) {
  13311. this._collider = new BABYLON.Collider();
  13312. }
  13313. this._collider.radius = this.ellipsoid;
  13314. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, direction, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  13315. return this;
  13316. };
  13317. // Submeshes octree
  13318. /**
  13319. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  13320. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree.
  13321. * Returns an Octree of submeshes.
  13322. */
  13323. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  13324. if (maxCapacity === void 0) { maxCapacity = 64; }
  13325. if (maxDepth === void 0) { maxDepth = 2; }
  13326. if (!this._submeshesOctree) {
  13327. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  13328. }
  13329. this.computeWorldMatrix(true);
  13330. // Update octree
  13331. var bbox = this.getBoundingInfo().boundingBox;
  13332. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  13333. return this._submeshesOctree;
  13334. };
  13335. // Collisions
  13336. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  13337. this._generatePointsArray();
  13338. // Transformation
  13339. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  13340. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  13341. subMesh._lastColliderWorldVertices = [];
  13342. subMesh._trianglePlanes = [];
  13343. var start = subMesh.verticesStart;
  13344. var end = (subMesh.verticesStart + subMesh.verticesCount);
  13345. for (var i = start; i < end; i++) {
  13346. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  13347. }
  13348. }
  13349. // Collide
  13350. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  13351. if (collider.collisionFound) {
  13352. collider.collidedMesh = this;
  13353. }
  13354. return this;
  13355. };
  13356. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  13357. var subMeshes;
  13358. var len;
  13359. // Octrees
  13360. if (this._submeshesOctree && this.useOctreeForCollisions) {
  13361. var radius = collider.velocityWorldLength + Math.max(collider.radius.x, collider.radius.y, collider.radius.z);
  13362. var intersections = this._submeshesOctree.intersects(collider.basePointWorld, radius);
  13363. len = intersections.length;
  13364. subMeshes = intersections.data;
  13365. }
  13366. else {
  13367. subMeshes = this.subMeshes;
  13368. len = subMeshes.length;
  13369. }
  13370. for (var index = 0; index < len; index++) {
  13371. var subMesh = subMeshes[index];
  13372. // Bounding test
  13373. if (len > 1 && !subMesh._checkCollision(collider))
  13374. continue;
  13375. this._collideForSubMesh(subMesh, transformMatrix, collider);
  13376. }
  13377. return this;
  13378. };
  13379. AbstractMesh.prototype._checkCollision = function (collider) {
  13380. // Bounding box test
  13381. if (!this._boundingInfo._checkCollision(collider))
  13382. return this;
  13383. // Transformation matrix
  13384. BABYLON.Matrix.ScalingToRef(1.0 / collider.radius.x, 1.0 / collider.radius.y, 1.0 / collider.radius.z, this._collisionsScalingMatrix);
  13385. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  13386. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  13387. return this;
  13388. };
  13389. // Picking
  13390. AbstractMesh.prototype._generatePointsArray = function () {
  13391. return false;
  13392. };
  13393. /**
  13394. * Checks if the passed Ray intersects with the mesh.
  13395. * Returns an object PickingInfo.
  13396. */
  13397. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  13398. var pickingInfo = new BABYLON.PickingInfo();
  13399. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  13400. return pickingInfo;
  13401. }
  13402. if (!this._generatePointsArray()) {
  13403. return pickingInfo;
  13404. }
  13405. var intersectInfo = null;
  13406. // Octrees
  13407. var subMeshes;
  13408. var len;
  13409. if (this._submeshesOctree && this.useOctreeForPicking) {
  13410. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  13411. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  13412. len = intersections.length;
  13413. subMeshes = intersections.data;
  13414. }
  13415. else {
  13416. subMeshes = this.subMeshes;
  13417. len = subMeshes.length;
  13418. }
  13419. for (var index = 0; index < len; index++) {
  13420. var subMesh = subMeshes[index];
  13421. // Bounding test
  13422. if (len > 1 && !subMesh.canIntersects(ray))
  13423. continue;
  13424. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  13425. if (currentIntersectInfo) {
  13426. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  13427. intersectInfo = currentIntersectInfo;
  13428. intersectInfo.subMeshId = index;
  13429. if (fastCheck) {
  13430. break;
  13431. }
  13432. }
  13433. }
  13434. }
  13435. if (intersectInfo) {
  13436. // Get picked point
  13437. var world = this.getWorldMatrix();
  13438. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  13439. var direction = ray.direction.clone();
  13440. direction = direction.scale(intersectInfo.distance);
  13441. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  13442. var pickedPoint = worldOrigin.add(worldDirection);
  13443. // Return result
  13444. pickingInfo.hit = true;
  13445. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  13446. pickingInfo.pickedPoint = pickedPoint;
  13447. pickingInfo.pickedMesh = this;
  13448. pickingInfo.bu = intersectInfo.bu;
  13449. pickingInfo.bv = intersectInfo.bv;
  13450. pickingInfo.faceId = intersectInfo.faceId;
  13451. pickingInfo.subMeshId = intersectInfo.subMeshId;
  13452. return pickingInfo;
  13453. }
  13454. return pickingInfo;
  13455. };
  13456. /**
  13457. * Clones the mesh, used by the class Mesh.
  13458. * Just returns `null` for an AbstractMesh.
  13459. */
  13460. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  13461. return null;
  13462. };
  13463. /**
  13464. * Disposes all the mesh submeshes.
  13465. * Returns the AbstractMesh.
  13466. */
  13467. AbstractMesh.prototype.releaseSubMeshes = function () {
  13468. if (this.subMeshes) {
  13469. while (this.subMeshes.length) {
  13470. this.subMeshes[0].dispose();
  13471. }
  13472. }
  13473. else {
  13474. this.subMeshes = new Array();
  13475. }
  13476. return this;
  13477. };
  13478. /**
  13479. * Disposes the AbstractMesh.
  13480. * Some internal references are kept for further use.
  13481. * By default, all the mesh children are also disposed unless the parameter `doNotRecurse` is set to `true`.
  13482. * Returns nothing.
  13483. */
  13484. AbstractMesh.prototype.dispose = function (doNotRecurse) {
  13485. var _this = this;
  13486. var index;
  13487. // Action manager
  13488. if (this.actionManager) {
  13489. this.actionManager.dispose();
  13490. this.actionManager = null;
  13491. }
  13492. // Skeleton
  13493. this.skeleton = null;
  13494. // Animations
  13495. this.getScene().stopAnimation(this);
  13496. // Physics
  13497. if (this.physicsImpostor) {
  13498. this.physicsImpostor.dispose();
  13499. }
  13500. // Intersections in progress
  13501. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  13502. var other = this._intersectionsInProgress[index];
  13503. var pos = other._intersectionsInProgress.indexOf(this);
  13504. other._intersectionsInProgress.splice(pos, 1);
  13505. }
  13506. this._intersectionsInProgress = [];
  13507. // Lights
  13508. var lights = this.getScene().lights;
  13509. lights.forEach(function (light) {
  13510. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  13511. if (meshIndex !== -1) {
  13512. light.includedOnlyMeshes.splice(meshIndex, 1);
  13513. }
  13514. meshIndex = light.excludedMeshes.indexOf(_this);
  13515. if (meshIndex !== -1) {
  13516. light.excludedMeshes.splice(meshIndex, 1);
  13517. }
  13518. // Shadow generators
  13519. var generator = light.getShadowGenerator();
  13520. if (generator) {
  13521. var shadowMap = generator.getShadowMap();
  13522. meshIndex = shadowMap.renderList.indexOf(_this);
  13523. if (meshIndex !== -1) {
  13524. shadowMap.renderList.splice(meshIndex, 1);
  13525. }
  13526. }
  13527. });
  13528. // Edges
  13529. if (this._edgesRenderer) {
  13530. this._edgesRenderer.dispose();
  13531. this._edgesRenderer = null;
  13532. }
  13533. // SubMeshes
  13534. if (this.getClassName() !== "InstancedMesh") {
  13535. this.releaseSubMeshes();
  13536. }
  13537. // Octree
  13538. var sceneOctree = this.getScene().selectionOctree;
  13539. if (sceneOctree) {
  13540. var index = sceneOctree.dynamicContent.indexOf(this);
  13541. if (index !== -1) {
  13542. sceneOctree.dynamicContent.splice(index, 1);
  13543. }
  13544. }
  13545. // Query
  13546. var engine = this.getScene().getEngine();
  13547. if (this._occlusionQuery) {
  13548. this._isOcclusionQueryInProgress = false;
  13549. engine.deleteQuery(this._occlusionQuery);
  13550. this._occlusionQuery = null;
  13551. }
  13552. // Engine
  13553. engine.wipeCaches();
  13554. // Remove from scene
  13555. this.getScene().removeMesh(this);
  13556. if (!doNotRecurse) {
  13557. // Particles
  13558. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  13559. if (this.getScene().particleSystems[index].emitter === this) {
  13560. this.getScene().particleSystems[index].dispose();
  13561. index--;
  13562. }
  13563. }
  13564. // Children
  13565. var objects = this.getDescendants(true);
  13566. for (index = 0; index < objects.length; index++) {
  13567. objects[index].dispose();
  13568. }
  13569. }
  13570. else {
  13571. var childMeshes = this.getChildMeshes(true);
  13572. for (index = 0; index < childMeshes.length; index++) {
  13573. var child = childMeshes[index];
  13574. child.parent = null;
  13575. child.computeWorldMatrix(true);
  13576. }
  13577. }
  13578. // facet data
  13579. if (this._facetDataEnabled) {
  13580. this.disableFacetData();
  13581. }
  13582. this.onAfterWorldMatrixUpdateObservable.clear();
  13583. this.onCollideObservable.clear();
  13584. this.onCollisionPositionChangeObservable.clear();
  13585. this._isDisposed = true;
  13586. _super.prototype.dispose.call(this);
  13587. };
  13588. /**
  13589. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  13590. * This Vector3 is expressed in the World space.
  13591. */
  13592. AbstractMesh.prototype.getDirection = function (localAxis) {
  13593. var result = BABYLON.Vector3.Zero();
  13594. this.getDirectionToRef(localAxis, result);
  13595. return result;
  13596. };
  13597. /**
  13598. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  13599. * localAxis is expressed in the mesh local space.
  13600. * result is computed in the Wordl space from the mesh World matrix.
  13601. * Returns the AbstractMesh.
  13602. */
  13603. AbstractMesh.prototype.getDirectionToRef = function (localAxis, result) {
  13604. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  13605. return this;
  13606. };
  13607. AbstractMesh.prototype.setPivotPoint = function (point, space) {
  13608. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  13609. if (this.getScene().getRenderId() == 0) {
  13610. this.computeWorldMatrix(true);
  13611. }
  13612. var wm = this.getWorldMatrix();
  13613. if (space == BABYLON.Space.WORLD) {
  13614. var tmat = BABYLON.Tmp.Matrix[0];
  13615. wm.invertToRef(tmat);
  13616. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  13617. }
  13618. BABYLON.Vector3.TransformCoordinatesToRef(point, wm, this.position);
  13619. this._pivotMatrix.m[12] = -point.x;
  13620. this._pivotMatrix.m[13] = -point.y;
  13621. this._pivotMatrix.m[14] = -point.z;
  13622. this._cache.pivotMatrixUpdated = true;
  13623. return this;
  13624. };
  13625. /**
  13626. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  13627. */
  13628. AbstractMesh.prototype.getPivotPoint = function () {
  13629. var point = BABYLON.Vector3.Zero();
  13630. this.getPivotPointToRef(point);
  13631. return point;
  13632. };
  13633. /**
  13634. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  13635. * Returns the AbstractMesh.
  13636. */
  13637. AbstractMesh.prototype.getPivotPointToRef = function (result) {
  13638. result.x = -this._pivotMatrix.m[12];
  13639. result.y = -this._pivotMatrix.m[13];
  13640. result.z = -this._pivotMatrix.m[14];
  13641. return this;
  13642. };
  13643. /**
  13644. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  13645. */
  13646. AbstractMesh.prototype.getAbsolutePivotPoint = function () {
  13647. var point = BABYLON.Vector3.Zero();
  13648. this.getAbsolutePivotPointToRef(point);
  13649. return point;
  13650. };
  13651. /**
  13652. * Defines the passed mesh as the parent of the current mesh.
  13653. * Returns the AbstractMesh.
  13654. */
  13655. AbstractMesh.prototype.setParent = function (mesh) {
  13656. var child = this;
  13657. var parent = mesh;
  13658. if (mesh == null) {
  13659. var rotation = BABYLON.Tmp.Quaternion[0];
  13660. var position = BABYLON.Tmp.Vector3[0];
  13661. var scale = BABYLON.Tmp.Vector3[1];
  13662. child.getWorldMatrix().decompose(scale, rotation, position);
  13663. if (child.rotationQuaternion) {
  13664. child.rotationQuaternion.copyFrom(rotation);
  13665. }
  13666. else {
  13667. rotation.toEulerAnglesToRef(child.rotation);
  13668. }
  13669. child.position.x = position.x;
  13670. child.position.y = position.y;
  13671. child.position.z = position.z;
  13672. }
  13673. else {
  13674. var rotation = BABYLON.Tmp.Quaternion[0];
  13675. var position = BABYLON.Tmp.Vector3[0];
  13676. var scale = BABYLON.Tmp.Vector3[1];
  13677. var m1 = BABYLON.Tmp.Matrix[0];
  13678. var m2 = BABYLON.Tmp.Matrix[1];
  13679. parent.getWorldMatrix().decompose(scale, rotation, position);
  13680. rotation.toRotationMatrix(m1);
  13681. m2.setTranslation(position);
  13682. m2.multiplyToRef(m1, m1);
  13683. var invParentMatrix = BABYLON.Matrix.Invert(m1);
  13684. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13685. m.decompose(scale, rotation, position);
  13686. if (child.rotationQuaternion) {
  13687. child.rotationQuaternion.copyFrom(rotation);
  13688. }
  13689. else {
  13690. rotation.toEulerAnglesToRef(child.rotation);
  13691. }
  13692. invParentMatrix = BABYLON.Matrix.Invert(parent.getWorldMatrix());
  13693. var m = child.getWorldMatrix().multiply(invParentMatrix);
  13694. m.decompose(scale, rotation, position);
  13695. child.position.x = position.x;
  13696. child.position.y = position.y;
  13697. child.position.z = position.z;
  13698. }
  13699. child.parent = parent;
  13700. return this;
  13701. };
  13702. /**
  13703. * Adds the passed mesh as a child to the current mesh.
  13704. * Returns the AbstractMesh.
  13705. */
  13706. AbstractMesh.prototype.addChild = function (mesh) {
  13707. mesh.setParent(this);
  13708. return this;
  13709. };
  13710. /**
  13711. * Removes the passed mesh from the current mesh children list.
  13712. * Returns the AbstractMesh.
  13713. */
  13714. AbstractMesh.prototype.removeChild = function (mesh) {
  13715. mesh.setParent(null);
  13716. return this;
  13717. };
  13718. /**
  13719. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  13720. * Returns the AbstractMesh.
  13721. */
  13722. AbstractMesh.prototype.getAbsolutePivotPointToRef = function (result) {
  13723. result.x = this._pivotMatrix.m[12];
  13724. result.y = this._pivotMatrix.m[13];
  13725. result.z = this._pivotMatrix.m[14];
  13726. this.getPivotPointToRef(result);
  13727. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  13728. return this;
  13729. };
  13730. // Facet data
  13731. /**
  13732. * Initialize the facet data arrays : facetNormals, facetPositions and facetPartitioning.
  13733. * Returns the AbstractMesh.
  13734. */
  13735. AbstractMesh.prototype._initFacetData = function () {
  13736. if (!this._facetNormals) {
  13737. this._facetNormals = new Array();
  13738. }
  13739. if (!this._facetPositions) {
  13740. this._facetPositions = new Array();
  13741. }
  13742. if (!this._facetPartitioning) {
  13743. this._facetPartitioning = new Array();
  13744. }
  13745. this._facetNb = this.getIndices().length / 3;
  13746. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  13747. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  13748. for (var f = 0; f < this._facetNb; f++) {
  13749. this._facetNormals[f] = BABYLON.Vector3.Zero();
  13750. this._facetPositions[f] = BABYLON.Vector3.Zero();
  13751. }
  13752. this._facetDataEnabled = true;
  13753. return this;
  13754. };
  13755. /**
  13756. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  13757. * This method can be called within the render loop.
  13758. * You don't need to call this method by yourself in the render loop when you update/morph a mesh with the methods CreateXXX() as they automatically manage this computation.
  13759. * Returns the AbstractMesh.
  13760. */
  13761. AbstractMesh.prototype.updateFacetData = function () {
  13762. if (!this._facetDataEnabled) {
  13763. this._initFacetData();
  13764. }
  13765. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13766. var indices = this.getIndices();
  13767. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13768. var bInfo = this.getBoundingInfo();
  13769. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  13770. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  13771. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  13772. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  13773. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  13774. this._subDiv.max = this._partitioningSubdivisions;
  13775. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  13776. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  13777. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  13778. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  13779. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  13780. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  13781. // set the parameters for ComputeNormals()
  13782. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  13783. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  13784. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  13785. this._facetParameters.bInfo = bInfo;
  13786. this._facetParameters.bbSize = this._bbSize;
  13787. this._facetParameters.subDiv = this._subDiv;
  13788. this._facetParameters.ratio = this.partitioningBBoxRatio;
  13789. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  13790. return this;
  13791. };
  13792. /**
  13793. * Returns the facetLocalNormals array.
  13794. * The normals are expressed in the mesh local space.
  13795. */
  13796. AbstractMesh.prototype.getFacetLocalNormals = function () {
  13797. if (!this._facetNormals) {
  13798. this.updateFacetData();
  13799. }
  13800. return this._facetNormals;
  13801. };
  13802. /**
  13803. * Returns the facetLocalPositions array.
  13804. * The facet positions are expressed in the mesh local space.
  13805. */
  13806. AbstractMesh.prototype.getFacetLocalPositions = function () {
  13807. if (!this._facetPositions) {
  13808. this.updateFacetData();
  13809. }
  13810. return this._facetPositions;
  13811. };
  13812. /**
  13813. * Returns the facetLocalPartioning array.
  13814. */
  13815. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  13816. if (!this._facetPartitioning) {
  13817. this.updateFacetData();
  13818. }
  13819. return this._facetPartitioning;
  13820. };
  13821. /**
  13822. * Returns the i-th facet position in the world system.
  13823. * This method allocates a new Vector3 per call.
  13824. */
  13825. AbstractMesh.prototype.getFacetPosition = function (i) {
  13826. var pos = BABYLON.Vector3.Zero();
  13827. this.getFacetPositionToRef(i, pos);
  13828. return pos;
  13829. };
  13830. /**
  13831. * Sets the reference Vector3 with the i-th facet position in the world system.
  13832. * Returns the AbstractMesh.
  13833. */
  13834. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  13835. var localPos = (this.getFacetLocalPositions())[i];
  13836. var world = this.getWorldMatrix();
  13837. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  13838. return this;
  13839. };
  13840. /**
  13841. * Returns the i-th facet normal in the world system.
  13842. * This method allocates a new Vector3 per call.
  13843. */
  13844. AbstractMesh.prototype.getFacetNormal = function (i) {
  13845. var norm = BABYLON.Vector3.Zero();
  13846. this.getFacetNormalToRef(i, norm);
  13847. return norm;
  13848. };
  13849. /**
  13850. * Sets the reference Vector3 with the i-th facet normal in the world system.
  13851. * Returns the AbstractMesh.
  13852. */
  13853. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  13854. var localNorm = (this.getFacetLocalNormals())[i];
  13855. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  13856. return this;
  13857. };
  13858. /**
  13859. * Returns the facets (in an array) in the same partitioning block than the one the passed coordinates are located (expressed in the mesh local system).
  13860. */
  13861. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  13862. var bInfo = this.getBoundingInfo();
  13863. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  13864. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  13865. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  13866. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  13867. return null;
  13868. }
  13869. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  13870. };
  13871. /**
  13872. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found.
  13873. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) World projection on the facet.
  13874. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13875. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13876. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13877. */
  13878. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  13879. if (checkFace === void 0) { checkFace = false; }
  13880. if (facing === void 0) { facing = true; }
  13881. var world = this.getWorldMatrix();
  13882. var invMat = BABYLON.Tmp.Matrix[5];
  13883. world.invertToRef(invMat);
  13884. var invVect = BABYLON.Tmp.Vector3[8];
  13885. var closest = null;
  13886. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  13887. closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  13888. if (projected) {
  13889. // tranform the local computed projected vector to world coordinates
  13890. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  13891. }
  13892. return closest;
  13893. };
  13894. /**
  13895. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found.
  13896. * If the parameter projected (vector3) is passed, it is set as the (x,y,z) local projection on the facet.
  13897. * If checkFace is true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned.
  13898. * If facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position.
  13899. * If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position.
  13900. */
  13901. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  13902. if (checkFace === void 0) { checkFace = false; }
  13903. if (facing === void 0) { facing = true; }
  13904. var closest = null;
  13905. var tmpx = 0.0;
  13906. var tmpy = 0.0;
  13907. var tmpz = 0.0;
  13908. var d = 0.0; // tmp dot facet normal * facet position
  13909. var t0 = 0.0;
  13910. var projx = 0.0;
  13911. var projy = 0.0;
  13912. var projz = 0.0;
  13913. // Get all the facets in the same partitioning block than (x, y, z)
  13914. var facetPositions = this.getFacetLocalPositions();
  13915. var facetNormals = this.getFacetLocalNormals();
  13916. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  13917. if (!facetsInBlock) {
  13918. return null;
  13919. }
  13920. // Get the closest facet to (x, y, z)
  13921. var shortest = Number.MAX_VALUE; // init distance vars
  13922. var tmpDistance = shortest;
  13923. var fib; // current facet in the block
  13924. var norm; // current facet normal
  13925. var p0; // current facet barycenter position
  13926. // loop on all the facets in the current partitioning block
  13927. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  13928. fib = facetsInBlock[idx];
  13929. norm = facetNormals[fib];
  13930. p0 = facetPositions[fib];
  13931. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  13932. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  13933. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  13934. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  13935. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  13936. projx = x + norm.x * t0;
  13937. projy = y + norm.y * t0;
  13938. projz = z + norm.z * t0;
  13939. tmpx = projx - x;
  13940. tmpy = projy - y;
  13941. tmpz = projz - z;
  13942. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  13943. if (tmpDistance < shortest) {
  13944. shortest = tmpDistance;
  13945. closest = fib;
  13946. if (projected) {
  13947. projected.x = projx;
  13948. projected.y = projy;
  13949. projected.z = projz;
  13950. }
  13951. }
  13952. }
  13953. }
  13954. return closest;
  13955. };
  13956. /**
  13957. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  13958. */
  13959. AbstractMesh.prototype.getFacetDataParameters = function () {
  13960. return this._facetParameters;
  13961. };
  13962. /**
  13963. * Disables the feature FacetData and frees the related memory.
  13964. * Returns the AbstractMesh.
  13965. */
  13966. AbstractMesh.prototype.disableFacetData = function () {
  13967. if (this._facetDataEnabled) {
  13968. this._facetDataEnabled = false;
  13969. this._facetPositions = null;
  13970. this._facetNormals = null;
  13971. this._facetPartitioning = null;
  13972. this._facetParameters = null;
  13973. }
  13974. return this;
  13975. };
  13976. /**
  13977. * Creates new normals data for the mesh.
  13978. * @param updatable.
  13979. */
  13980. AbstractMesh.prototype.createNormals = function (updatable) {
  13981. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  13982. var indices = this.getIndices();
  13983. var normals;
  13984. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  13985. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  13986. }
  13987. else {
  13988. normals = [];
  13989. }
  13990. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  13991. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  13992. };
  13993. AbstractMesh.prototype.checkOcclusionQuery = function () {
  13994. var engine = this.getEngine();
  13995. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  13996. this._isOccluded = false;
  13997. return;
  13998. }
  13999. if (this.isOcclusionQueryInProgress) {
  14000. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  14001. if (isOcclusionQueryAvailable) {
  14002. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  14003. this._isOcclusionQueryInProgress = false;
  14004. this._occlusionInternalRetryCounter = 0;
  14005. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  14006. }
  14007. else {
  14008. this._occlusionInternalRetryCounter++;
  14009. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  14010. this._isOcclusionQueryInProgress = false;
  14011. this._occlusionInternalRetryCounter = 0;
  14012. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  14013. // if strict continue the last state of the object.
  14014. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  14015. }
  14016. else {
  14017. return;
  14018. }
  14019. }
  14020. }
  14021. var scene = this.getScene();
  14022. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  14023. if (!this._occlusionQuery) {
  14024. this._occlusionQuery = engine.createQuery();
  14025. }
  14026. engine.beginQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  14027. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  14028. engine.endQuery(this.occlusionQueryAlgorithmType);
  14029. this._isOcclusionQueryInProgress = true;
  14030. };
  14031. // Statics
  14032. AbstractMesh._BILLBOARDMODE_NONE = 0;
  14033. AbstractMesh._BILLBOARDMODE_X = 1;
  14034. AbstractMesh._BILLBOARDMODE_Y = 2;
  14035. AbstractMesh._BILLBOARDMODE_Z = 4;
  14036. AbstractMesh._BILLBOARDMODE_ALL = 7;
  14037. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  14038. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  14039. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  14040. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  14041. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  14042. AbstractMesh._rotationAxisCache = new BABYLON.Quaternion();
  14043. AbstractMesh._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  14044. return AbstractMesh;
  14045. }(BABYLON.Node));
  14046. BABYLON.AbstractMesh = AbstractMesh;
  14047. })(BABYLON || (BABYLON = {}));
  14048. //# sourceMappingURL=babylon.abstractMesh.js.map
  14049. var BABYLON;
  14050. (function (BABYLON) {
  14051. var Light = (function (_super) {
  14052. __extends(Light, _super);
  14053. /**
  14054. * Creates a Light object in the scene.
  14055. * Documentation : http://doc.babylonjs.com/tutorials/lights
  14056. */
  14057. function Light(name, scene) {
  14058. var _this = _super.call(this, name, scene) || this;
  14059. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  14060. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  14061. _this.intensity = 1.0;
  14062. _this.range = Number.MAX_VALUE;
  14063. /**
  14064. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  14065. * of light.
  14066. */
  14067. _this._photometricScale = 1.0;
  14068. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  14069. _this._radius = 0.00001;
  14070. _this.renderPriority = 0;
  14071. /**
  14072. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  14073. * the current shadow generator.
  14074. */
  14075. _this.shadowEnabled = true;
  14076. _this._excludeWithLayerMask = 0;
  14077. _this._includeOnlyWithLayerMask = 0;
  14078. _this._lightmapMode = 0;
  14079. _this._excludedMeshesIds = new Array();
  14080. _this._includedOnlyMeshesIds = new Array();
  14081. _this.getScene().addLight(_this);
  14082. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  14083. _this._buildUniformLayout();
  14084. _this.includedOnlyMeshes = new Array();
  14085. _this.excludedMeshes = new Array();
  14086. _this._resyncMeshes();
  14087. return _this;
  14088. }
  14089. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  14090. /**
  14091. * If every light affecting the material is in this lightmapMode,
  14092. * material.lightmapTexture adds or multiplies
  14093. * (depends on material.useLightmapAsShadowmap)
  14094. * after every other light calculations.
  14095. */
  14096. get: function () {
  14097. return Light._LIGHTMAP_DEFAULT;
  14098. },
  14099. enumerable: true,
  14100. configurable: true
  14101. });
  14102. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  14103. /**
  14104. * material.lightmapTexture as only diffuse lighting from this light
  14105. * adds pnly specular lighting from this light
  14106. * adds dynamic shadows
  14107. */
  14108. get: function () {
  14109. return Light._LIGHTMAP_SPECULAR;
  14110. },
  14111. enumerable: true,
  14112. configurable: true
  14113. });
  14114. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  14115. /**
  14116. * material.lightmapTexture as only lighting
  14117. * no light calculation from this light
  14118. * only adds dynamic shadows from this light
  14119. */
  14120. get: function () {
  14121. return Light._LIGHTMAP_SHADOWSONLY;
  14122. },
  14123. enumerable: true,
  14124. configurable: true
  14125. });
  14126. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  14127. /**
  14128. * Each light type uses the default quantity according to its type:
  14129. * point/spot lights use luminous intensity
  14130. * directional lights use illuminance
  14131. */
  14132. get: function () {
  14133. return Light._INTENSITYMODE_AUTOMATIC;
  14134. },
  14135. enumerable: true,
  14136. configurable: true
  14137. });
  14138. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  14139. /**
  14140. * lumen (lm)
  14141. */
  14142. get: function () {
  14143. return Light._INTENSITYMODE_LUMINOUSPOWER;
  14144. },
  14145. enumerable: true,
  14146. configurable: true
  14147. });
  14148. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  14149. /**
  14150. * candela (lm/sr)
  14151. */
  14152. get: function () {
  14153. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  14154. },
  14155. enumerable: true,
  14156. configurable: true
  14157. });
  14158. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  14159. /**
  14160. * lux (lm/m^2)
  14161. */
  14162. get: function () {
  14163. return Light._INTENSITYMODE_ILLUMINANCE;
  14164. },
  14165. enumerable: true,
  14166. configurable: true
  14167. });
  14168. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  14169. /**
  14170. * nit (cd/m^2)
  14171. */
  14172. get: function () {
  14173. return Light._INTENSITYMODE_LUMINANCE;
  14174. },
  14175. enumerable: true,
  14176. configurable: true
  14177. });
  14178. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  14179. /**
  14180. * Light type const id of the point light.
  14181. */
  14182. get: function () {
  14183. return Light._LIGHTTYPEID_POINTLIGHT;
  14184. },
  14185. enumerable: true,
  14186. configurable: true
  14187. });
  14188. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  14189. /**
  14190. * Light type const id of the directional light.
  14191. */
  14192. get: function () {
  14193. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  14194. },
  14195. enumerable: true,
  14196. configurable: true
  14197. });
  14198. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  14199. /**
  14200. * Light type const id of the spot light.
  14201. */
  14202. get: function () {
  14203. return Light._LIGHTTYPEID_SPOTLIGHT;
  14204. },
  14205. enumerable: true,
  14206. configurable: true
  14207. });
  14208. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  14209. /**
  14210. * Light type const id of the hemispheric light.
  14211. */
  14212. get: function () {
  14213. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  14214. },
  14215. enumerable: true,
  14216. configurable: true
  14217. });
  14218. Object.defineProperty(Light.prototype, "intensityMode", {
  14219. /**
  14220. * Gets the photometric scale used to interpret the intensity.
  14221. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14222. */
  14223. get: function () {
  14224. return this._intensityMode;
  14225. },
  14226. /**
  14227. * Sets the photometric scale used to interpret the intensity.
  14228. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  14229. */
  14230. set: function (value) {
  14231. this._intensityMode = value;
  14232. this._computePhotometricScale();
  14233. },
  14234. enumerable: true,
  14235. configurable: true
  14236. });
  14237. ;
  14238. ;
  14239. Object.defineProperty(Light.prototype, "radius", {
  14240. /**
  14241. * Gets the light radius used by PBR Materials to simulate soft area lights.
  14242. */
  14243. get: function () {
  14244. return this._radius;
  14245. },
  14246. /**
  14247. * sets the light radius used by PBR Materials to simulate soft area lights.
  14248. */
  14249. set: function (value) {
  14250. this._radius = value;
  14251. this._computePhotometricScale();
  14252. },
  14253. enumerable: true,
  14254. configurable: true
  14255. });
  14256. ;
  14257. ;
  14258. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  14259. get: function () {
  14260. return this._includedOnlyMeshes;
  14261. },
  14262. set: function (value) {
  14263. this._includedOnlyMeshes = value;
  14264. this._hookArrayForIncludedOnly(value);
  14265. },
  14266. enumerable: true,
  14267. configurable: true
  14268. });
  14269. Object.defineProperty(Light.prototype, "excludedMeshes", {
  14270. get: function () {
  14271. return this._excludedMeshes;
  14272. },
  14273. set: function (value) {
  14274. this._excludedMeshes = value;
  14275. this._hookArrayForExcluded(value);
  14276. },
  14277. enumerable: true,
  14278. configurable: true
  14279. });
  14280. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  14281. get: function () {
  14282. return this._excludeWithLayerMask;
  14283. },
  14284. set: function (value) {
  14285. this._excludeWithLayerMask = value;
  14286. this._resyncMeshes();
  14287. },
  14288. enumerable: true,
  14289. configurable: true
  14290. });
  14291. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  14292. get: function () {
  14293. return this._includeOnlyWithLayerMask;
  14294. },
  14295. set: function (value) {
  14296. this._includeOnlyWithLayerMask = value;
  14297. this._resyncMeshes();
  14298. },
  14299. enumerable: true,
  14300. configurable: true
  14301. });
  14302. Object.defineProperty(Light.prototype, "lightmapMode", {
  14303. get: function () {
  14304. return this._lightmapMode;
  14305. },
  14306. set: function (value) {
  14307. if (this._lightmapMode === value) {
  14308. return;
  14309. }
  14310. this._lightmapMode = value;
  14311. this._markMeshesAsLightDirty();
  14312. },
  14313. enumerable: true,
  14314. configurable: true
  14315. });
  14316. Light.prototype._buildUniformLayout = function () {
  14317. // Overridden
  14318. };
  14319. /**
  14320. * Returns the string "Light".
  14321. */
  14322. Light.prototype.getClassName = function () {
  14323. return "Light";
  14324. };
  14325. /**
  14326. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14327. */
  14328. Light.prototype.toString = function (fullDetails) {
  14329. var ret = "Name: " + this.name;
  14330. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  14331. if (this.animations) {
  14332. for (var i = 0; i < this.animations.length; i++) {
  14333. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14334. }
  14335. }
  14336. if (fullDetails) {
  14337. }
  14338. return ret;
  14339. };
  14340. /**
  14341. * Set the enabled state of this node.
  14342. * @param {boolean} value - the new enabled state
  14343. * @see isEnabled
  14344. */
  14345. Light.prototype.setEnabled = function (value) {
  14346. _super.prototype.setEnabled.call(this, value);
  14347. this._resyncMeshes();
  14348. };
  14349. /**
  14350. * Returns the Light associated shadow generator.
  14351. */
  14352. Light.prototype.getShadowGenerator = function () {
  14353. return this._shadowGenerator;
  14354. };
  14355. /**
  14356. * Returns a Vector3, the absolute light position in the World.
  14357. */
  14358. Light.prototype.getAbsolutePosition = function () {
  14359. return BABYLON.Vector3.Zero();
  14360. };
  14361. Light.prototype.transferToEffect = function (effect, lightIndex) {
  14362. };
  14363. Light.prototype._getWorldMatrix = function () {
  14364. return BABYLON.Matrix.Identity();
  14365. };
  14366. /**
  14367. * Boolean : True if the light will affect the passed mesh.
  14368. */
  14369. Light.prototype.canAffectMesh = function (mesh) {
  14370. if (!mesh) {
  14371. return true;
  14372. }
  14373. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  14374. return false;
  14375. }
  14376. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  14377. return false;
  14378. }
  14379. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  14380. return false;
  14381. }
  14382. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  14383. return false;
  14384. }
  14385. return true;
  14386. };
  14387. /**
  14388. * Returns the light World matrix.
  14389. */
  14390. Light.prototype.getWorldMatrix = function () {
  14391. this._currentRenderId = this.getScene().getRenderId();
  14392. var worldMatrix = this._getWorldMatrix();
  14393. if (this.parent && this.parent.getWorldMatrix) {
  14394. if (!this._parentedWorldMatrix) {
  14395. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  14396. }
  14397. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  14398. this._markSyncedWithParent();
  14399. return this._parentedWorldMatrix;
  14400. }
  14401. return worldMatrix;
  14402. };
  14403. /**
  14404. * Sort function to order lights for rendering.
  14405. * @param a First Light object to compare to second.
  14406. * @param b Second Light object to compare first.
  14407. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  14408. */
  14409. Light.compareLightsPriority = function (a, b) {
  14410. //shadow-casting lights have priority over non-shadow-casting lights
  14411. //the renderPrioirty is a secondary sort criterion
  14412. if (a.shadowEnabled !== b.shadowEnabled) {
  14413. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  14414. }
  14415. return b.renderPriority - a.renderPriority;
  14416. };
  14417. /**
  14418. * Disposes the light.
  14419. */
  14420. Light.prototype.dispose = function () {
  14421. if (this._shadowGenerator) {
  14422. this._shadowGenerator.dispose();
  14423. this._shadowGenerator = null;
  14424. }
  14425. // Animations
  14426. this.getScene().stopAnimation(this);
  14427. // Remove from meshes
  14428. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14429. var mesh = _a[_i];
  14430. mesh._removeLightSource(this);
  14431. }
  14432. this._uniformBuffer.dispose();
  14433. // Remove from scene
  14434. this.getScene().removeLight(this);
  14435. _super.prototype.dispose.call(this);
  14436. };
  14437. /**
  14438. * Returns the light type ID (integer).
  14439. */
  14440. Light.prototype.getTypeID = function () {
  14441. return 0;
  14442. };
  14443. /**
  14444. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  14445. */
  14446. Light.prototype.getScaledIntensity = function () {
  14447. return this._photometricScale * this.intensity;
  14448. };
  14449. /**
  14450. * Returns a new Light object, named "name", from the current one.
  14451. */
  14452. Light.prototype.clone = function (name) {
  14453. return BABYLON.SerializationHelper.Clone(Light.GetConstructorFromName(this.getTypeID(), name, this.getScene()), this);
  14454. };
  14455. /**
  14456. * Serializes the current light into a Serialization object.
  14457. * Returns the serialized object.
  14458. */
  14459. Light.prototype.serialize = function () {
  14460. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  14461. // Type
  14462. serializationObject.type = this.getTypeID();
  14463. // Parent
  14464. if (this.parent) {
  14465. serializationObject.parentId = this.parent.id;
  14466. }
  14467. // Inclusion / exclusions
  14468. if (this.excludedMeshes.length > 0) {
  14469. serializationObject.excludedMeshesIds = [];
  14470. this.excludedMeshes.forEach(function (mesh) {
  14471. serializationObject.excludedMeshesIds.push(mesh.id);
  14472. });
  14473. }
  14474. if (this.includedOnlyMeshes.length > 0) {
  14475. serializationObject.includedOnlyMeshesIds = [];
  14476. this.includedOnlyMeshes.forEach(function (mesh) {
  14477. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  14478. });
  14479. }
  14480. // Animations
  14481. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  14482. serializationObject.ranges = this.serializeAnimationRanges();
  14483. return serializationObject;
  14484. };
  14485. /**
  14486. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  14487. * This new light is named "name" and added to the passed scene.
  14488. */
  14489. Light.GetConstructorFromName = function (type, name, scene) {
  14490. switch (type) {
  14491. case 0:
  14492. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  14493. case 1:
  14494. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  14495. case 2:
  14496. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  14497. case 3:
  14498. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  14499. }
  14500. };
  14501. /**
  14502. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  14503. */
  14504. Light.Parse = function (parsedLight, scene) {
  14505. var light = BABYLON.SerializationHelper.Parse(Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene), parsedLight, scene);
  14506. // Inclusion / exclusions
  14507. if (parsedLight.excludedMeshesIds) {
  14508. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  14509. }
  14510. if (parsedLight.includedOnlyMeshesIds) {
  14511. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  14512. }
  14513. // Parent
  14514. if (parsedLight.parentId) {
  14515. light._waitingParentId = parsedLight.parentId;
  14516. }
  14517. // Animations
  14518. if (parsedLight.animations) {
  14519. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  14520. var parsedAnimation = parsedLight.animations[animationIndex];
  14521. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  14522. }
  14523. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  14524. }
  14525. if (parsedLight.autoAnimate) {
  14526. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  14527. }
  14528. return light;
  14529. };
  14530. Light.prototype._hookArrayForExcluded = function (array) {
  14531. var _this = this;
  14532. var oldPush = array.push;
  14533. array.push = function () {
  14534. var items = [];
  14535. for (var _i = 0; _i < arguments.length; _i++) {
  14536. items[_i] = arguments[_i];
  14537. }
  14538. var result = oldPush.apply(array, items);
  14539. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  14540. var item = items_1[_a];
  14541. item._resyncLighSource(_this);
  14542. }
  14543. return result;
  14544. };
  14545. var oldSplice = array.splice;
  14546. array.splice = function (index, deleteCount) {
  14547. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14548. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  14549. var item = deleted_1[_i];
  14550. item._resyncLighSource(_this);
  14551. }
  14552. return deleted;
  14553. };
  14554. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  14555. var item = array_1[_i];
  14556. item._resyncLighSource(this);
  14557. }
  14558. };
  14559. Light.prototype._hookArrayForIncludedOnly = function (array) {
  14560. var _this = this;
  14561. var oldPush = array.push;
  14562. array.push = function () {
  14563. var items = [];
  14564. for (var _i = 0; _i < arguments.length; _i++) {
  14565. items[_i] = arguments[_i];
  14566. }
  14567. var result = oldPush.apply(array, items);
  14568. _this._resyncMeshes();
  14569. return result;
  14570. };
  14571. var oldSplice = array.splice;
  14572. array.splice = function (index, deleteCount) {
  14573. var deleted = oldSplice.apply(array, [index, deleteCount]);
  14574. _this._resyncMeshes();
  14575. return deleted;
  14576. };
  14577. this._resyncMeshes();
  14578. };
  14579. Light.prototype._resyncMeshes = function () {
  14580. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14581. var mesh = _a[_i];
  14582. mesh._resyncLighSource(this);
  14583. }
  14584. };
  14585. Light.prototype._markMeshesAsLightDirty = function () {
  14586. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  14587. var mesh = _a[_i];
  14588. if (mesh._lightSources.indexOf(this) !== -1) {
  14589. mesh._markSubMeshesAsLightDirty();
  14590. }
  14591. }
  14592. };
  14593. /**
  14594. * Recomputes the cached photometric scale if needed.
  14595. */
  14596. Light.prototype._computePhotometricScale = function () {
  14597. this._photometricScale = this._getPhotometricScale();
  14598. this.getScene().resetCachedMaterial();
  14599. };
  14600. /**
  14601. * Returns the Photometric Scale according to the light type and intensity mode.
  14602. */
  14603. Light.prototype._getPhotometricScale = function () {
  14604. var photometricScale = 0.0;
  14605. var lightTypeID = this.getTypeID();
  14606. //get photometric mode
  14607. var photometricMode = this.intensityMode;
  14608. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  14609. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  14610. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  14611. }
  14612. else {
  14613. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  14614. }
  14615. }
  14616. //compute photometric scale
  14617. switch (lightTypeID) {
  14618. case Light.LIGHTTYPEID_POINTLIGHT:
  14619. case Light.LIGHTTYPEID_SPOTLIGHT:
  14620. switch (photometricMode) {
  14621. case Light.INTENSITYMODE_LUMINOUSPOWER:
  14622. photometricScale = 1.0 / (4.0 * Math.PI);
  14623. break;
  14624. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  14625. photometricScale = 1.0;
  14626. break;
  14627. case Light.INTENSITYMODE_LUMINANCE:
  14628. photometricScale = this.radius * this.radius;
  14629. break;
  14630. }
  14631. break;
  14632. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  14633. switch (photometricMode) {
  14634. case Light.INTENSITYMODE_ILLUMINANCE:
  14635. photometricScale = 1.0;
  14636. break;
  14637. case Light.INTENSITYMODE_LUMINANCE:
  14638. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  14639. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  14640. var apexAngleRadians = this.radius;
  14641. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  14642. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  14643. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  14644. photometricScale = solidAngle;
  14645. break;
  14646. }
  14647. break;
  14648. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  14649. // No fall off in hemisperic light.
  14650. photometricScale = 1.0;
  14651. break;
  14652. }
  14653. return photometricScale;
  14654. };
  14655. Light.prototype._reorderLightsInScene = function () {
  14656. var scene = this.getScene();
  14657. if (this.renderPriority != 0) {
  14658. scene.requireLightSorting = true;
  14659. }
  14660. this.getScene().sortLightsByPriority();
  14661. };
  14662. //lightmapMode Consts
  14663. Light._LIGHTMAP_DEFAULT = 0;
  14664. Light._LIGHTMAP_SPECULAR = 1;
  14665. Light._LIGHTMAP_SHADOWSONLY = 2;
  14666. // Intensity Mode Consts
  14667. Light._INTENSITYMODE_AUTOMATIC = 0;
  14668. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  14669. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  14670. Light._INTENSITYMODE_ILLUMINANCE = 3;
  14671. Light._INTENSITYMODE_LUMINANCE = 4;
  14672. // Light types ids const.
  14673. Light._LIGHTTYPEID_POINTLIGHT = 0;
  14674. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  14675. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  14676. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  14677. __decorate([
  14678. BABYLON.serializeAsColor3()
  14679. ], Light.prototype, "diffuse", void 0);
  14680. __decorate([
  14681. BABYLON.serializeAsColor3()
  14682. ], Light.prototype, "specular", void 0);
  14683. __decorate([
  14684. BABYLON.serialize()
  14685. ], Light.prototype, "intensity", void 0);
  14686. __decorate([
  14687. BABYLON.serialize()
  14688. ], Light.prototype, "range", void 0);
  14689. __decorate([
  14690. BABYLON.serialize()
  14691. ], Light.prototype, "intensityMode", null);
  14692. __decorate([
  14693. BABYLON.serialize()
  14694. ], Light.prototype, "radius", null);
  14695. __decorate([
  14696. BABYLON.serialize()
  14697. ], Light.prototype, "_renderPriority", void 0);
  14698. __decorate([
  14699. BABYLON.expandToProperty("_reorderLightsInScene")
  14700. ], Light.prototype, "renderPriority", void 0);
  14701. __decorate([
  14702. BABYLON.serialize()
  14703. ], Light.prototype, "shadowEnabled", void 0);
  14704. __decorate([
  14705. BABYLON.serialize("excludeWithLayerMask")
  14706. ], Light.prototype, "_excludeWithLayerMask", void 0);
  14707. __decorate([
  14708. BABYLON.serialize("includeOnlyWithLayerMask")
  14709. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  14710. __decorate([
  14711. BABYLON.serialize("lightmapMode")
  14712. ], Light.prototype, "_lightmapMode", void 0);
  14713. return Light;
  14714. }(BABYLON.Node));
  14715. BABYLON.Light = Light;
  14716. })(BABYLON || (BABYLON = {}));
  14717. //# sourceMappingURL=babylon.light.js.map
  14718. var BABYLON;
  14719. (function (BABYLON) {
  14720. var Camera = (function (_super) {
  14721. __extends(Camera, _super);
  14722. function Camera(name, position, scene) {
  14723. var _this = _super.call(this, name, scene) || this;
  14724. _this.upVector = BABYLON.Vector3.Up();
  14725. _this.orthoLeft = null;
  14726. _this.orthoRight = null;
  14727. _this.orthoBottom = null;
  14728. _this.orthoTop = null;
  14729. _this.fov = 0.8;
  14730. _this.minZ = 1;
  14731. _this.maxZ = 10000.0;
  14732. _this.inertia = 0.9;
  14733. _this.mode = Camera.PERSPECTIVE_CAMERA;
  14734. _this.isIntermediate = false;
  14735. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  14736. _this.layerMask = 0x0FFFFFFF;
  14737. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  14738. // Camera rig members
  14739. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  14740. _this._rigCameras = new Array();
  14741. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  14742. _this.customRenderTargets = new Array();
  14743. // Observables
  14744. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  14745. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  14746. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  14747. // Cache
  14748. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  14749. _this._projectionMatrix = new BABYLON.Matrix();
  14750. _this._doNotComputeProjectionMatrix = false;
  14751. _this._postProcesses = new Array();
  14752. _this._transformMatrix = BABYLON.Matrix.Zero();
  14753. _this._activeMeshes = new BABYLON.SmartArray(256);
  14754. _this._globalPosition = BABYLON.Vector3.Zero();
  14755. _this._refreshFrustumPlanes = true;
  14756. _this.getScene().addCamera(_this);
  14757. if (!_this.getScene().activeCamera) {
  14758. _this.getScene().activeCamera = _this;
  14759. }
  14760. _this.position = position;
  14761. return _this;
  14762. }
  14763. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  14764. get: function () {
  14765. return Camera._PERSPECTIVE_CAMERA;
  14766. },
  14767. enumerable: true,
  14768. configurable: true
  14769. });
  14770. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  14771. get: function () {
  14772. return Camera._ORTHOGRAPHIC_CAMERA;
  14773. },
  14774. enumerable: true,
  14775. configurable: true
  14776. });
  14777. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  14778. get: function () {
  14779. return Camera._FOVMODE_VERTICAL_FIXED;
  14780. },
  14781. enumerable: true,
  14782. configurable: true
  14783. });
  14784. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  14785. get: function () {
  14786. return Camera._FOVMODE_HORIZONTAL_FIXED;
  14787. },
  14788. enumerable: true,
  14789. configurable: true
  14790. });
  14791. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  14792. get: function () {
  14793. return Camera._RIG_MODE_NONE;
  14794. },
  14795. enumerable: true,
  14796. configurable: true
  14797. });
  14798. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  14799. get: function () {
  14800. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  14801. },
  14802. enumerable: true,
  14803. configurable: true
  14804. });
  14805. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  14806. get: function () {
  14807. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  14808. },
  14809. enumerable: true,
  14810. configurable: true
  14811. });
  14812. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  14813. get: function () {
  14814. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  14815. },
  14816. enumerable: true,
  14817. configurable: true
  14818. });
  14819. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  14820. get: function () {
  14821. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  14822. },
  14823. enumerable: true,
  14824. configurable: true
  14825. });
  14826. Object.defineProperty(Camera, "RIG_MODE_VR", {
  14827. get: function () {
  14828. return Camera._RIG_MODE_VR;
  14829. },
  14830. enumerable: true,
  14831. configurable: true
  14832. });
  14833. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  14834. get: function () {
  14835. return Camera._RIG_MODE_WEBVR;
  14836. },
  14837. enumerable: true,
  14838. configurable: true
  14839. });
  14840. Camera.prototype.getClassName = function () {
  14841. return "Camera";
  14842. };
  14843. /**
  14844. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  14845. */
  14846. Camera.prototype.toString = function (fullDetails) {
  14847. var ret = "Name: " + this.name;
  14848. ret += ", type: " + this.getClassName();
  14849. if (this.animations) {
  14850. for (var i = 0; i < this.animations.length; i++) {
  14851. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  14852. }
  14853. }
  14854. if (fullDetails) {
  14855. }
  14856. return ret;
  14857. };
  14858. Object.defineProperty(Camera.prototype, "globalPosition", {
  14859. get: function () {
  14860. return this._globalPosition;
  14861. },
  14862. enumerable: true,
  14863. configurable: true
  14864. });
  14865. Camera.prototype.getActiveMeshes = function () {
  14866. return this._activeMeshes;
  14867. };
  14868. Camera.prototype.isActiveMesh = function (mesh) {
  14869. return (this._activeMeshes.indexOf(mesh) !== -1);
  14870. };
  14871. //Cache
  14872. Camera.prototype._initCache = function () {
  14873. _super.prototype._initCache.call(this);
  14874. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14875. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  14876. this._cache.mode = undefined;
  14877. this._cache.minZ = undefined;
  14878. this._cache.maxZ = undefined;
  14879. this._cache.fov = undefined;
  14880. this._cache.fovMode = undefined;
  14881. this._cache.aspectRatio = undefined;
  14882. this._cache.orthoLeft = undefined;
  14883. this._cache.orthoRight = undefined;
  14884. this._cache.orthoBottom = undefined;
  14885. this._cache.orthoTop = undefined;
  14886. this._cache.renderWidth = undefined;
  14887. this._cache.renderHeight = undefined;
  14888. };
  14889. Camera.prototype._updateCache = function (ignoreParentClass) {
  14890. if (!ignoreParentClass) {
  14891. _super.prototype._updateCache.call(this);
  14892. }
  14893. var engine = this.getEngine();
  14894. this._cache.position.copyFrom(this.position);
  14895. this._cache.upVector.copyFrom(this.upVector);
  14896. this._cache.mode = this.mode;
  14897. this._cache.minZ = this.minZ;
  14898. this._cache.maxZ = this.maxZ;
  14899. this._cache.fov = this.fov;
  14900. this._cache.fovMode = this.fovMode;
  14901. this._cache.aspectRatio = engine.getAspectRatio(this);
  14902. this._cache.orthoLeft = this.orthoLeft;
  14903. this._cache.orthoRight = this.orthoRight;
  14904. this._cache.orthoBottom = this.orthoBottom;
  14905. this._cache.orthoTop = this.orthoTop;
  14906. this._cache.renderWidth = engine.getRenderWidth();
  14907. this._cache.renderHeight = engine.getRenderHeight();
  14908. };
  14909. Camera.prototype._updateFromScene = function () {
  14910. this.updateCache();
  14911. this.update();
  14912. };
  14913. // Synchronized
  14914. Camera.prototype._isSynchronized = function () {
  14915. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  14916. };
  14917. Camera.prototype._isSynchronizedViewMatrix = function () {
  14918. if (!_super.prototype._isSynchronized.call(this))
  14919. return false;
  14920. return this._cache.position.equals(this.position)
  14921. && this._cache.upVector.equals(this.upVector)
  14922. && this.isSynchronizedWithParent();
  14923. };
  14924. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  14925. var check = this._cache.mode === this.mode
  14926. && this._cache.minZ === this.minZ
  14927. && this._cache.maxZ === this.maxZ;
  14928. if (!check) {
  14929. return false;
  14930. }
  14931. var engine = this.getEngine();
  14932. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  14933. check = this._cache.fov === this.fov
  14934. && this._cache.fovMode === this.fovMode
  14935. && this._cache.aspectRatio === engine.getAspectRatio(this);
  14936. }
  14937. else {
  14938. check = this._cache.orthoLeft === this.orthoLeft
  14939. && this._cache.orthoRight === this.orthoRight
  14940. && this._cache.orthoBottom === this.orthoBottom
  14941. && this._cache.orthoTop === this.orthoTop
  14942. && this._cache.renderWidth === engine.getRenderWidth()
  14943. && this._cache.renderHeight === engine.getRenderHeight();
  14944. }
  14945. return check;
  14946. };
  14947. // Controls
  14948. Camera.prototype.attachControl = function (element, noPreventDefault) {
  14949. };
  14950. Camera.prototype.detachControl = function (element) {
  14951. };
  14952. Camera.prototype.update = function () {
  14953. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  14954. this._updateRigCameras();
  14955. }
  14956. this._checkInputs();
  14957. };
  14958. Camera.prototype._checkInputs = function () {
  14959. this.onAfterCheckInputsObservable.notifyObservers(this);
  14960. };
  14961. Object.defineProperty(Camera.prototype, "rigCameras", {
  14962. get: function () {
  14963. return this._rigCameras;
  14964. },
  14965. enumerable: true,
  14966. configurable: true
  14967. });
  14968. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  14969. get: function () {
  14970. return this._rigPostProcess;
  14971. },
  14972. enumerable: true,
  14973. configurable: true
  14974. });
  14975. Camera.prototype._cascadePostProcessesToRigCams = function () {
  14976. // invalidate framebuffer
  14977. if (this._postProcesses.length > 0) {
  14978. this._postProcesses[0].markTextureDirty();
  14979. }
  14980. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  14981. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  14982. var cam = this._rigCameras[i];
  14983. var rigPostProcess = cam._rigPostProcess;
  14984. // for VR rig, there does not have to be a post process
  14985. if (rigPostProcess) {
  14986. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  14987. if (isPass) {
  14988. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  14989. cam.isIntermediate = this._postProcesses.length === 0;
  14990. }
  14991. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  14992. rigPostProcess.markTextureDirty();
  14993. }
  14994. else {
  14995. cam._postProcesses = this._postProcesses.slice(0);
  14996. }
  14997. }
  14998. };
  14999. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  15000. if (insertAt === void 0) { insertAt = null; }
  15001. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  15002. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  15003. return 0;
  15004. }
  15005. if (insertAt == null || insertAt < 0) {
  15006. this._postProcesses.push(postProcess);
  15007. }
  15008. else {
  15009. this._postProcesses.splice(insertAt, 0, postProcess);
  15010. }
  15011. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15012. return this._postProcesses.indexOf(postProcess);
  15013. };
  15014. Camera.prototype.detachPostProcess = function (postProcess, atIndices) {
  15015. if (atIndices === void 0) { atIndices = null; }
  15016. var result = [];
  15017. var i;
  15018. var index;
  15019. if (!atIndices) {
  15020. var idx = this._postProcesses.indexOf(postProcess);
  15021. if (idx !== -1) {
  15022. this._postProcesses.splice(idx, 1);
  15023. }
  15024. }
  15025. else {
  15026. atIndices = (atIndices instanceof Array) ? atIndices : [atIndices];
  15027. // iterate descending, so can just splice as we go
  15028. for (i = atIndices.length - 1; i >= 0; i--) {
  15029. if (this._postProcesses[atIndices[i]] !== postProcess) {
  15030. result.push(i);
  15031. continue;
  15032. }
  15033. index = atIndices[i];
  15034. this._postProcesses.splice(index, 1);
  15035. }
  15036. }
  15037. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  15038. return result;
  15039. };
  15040. Camera.prototype.getWorldMatrix = function () {
  15041. if (!this._worldMatrix) {
  15042. this._worldMatrix = BABYLON.Matrix.Identity();
  15043. }
  15044. var viewMatrix = this.getViewMatrix();
  15045. viewMatrix.invertToRef(this._worldMatrix);
  15046. return this._worldMatrix;
  15047. };
  15048. Camera.prototype._getViewMatrix = function () {
  15049. return BABYLON.Matrix.Identity();
  15050. };
  15051. Camera.prototype.getViewMatrix = function (force) {
  15052. if (!force && this._isSynchronizedViewMatrix()) {
  15053. return this._computedViewMatrix;
  15054. }
  15055. this._computedViewMatrix = this._getViewMatrix();
  15056. this._currentRenderId = this.getScene().getRenderId();
  15057. this._refreshFrustumPlanes = true;
  15058. if (!this.parent || !this.parent.getWorldMatrix) {
  15059. this._globalPosition.copyFrom(this.position);
  15060. }
  15061. else {
  15062. if (!this._worldMatrix) {
  15063. this._worldMatrix = BABYLON.Matrix.Identity();
  15064. }
  15065. this._computedViewMatrix.invertToRef(this._worldMatrix);
  15066. this._worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._computedViewMatrix);
  15067. this._globalPosition.copyFromFloats(this._computedViewMatrix.m[12], this._computedViewMatrix.m[13], this._computedViewMatrix.m[14]);
  15068. this._computedViewMatrix.invert();
  15069. this._markSyncedWithParent();
  15070. }
  15071. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  15072. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  15073. }
  15074. this.onViewMatrixChangedObservable.notifyObservers(this);
  15075. return this._computedViewMatrix;
  15076. };
  15077. Camera.prototype.freezeProjectionMatrix = function (projection) {
  15078. this._doNotComputeProjectionMatrix = true;
  15079. if (projection !== undefined) {
  15080. this._projectionMatrix = projection;
  15081. }
  15082. };
  15083. ;
  15084. Camera.prototype.unfreezeProjectionMatrix = function () {
  15085. this._doNotComputeProjectionMatrix = false;
  15086. };
  15087. ;
  15088. Camera.prototype.getProjectionMatrix = function (force) {
  15089. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  15090. return this._projectionMatrix;
  15091. }
  15092. this._refreshFrustumPlanes = true;
  15093. var engine = this.getEngine();
  15094. var scene = this.getScene();
  15095. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  15096. if (this.minZ <= 0) {
  15097. this.minZ = 0.1;
  15098. }
  15099. if (scene.useRightHandedSystem) {
  15100. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15101. }
  15102. else {
  15103. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  15104. }
  15105. }
  15106. else {
  15107. var halfWidth = engine.getRenderWidth() / 2.0;
  15108. var halfHeight = engine.getRenderHeight() / 2.0;
  15109. if (scene.useRightHandedSystem) {
  15110. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15111. }
  15112. else {
  15113. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  15114. }
  15115. }
  15116. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  15117. return this._projectionMatrix;
  15118. };
  15119. Camera.prototype.getTranformationMatrix = function () {
  15120. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  15121. return this._transformMatrix;
  15122. };
  15123. Camera.prototype.updateFrustumPlanes = function () {
  15124. if (!this._refreshFrustumPlanes) {
  15125. return;
  15126. }
  15127. this.getTranformationMatrix();
  15128. if (!this._frustumPlanes) {
  15129. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  15130. }
  15131. else {
  15132. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  15133. }
  15134. this._refreshFrustumPlanes = false;
  15135. };
  15136. Camera.prototype.isInFrustum = function (target) {
  15137. this.updateFrustumPlanes();
  15138. return target.isInFrustum(this._frustumPlanes);
  15139. };
  15140. Camera.prototype.isCompletelyInFrustum = function (target) {
  15141. this.updateFrustumPlanes();
  15142. return target.isCompletelyInFrustum(this._frustumPlanes);
  15143. };
  15144. Camera.prototype.getForwardRay = function (length, transform, origin) {
  15145. if (length === void 0) { length = 100; }
  15146. if (!transform) {
  15147. transform = this.getWorldMatrix();
  15148. }
  15149. if (!origin) {
  15150. origin = this.position;
  15151. }
  15152. var forward = new BABYLON.Vector3(0, 0, 1);
  15153. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  15154. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  15155. return new BABYLON.Ray(origin, direction, length);
  15156. };
  15157. Camera.prototype.dispose = function () {
  15158. // Observables
  15159. this.onViewMatrixChangedObservable.clear();
  15160. this.onProjectionMatrixChangedObservable.clear();
  15161. this.onAfterCheckInputsObservable.clear();
  15162. // Inputs
  15163. if (this.inputs) {
  15164. this.inputs.clear();
  15165. }
  15166. // Animations
  15167. this.getScene().stopAnimation(this);
  15168. // Remove from scene
  15169. this.getScene().removeCamera(this);
  15170. while (this._rigCameras.length > 0) {
  15171. this._rigCameras.pop().dispose();
  15172. }
  15173. // Postprocesses
  15174. var i = this._postProcesses.length;
  15175. while (--i >= 0) {
  15176. this._postProcesses[i].dispose(this);
  15177. }
  15178. // Render targets
  15179. var i = this.customRenderTargets.length;
  15180. while (--i >= 0) {
  15181. this.customRenderTargets[i].dispose();
  15182. }
  15183. this.customRenderTargets = [];
  15184. // Active Meshes
  15185. this._activeMeshes.dispose();
  15186. _super.prototype.dispose.call(this);
  15187. };
  15188. Object.defineProperty(Camera.prototype, "leftCamera", {
  15189. // ---- Camera rigs section ----
  15190. get: function () {
  15191. if (this._rigCameras.length < 1) {
  15192. return undefined;
  15193. }
  15194. return this._rigCameras[0];
  15195. },
  15196. enumerable: true,
  15197. configurable: true
  15198. });
  15199. Object.defineProperty(Camera.prototype, "rightCamera", {
  15200. get: function () {
  15201. if (this._rigCameras.length < 2) {
  15202. return undefined;
  15203. }
  15204. return this._rigCameras[1];
  15205. },
  15206. enumerable: true,
  15207. configurable: true
  15208. });
  15209. Camera.prototype.getLeftTarget = function () {
  15210. if (this._rigCameras.length < 1) {
  15211. return undefined;
  15212. }
  15213. return this._rigCameras[0].getTarget();
  15214. };
  15215. Camera.prototype.getRightTarget = function () {
  15216. if (this._rigCameras.length < 2) {
  15217. return undefined;
  15218. }
  15219. return this._rigCameras[1].getTarget();
  15220. };
  15221. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  15222. while (this._rigCameras.length > 0) {
  15223. this._rigCameras.pop().dispose();
  15224. }
  15225. this.cameraRigMode = mode;
  15226. this._cameraRigParams = {};
  15227. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  15228. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  15229. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  15230. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  15231. // create the rig cameras, unless none
  15232. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  15233. this._rigCameras.push(this.createRigCamera(this.name + "_L", 0));
  15234. this._rigCameras.push(this.createRigCamera(this.name + "_R", 1));
  15235. }
  15236. switch (this.cameraRigMode) {
  15237. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  15238. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15239. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  15240. break;
  15241. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  15242. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  15243. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  15244. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  15245. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  15246. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  15247. break;
  15248. case Camera.RIG_MODE_VR:
  15249. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  15250. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  15251. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15252. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15253. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  15254. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  15255. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  15256. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  15257. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15258. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15259. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  15260. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  15261. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  15262. if (metrics.compensateDistortion) {
  15263. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  15264. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  15265. }
  15266. break;
  15267. case Camera.RIG_MODE_WEBVR:
  15268. if (rigParams.vrDisplay) {
  15269. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  15270. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  15271. //Left eye
  15272. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  15273. this._rigCameras[0].setCameraRigParameter("left", true);
  15274. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  15275. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  15276. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  15277. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15278. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15279. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15280. this._rigCameras[0].parent = this;
  15281. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  15282. //Right eye
  15283. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  15284. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  15285. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  15286. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  15287. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  15288. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  15289. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  15290. this._rigCameras[1].parent = this;
  15291. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  15292. }
  15293. break;
  15294. }
  15295. this._cascadePostProcessesToRigCams();
  15296. this.
  15297. update();
  15298. };
  15299. Camera.prototype._getVRProjectionMatrix = function () {
  15300. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  15301. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  15302. return this._projectionMatrix;
  15303. };
  15304. Camera.prototype._updateCameraRotationMatrix = function () {
  15305. //Here for WebVR
  15306. };
  15307. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  15308. //Here for WebVR
  15309. };
  15310. /**
  15311. * This function MUST be overwritten by the different WebVR cameras available.
  15312. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15313. */
  15314. Camera.prototype._getWebVRProjectionMatrix = function () {
  15315. return BABYLON.Matrix.Identity();
  15316. };
  15317. /**
  15318. * This function MUST be overwritten by the different WebVR cameras available.
  15319. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  15320. */
  15321. Camera.prototype._getWebVRViewMatrix = function () {
  15322. return BABYLON.Matrix.Identity();
  15323. };
  15324. Camera.prototype.setCameraRigParameter = function (name, value) {
  15325. if (!this._cameraRigParams) {
  15326. this._cameraRigParams = {};
  15327. }
  15328. this._cameraRigParams[name] = value;
  15329. //provisionnally:
  15330. if (name === "interaxialDistance") {
  15331. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  15332. }
  15333. };
  15334. /**
  15335. * needs to be overridden by children so sub has required properties to be copied
  15336. */
  15337. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  15338. return null;
  15339. };
  15340. /**
  15341. * May need to be overridden by children
  15342. */
  15343. Camera.prototype._updateRigCameras = function () {
  15344. for (var i = 0; i < this._rigCameras.length; i++) {
  15345. this._rigCameras[i].minZ = this.minZ;
  15346. this._rigCameras[i].maxZ = this.maxZ;
  15347. this._rigCameras[i].fov = this.fov;
  15348. }
  15349. // only update viewport when ANAGLYPH
  15350. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  15351. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  15352. }
  15353. };
  15354. Camera.prototype._setupInputs = function () {
  15355. };
  15356. Camera.prototype.serialize = function () {
  15357. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  15358. // Type
  15359. serializationObject.type = this.getClassName();
  15360. // Parent
  15361. if (this.parent) {
  15362. serializationObject.parentId = this.parent.id;
  15363. }
  15364. if (this.inputs) {
  15365. this.inputs.serialize(serializationObject);
  15366. }
  15367. // Animations
  15368. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  15369. serializationObject.ranges = this.serializeAnimationRanges();
  15370. return serializationObject;
  15371. };
  15372. Camera.prototype.clone = function (name) {
  15373. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  15374. };
  15375. Camera.prototype.getDirection = function (localAxis) {
  15376. var result = BABYLON.Vector3.Zero();
  15377. this.getDirectionToRef(localAxis, result);
  15378. return result;
  15379. };
  15380. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  15381. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  15382. };
  15383. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  15384. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  15385. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  15386. switch (type) {
  15387. case "ArcRotateCamera":
  15388. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  15389. case "DeviceOrientationCamera":
  15390. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  15391. case "FollowCamera":
  15392. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  15393. case "ArcFollowCamera":
  15394. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  15395. case "GamepadCamera":
  15396. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15397. case "TouchCamera":
  15398. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  15399. case "VirtualJoysticksCamera":
  15400. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  15401. case "WebVRFreeCamera":
  15402. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15403. case "WebVRGamepadCamera":
  15404. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15405. case "VRDeviceOrientationFreeCamera":
  15406. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  15407. case "VRDeviceOrientationGamepadCamera":
  15408. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  15409. case "AnaglyphArcRotateCamera":
  15410. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15411. case "AnaglyphFreeCamera":
  15412. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15413. case "AnaglyphGamepadCamera":
  15414. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15415. case "AnaglyphUniversalCamera":
  15416. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  15417. case "StereoscopicArcRotateCamera":
  15418. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15419. case "StereoscopicFreeCamera":
  15420. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15421. case "StereoscopicGamepadCamera":
  15422. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15423. case "StereoscopicUniversalCamera":
  15424. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  15425. case "FreeCamera":// Forcing Universal here
  15426. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15427. default:// Universal Camera is the default value
  15428. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  15429. }
  15430. };
  15431. Camera.Parse = function (parsedCamera, scene) {
  15432. var type = parsedCamera.type;
  15433. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  15434. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  15435. // Parent
  15436. if (parsedCamera.parentId) {
  15437. camera._waitingParentId = parsedCamera.parentId;
  15438. }
  15439. //If camera has an input manager, let it parse inputs settings
  15440. if (camera.inputs) {
  15441. camera.inputs.parse(parsedCamera);
  15442. camera._setupInputs();
  15443. }
  15444. if (camera.setPosition) {
  15445. camera.position.copyFromFloats(0, 0, 0);
  15446. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  15447. }
  15448. // Target
  15449. if (parsedCamera.target) {
  15450. if (camera.setTarget) {
  15451. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  15452. }
  15453. }
  15454. // Apply 3d rig, when found
  15455. if (parsedCamera.cameraRigMode) {
  15456. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  15457. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  15458. }
  15459. // Animations
  15460. if (parsedCamera.animations) {
  15461. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  15462. var parsedAnimation = parsedCamera.animations[animationIndex];
  15463. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  15464. }
  15465. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  15466. }
  15467. if (parsedCamera.autoAnimate) {
  15468. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  15469. }
  15470. return camera;
  15471. };
  15472. // Statics
  15473. Camera._PERSPECTIVE_CAMERA = 0;
  15474. Camera._ORTHOGRAPHIC_CAMERA = 1;
  15475. Camera._FOVMODE_VERTICAL_FIXED = 0;
  15476. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  15477. Camera._RIG_MODE_NONE = 0;
  15478. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  15479. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  15480. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  15481. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  15482. Camera._RIG_MODE_VR = 20;
  15483. Camera._RIG_MODE_WEBVR = 21;
  15484. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  15485. __decorate([
  15486. BABYLON.serializeAsVector3()
  15487. ], Camera.prototype, "position", void 0);
  15488. __decorate([
  15489. BABYLON.serializeAsVector3()
  15490. ], Camera.prototype, "upVector", void 0);
  15491. __decorate([
  15492. BABYLON.serialize()
  15493. ], Camera.prototype, "orthoLeft", void 0);
  15494. __decorate([
  15495. BABYLON.serialize()
  15496. ], Camera.prototype, "orthoRight", void 0);
  15497. __decorate([
  15498. BABYLON.serialize()
  15499. ], Camera.prototype, "orthoBottom", void 0);
  15500. __decorate([
  15501. BABYLON.serialize()
  15502. ], Camera.prototype, "orthoTop", void 0);
  15503. __decorate([
  15504. BABYLON.serialize()
  15505. ], Camera.prototype, "fov", void 0);
  15506. __decorate([
  15507. BABYLON.serialize()
  15508. ], Camera.prototype, "minZ", void 0);
  15509. __decorate([
  15510. BABYLON.serialize()
  15511. ], Camera.prototype, "maxZ", void 0);
  15512. __decorate([
  15513. BABYLON.serialize()
  15514. ], Camera.prototype, "inertia", void 0);
  15515. __decorate([
  15516. BABYLON.serialize()
  15517. ], Camera.prototype, "mode", void 0);
  15518. __decorate([
  15519. BABYLON.serialize()
  15520. ], Camera.prototype, "layerMask", void 0);
  15521. __decorate([
  15522. BABYLON.serialize()
  15523. ], Camera.prototype, "fovMode", void 0);
  15524. __decorate([
  15525. BABYLON.serialize()
  15526. ], Camera.prototype, "cameraRigMode", void 0);
  15527. __decorate([
  15528. BABYLON.serialize()
  15529. ], Camera.prototype, "interaxialDistance", void 0);
  15530. __decorate([
  15531. BABYLON.serialize()
  15532. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  15533. return Camera;
  15534. }(BABYLON.Node));
  15535. BABYLON.Camera = Camera;
  15536. })(BABYLON || (BABYLON = {}));
  15537. //# sourceMappingURL=babylon.camera.js.map
  15538. var BABYLON;
  15539. (function (BABYLON) {
  15540. var RenderingManager = (function () {
  15541. function RenderingManager(scene) {
  15542. this._renderingGroups = new Array();
  15543. this._autoClearDepthStencil = {};
  15544. this._customOpaqueSortCompareFn = {};
  15545. this._customAlphaTestSortCompareFn = {};
  15546. this._customTransparentSortCompareFn = {};
  15547. this._renderinGroupInfo = null;
  15548. this._scene = scene;
  15549. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  15550. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  15551. }
  15552. }
  15553. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  15554. if (depth === void 0) { depth = true; }
  15555. if (stencil === void 0) { stencil = true; }
  15556. if (this._depthStencilBufferAlreadyCleaned) {
  15557. return;
  15558. }
  15559. this._scene.getEngine().clear(null, false, depth, stencil);
  15560. this._depthStencilBufferAlreadyCleaned = true;
  15561. };
  15562. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  15563. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  15564. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  15565. var info = null;
  15566. if (observable) {
  15567. if (!this._renderinGroupInfo) {
  15568. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  15569. }
  15570. info = this._renderinGroupInfo;
  15571. info.scene = this._scene;
  15572. info.camera = this._scene.activeCamera;
  15573. }
  15574. // Dispatch sprites
  15575. if (renderSprites) {
  15576. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  15577. var manager = this._scene.spriteManagers[index];
  15578. this.dispatchSprites(manager);
  15579. }
  15580. }
  15581. // Render
  15582. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15583. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  15584. var renderingGroup = this._renderingGroups[index];
  15585. if (!renderingGroup && !observable)
  15586. continue;
  15587. this._currentIndex = index;
  15588. var renderingGroupMask = 0;
  15589. // Fire PRECLEAR stage
  15590. if (observable) {
  15591. renderingGroupMask = Math.pow(2, index);
  15592. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  15593. info.renderingGroupId = index;
  15594. observable.notifyObservers(info, renderingGroupMask);
  15595. }
  15596. // Clear depth/stencil if needed
  15597. if (RenderingManager.AUTOCLEAR) {
  15598. var autoClear = this._autoClearDepthStencil[index];
  15599. if (autoClear && autoClear.autoClear) {
  15600. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  15601. }
  15602. }
  15603. if (observable) {
  15604. // Fire PREOPAQUE stage
  15605. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  15606. observable.notifyObservers(info, renderingGroupMask);
  15607. // Fire PRETRANSPARENT stage
  15608. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  15609. observable.notifyObservers(info, renderingGroupMask);
  15610. }
  15611. if (renderingGroup)
  15612. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  15613. // Fire POSTTRANSPARENT stage
  15614. if (observable) {
  15615. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  15616. observable.notifyObservers(info, renderingGroupMask);
  15617. }
  15618. }
  15619. };
  15620. RenderingManager.prototype.reset = function () {
  15621. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15622. var renderingGroup = this._renderingGroups[index];
  15623. if (renderingGroup) {
  15624. renderingGroup.prepare();
  15625. }
  15626. }
  15627. };
  15628. RenderingManager.prototype.dispose = function () {
  15629. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  15630. var renderingGroup = this._renderingGroups[index];
  15631. if (renderingGroup) {
  15632. renderingGroup.dispose();
  15633. }
  15634. }
  15635. this._renderingGroups.length = 0;
  15636. };
  15637. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  15638. if (!this._renderingGroups[renderingGroupId]) {
  15639. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  15640. }
  15641. };
  15642. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  15643. var renderingGroupId = spriteManager.renderingGroupId || 0;
  15644. this._prepareRenderingGroup(renderingGroupId);
  15645. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  15646. };
  15647. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  15648. var renderingGroupId = particleSystem.renderingGroupId || 0;
  15649. this._prepareRenderingGroup(renderingGroupId);
  15650. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  15651. };
  15652. RenderingManager.prototype.dispatch = function (subMesh) {
  15653. var mesh = subMesh.getMesh();
  15654. var renderingGroupId = mesh.renderingGroupId || 0;
  15655. this._prepareRenderingGroup(renderingGroupId);
  15656. this._renderingGroups[renderingGroupId].dispatch(subMesh);
  15657. };
  15658. /**
  15659. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  15660. * This allowed control for front to back rendering or reversly depending of the special needs.
  15661. *
  15662. * @param renderingGroupId The rendering group id corresponding to its index
  15663. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  15664. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  15665. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  15666. */
  15667. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15668. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15669. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15670. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15671. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  15672. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  15673. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  15674. if (this._renderingGroups[renderingGroupId]) {
  15675. var group = this._renderingGroups[renderingGroupId];
  15676. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  15677. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  15678. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  15679. }
  15680. };
  15681. /**
  15682. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  15683. *
  15684. * @param renderingGroupId The rendering group id corresponding to its index
  15685. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  15686. * @param depth Automatically clears depth between groups if true and autoClear is true.
  15687. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  15688. */
  15689. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  15690. if (depth === void 0) { depth = true; }
  15691. if (stencil === void 0) { stencil = true; }
  15692. this._autoClearDepthStencil[renderingGroupId] = {
  15693. autoClear: autoClearDepthStencil,
  15694. depth: depth,
  15695. stencil: stencil
  15696. };
  15697. };
  15698. /**
  15699. * The max id used for rendering groups (not included)
  15700. */
  15701. RenderingManager.MAX_RENDERINGGROUPS = 4;
  15702. /**
  15703. * The min id used for rendering groups (included)
  15704. */
  15705. RenderingManager.MIN_RENDERINGGROUPS = 0;
  15706. /**
  15707. * Used to globally prevent autoclearing scenes.
  15708. */
  15709. RenderingManager.AUTOCLEAR = true;
  15710. return RenderingManager;
  15711. }());
  15712. BABYLON.RenderingManager = RenderingManager;
  15713. })(BABYLON || (BABYLON = {}));
  15714. //# sourceMappingURL=babylon.renderingManager.js.map
  15715. var BABYLON;
  15716. (function (BABYLON) {
  15717. var RenderingGroup = (function () {
  15718. /**
  15719. * Creates a new rendering group.
  15720. * @param index The rendering group index
  15721. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  15722. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  15723. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  15724. */
  15725. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  15726. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  15727. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  15728. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  15729. this.index = index;
  15730. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  15731. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  15732. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  15733. this._particleSystems = new BABYLON.SmartArray(256);
  15734. this._spriteManagers = new BABYLON.SmartArray(256);
  15735. this._edgesRenderers = new BABYLON.SmartArray(16);
  15736. this._scene = scene;
  15737. this.opaqueSortCompareFn = opaqueSortCompareFn;
  15738. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  15739. this.transparentSortCompareFn = transparentSortCompareFn;
  15740. }
  15741. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  15742. /**
  15743. * Set the opaque sort comparison function.
  15744. * If null the sub meshes will be render in the order they were created
  15745. */
  15746. set: function (value) {
  15747. this._opaqueSortCompareFn = value;
  15748. if (value) {
  15749. this._renderOpaque = this.renderOpaqueSorted;
  15750. }
  15751. else {
  15752. this._renderOpaque = RenderingGroup.renderUnsorted;
  15753. }
  15754. },
  15755. enumerable: true,
  15756. configurable: true
  15757. });
  15758. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  15759. /**
  15760. * Set the alpha test sort comparison function.
  15761. * If null the sub meshes will be render in the order they were created
  15762. */
  15763. set: function (value) {
  15764. this._alphaTestSortCompareFn = value;
  15765. if (value) {
  15766. this._renderAlphaTest = this.renderAlphaTestSorted;
  15767. }
  15768. else {
  15769. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  15770. }
  15771. },
  15772. enumerable: true,
  15773. configurable: true
  15774. });
  15775. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  15776. /**
  15777. * Set the transparent sort comparison function.
  15778. * If null the sub meshes will be render in the order they were created
  15779. */
  15780. set: function (value) {
  15781. if (value) {
  15782. this._transparentSortCompareFn = value;
  15783. }
  15784. else {
  15785. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  15786. }
  15787. this._renderTransparent = this.renderTransparentSorted;
  15788. },
  15789. enumerable: true,
  15790. configurable: true
  15791. });
  15792. /**
  15793. * Render all the sub meshes contained in the group.
  15794. * @param customRenderFunction Used to override the default render behaviour of the group.
  15795. * @returns true if rendered some submeshes.
  15796. */
  15797. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  15798. if (customRenderFunction) {
  15799. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes);
  15800. return;
  15801. }
  15802. var engine = this._scene.getEngine();
  15803. // Opaque
  15804. if (this._opaqueSubMeshes.length !== 0) {
  15805. this._renderOpaque(this._opaqueSubMeshes);
  15806. }
  15807. // Alpha test
  15808. if (this._alphaTestSubMeshes.length !== 0) {
  15809. engine.setAlphaTesting(true);
  15810. this._renderAlphaTest(this._alphaTestSubMeshes);
  15811. engine.setAlphaTesting(false);
  15812. }
  15813. var stencilState = engine.getStencilBuffer();
  15814. engine.setStencilBuffer(false);
  15815. // Sprites
  15816. if (renderSprites) {
  15817. this._renderSprites();
  15818. }
  15819. // Particles
  15820. if (renderParticles) {
  15821. this._renderParticles(activeMeshes);
  15822. }
  15823. if (this.onBeforeTransparentRendering) {
  15824. this.onBeforeTransparentRendering();
  15825. }
  15826. // Transparent
  15827. if (this._transparentSubMeshes.length !== 0) {
  15828. this._renderTransparent(this._transparentSubMeshes);
  15829. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  15830. }
  15831. // Set back stencil to false in case it changes before the edge renderer.
  15832. engine.setStencilBuffer(false);
  15833. // Edges
  15834. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  15835. this._edgesRenderers.data[edgesRendererIndex].render();
  15836. }
  15837. // Restore Stencil state.
  15838. engine.setStencilBuffer(stencilState);
  15839. };
  15840. /**
  15841. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  15842. * @param subMeshes The submeshes to render
  15843. */
  15844. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  15845. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15846. };
  15847. /**
  15848. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  15849. * @param subMeshes The submeshes to render
  15850. */
  15851. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  15852. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera.globalPosition, false);
  15853. };
  15854. /**
  15855. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  15856. * @param subMeshes The submeshes to render
  15857. */
  15858. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  15859. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera.globalPosition, true);
  15860. };
  15861. /**
  15862. * Renders the submeshes in a specified order.
  15863. * @param subMeshes The submeshes to sort before render
  15864. * @param sortCompareFn The comparison function use to sort
  15865. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  15866. * @param transparent Specifies to activate blending if true
  15867. */
  15868. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, cameraPosition, transparent) {
  15869. var subIndex = 0;
  15870. var subMesh;
  15871. for (; subIndex < subMeshes.length; subIndex++) {
  15872. subMesh = subMeshes.data[subIndex];
  15873. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  15874. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  15875. }
  15876. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  15877. sortedArray.sort(sortCompareFn);
  15878. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  15879. subMesh = sortedArray[subIndex];
  15880. subMesh.render(transparent);
  15881. }
  15882. };
  15883. /**
  15884. * Renders the submeshes in the order they were dispatched (no sort applied).
  15885. * @param subMeshes The submeshes to render
  15886. */
  15887. RenderingGroup.renderUnsorted = function (subMeshes) {
  15888. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  15889. var submesh = subMeshes.data[subIndex];
  15890. submesh.render(false);
  15891. }
  15892. };
  15893. /**
  15894. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15895. * are rendered back to front if in the same alpha index.
  15896. *
  15897. * @param a The first submesh
  15898. * @param b The second submesh
  15899. * @returns The result of the comparison
  15900. */
  15901. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  15902. // Alpha index first
  15903. if (a._alphaIndex > b._alphaIndex) {
  15904. return 1;
  15905. }
  15906. if (a._alphaIndex < b._alphaIndex) {
  15907. return -1;
  15908. }
  15909. // Then distance to camera
  15910. return RenderingGroup.backToFrontSortCompare(a, b);
  15911. };
  15912. /**
  15913. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15914. * are rendered back to front.
  15915. *
  15916. * @param a The first submesh
  15917. * @param b The second submesh
  15918. * @returns The result of the comparison
  15919. */
  15920. RenderingGroup.backToFrontSortCompare = function (a, b) {
  15921. // Then distance to camera
  15922. if (a._distanceToCamera < b._distanceToCamera) {
  15923. return 1;
  15924. }
  15925. if (a._distanceToCamera > b._distanceToCamera) {
  15926. return -1;
  15927. }
  15928. return 0;
  15929. };
  15930. /**
  15931. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  15932. * are rendered front to back (prevent overdraw).
  15933. *
  15934. * @param a The first submesh
  15935. * @param b The second submesh
  15936. * @returns The result of the comparison
  15937. */
  15938. RenderingGroup.frontToBackSortCompare = function (a, b) {
  15939. // Then distance to camera
  15940. if (a._distanceToCamera < b._distanceToCamera) {
  15941. return -1;
  15942. }
  15943. if (a._distanceToCamera > b._distanceToCamera) {
  15944. return 1;
  15945. }
  15946. return 0;
  15947. };
  15948. /**
  15949. * Resets the different lists of submeshes to prepare a new frame.
  15950. */
  15951. RenderingGroup.prototype.prepare = function () {
  15952. this._opaqueSubMeshes.reset();
  15953. this._transparentSubMeshes.reset();
  15954. this._alphaTestSubMeshes.reset();
  15955. this._particleSystems.reset();
  15956. this._spriteManagers.reset();
  15957. this._edgesRenderers.reset();
  15958. };
  15959. RenderingGroup.prototype.dispose = function () {
  15960. this._opaqueSubMeshes.dispose();
  15961. this._transparentSubMeshes.dispose();
  15962. this._alphaTestSubMeshes.dispose();
  15963. this._particleSystems.dispose();
  15964. this._spriteManagers.dispose();
  15965. this._edgesRenderers.dispose();
  15966. };
  15967. /**
  15968. * Inserts the submesh in its correct queue depending on its material.
  15969. * @param subMesh The submesh to dispatch
  15970. */
  15971. RenderingGroup.prototype.dispatch = function (subMesh) {
  15972. var material = subMesh.getMaterial();
  15973. var mesh = subMesh.getMesh();
  15974. if (material.needAlphaBlending() || mesh.visibility < 1.0 || mesh.hasVertexAlpha) {
  15975. this._transparentSubMeshes.push(subMesh);
  15976. }
  15977. else if (material.needAlphaTesting()) {
  15978. this._alphaTestSubMeshes.push(subMesh);
  15979. }
  15980. else {
  15981. this._opaqueSubMeshes.push(subMesh); // Opaque
  15982. }
  15983. if (mesh._edgesRenderer) {
  15984. this._edgesRenderers.push(mesh._edgesRenderer);
  15985. }
  15986. };
  15987. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  15988. this._spriteManagers.push(spriteManager);
  15989. };
  15990. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  15991. this._particleSystems.push(particleSystem);
  15992. };
  15993. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  15994. if (this._particleSystems.length === 0) {
  15995. return;
  15996. }
  15997. // Particles
  15998. var activeCamera = this._scene.activeCamera;
  15999. this._scene._particlesDuration.beginMonitoring();
  16000. for (var particleIndex = 0; particleIndex < this._scene._activeParticleSystems.length; particleIndex++) {
  16001. var particleSystem = this._scene._activeParticleSystems.data[particleIndex];
  16002. if ((activeCamera.layerMask & particleSystem.layerMask) === 0) {
  16003. continue;
  16004. }
  16005. var emitter = particleSystem.emitter;
  16006. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  16007. this._scene._activeParticles.addCount(particleSystem.render(), false);
  16008. }
  16009. }
  16010. this._scene._particlesDuration.endMonitoring(false);
  16011. };
  16012. RenderingGroup.prototype._renderSprites = function () {
  16013. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  16014. return;
  16015. }
  16016. // Sprites
  16017. var activeCamera = this._scene.activeCamera;
  16018. this._scene._spritesDuration.beginMonitoring();
  16019. for (var id = 0; id < this._spriteManagers.length; id++) {
  16020. var spriteManager = this._spriteManagers.data[id];
  16021. if (((activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  16022. spriteManager.render();
  16023. }
  16024. }
  16025. this._scene._spritesDuration.endMonitoring(false);
  16026. };
  16027. return RenderingGroup;
  16028. }());
  16029. BABYLON.RenderingGroup = RenderingGroup;
  16030. })(BABYLON || (BABYLON = {}));
  16031. //# sourceMappingURL=babylon.renderingGroup.js.map
  16032. var BABYLON;
  16033. (function (BABYLON) {
  16034. var ClickInfo = (function () {
  16035. function ClickInfo() {
  16036. this._singleClick = false;
  16037. this._doubleClick = false;
  16038. this._hasSwiped = false;
  16039. this._ignore = false;
  16040. }
  16041. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  16042. get: function () {
  16043. return this._singleClick;
  16044. },
  16045. set: function (b) {
  16046. this._singleClick = b;
  16047. },
  16048. enumerable: true,
  16049. configurable: true
  16050. });
  16051. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  16052. get: function () {
  16053. return this._doubleClick;
  16054. },
  16055. set: function (b) {
  16056. this._doubleClick = b;
  16057. },
  16058. enumerable: true,
  16059. configurable: true
  16060. });
  16061. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  16062. get: function () {
  16063. return this._hasSwiped;
  16064. },
  16065. set: function (b) {
  16066. this._hasSwiped = b;
  16067. },
  16068. enumerable: true,
  16069. configurable: true
  16070. });
  16071. Object.defineProperty(ClickInfo.prototype, "ignore", {
  16072. get: function () {
  16073. return this._ignore;
  16074. },
  16075. set: function (b) {
  16076. this._ignore = b;
  16077. },
  16078. enumerable: true,
  16079. configurable: true
  16080. });
  16081. return ClickInfo;
  16082. }());
  16083. var PointerEventTypes = (function () {
  16084. function PointerEventTypes() {
  16085. }
  16086. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  16087. get: function () {
  16088. return PointerEventTypes._POINTERDOWN;
  16089. },
  16090. enumerable: true,
  16091. configurable: true
  16092. });
  16093. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  16094. get: function () {
  16095. return PointerEventTypes._POINTERUP;
  16096. },
  16097. enumerable: true,
  16098. configurable: true
  16099. });
  16100. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  16101. get: function () {
  16102. return PointerEventTypes._POINTERMOVE;
  16103. },
  16104. enumerable: true,
  16105. configurable: true
  16106. });
  16107. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  16108. get: function () {
  16109. return PointerEventTypes._POINTERWHEEL;
  16110. },
  16111. enumerable: true,
  16112. configurable: true
  16113. });
  16114. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  16115. get: function () {
  16116. return PointerEventTypes._POINTERPICK;
  16117. },
  16118. enumerable: true,
  16119. configurable: true
  16120. });
  16121. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  16122. get: function () {
  16123. return PointerEventTypes._POINTERTAP;
  16124. },
  16125. enumerable: true,
  16126. configurable: true
  16127. });
  16128. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  16129. get: function () {
  16130. return PointerEventTypes._POINTERDOUBLETAP;
  16131. },
  16132. enumerable: true,
  16133. configurable: true
  16134. });
  16135. PointerEventTypes._POINTERDOWN = 0x01;
  16136. PointerEventTypes._POINTERUP = 0x02;
  16137. PointerEventTypes._POINTERMOVE = 0x04;
  16138. PointerEventTypes._POINTERWHEEL = 0x08;
  16139. PointerEventTypes._POINTERPICK = 0x10;
  16140. PointerEventTypes._POINTERTAP = 0x20;
  16141. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  16142. return PointerEventTypes;
  16143. }());
  16144. BABYLON.PointerEventTypes = PointerEventTypes;
  16145. var PointerInfoBase = (function () {
  16146. function PointerInfoBase(type, event) {
  16147. this.type = type;
  16148. this.event = event;
  16149. }
  16150. return PointerInfoBase;
  16151. }());
  16152. BABYLON.PointerInfoBase = PointerInfoBase;
  16153. /**
  16154. * This class is used to store pointer related info for the onPrePointerObservable event.
  16155. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  16156. */
  16157. var PointerInfoPre = (function (_super) {
  16158. __extends(PointerInfoPre, _super);
  16159. function PointerInfoPre(type, event, localX, localY) {
  16160. var _this = _super.call(this, type, event) || this;
  16161. _this.skipOnPointerObservable = false;
  16162. _this.localPosition = new BABYLON.Vector2(localX, localY);
  16163. return _this;
  16164. }
  16165. return PointerInfoPre;
  16166. }(PointerInfoBase));
  16167. BABYLON.PointerInfoPre = PointerInfoPre;
  16168. /**
  16169. * This type contains all the data related to a pointer event in Babylon.js.
  16170. * 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.
  16171. */
  16172. var PointerInfo = (function (_super) {
  16173. __extends(PointerInfo, _super);
  16174. function PointerInfo(type, event, pickInfo) {
  16175. var _this = _super.call(this, type, event) || this;
  16176. _this.pickInfo = pickInfo;
  16177. return _this;
  16178. }
  16179. return PointerInfo;
  16180. }(PointerInfoBase));
  16181. BABYLON.PointerInfo = PointerInfo;
  16182. /**
  16183. * This class is used by the onRenderingGroupObservable
  16184. */
  16185. var RenderingGroupInfo = (function () {
  16186. function RenderingGroupInfo() {
  16187. }
  16188. /**
  16189. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  16190. * This stage will be fired no matter what
  16191. */
  16192. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  16193. /**
  16194. * Called before opaque object are rendered.
  16195. * This stage will be fired only if there's 3D Opaque content to render
  16196. */
  16197. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  16198. /**
  16199. * Called after the opaque objects are rendered and before the transparent ones
  16200. * This stage will be fired only if there's 3D transparent content to render
  16201. */
  16202. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  16203. /**
  16204. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  16205. * This stage will be fired no matter what
  16206. */
  16207. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  16208. return RenderingGroupInfo;
  16209. }());
  16210. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  16211. /**
  16212. * Represents a scene to be rendered by the engine.
  16213. * @see http://doc.babylonjs.com/page.php?p=21911
  16214. */
  16215. var Scene = (function () {
  16216. /**
  16217. * @constructor
  16218. * @param {BABYLON.Engine} engine - the engine to be used to render this scene.
  16219. */
  16220. function Scene(engine) {
  16221. // Members
  16222. this.autoClear = true;
  16223. this.autoClearDepthAndStencil = true;
  16224. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  16225. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  16226. this.forceWireframe = false;
  16227. this._forcePointsCloud = false;
  16228. this.forceShowBoundingBoxes = false;
  16229. this.animationsEnabled = true;
  16230. this.constantlyUpdateMeshUnderPointer = false;
  16231. this.hoverCursor = "pointer";
  16232. this.defaultCursor = "";
  16233. // Metadata
  16234. this.metadata = null;
  16235. // Events
  16236. /**
  16237. * An event triggered when the scene is disposed.
  16238. * @type {BABYLON.Observable}
  16239. */
  16240. this.onDisposeObservable = new BABYLON.Observable();
  16241. /**
  16242. * An event triggered before rendering the scene
  16243. * @type {BABYLON.Observable}
  16244. */
  16245. this.onBeforeRenderObservable = new BABYLON.Observable();
  16246. /**
  16247. * An event triggered after rendering the scene
  16248. * @type {BABYLON.Observable}
  16249. */
  16250. this.onAfterRenderObservable = new BABYLON.Observable();
  16251. /**
  16252. * An event triggered when the scene is ready
  16253. * @type {BABYLON.Observable}
  16254. */
  16255. this.onReadyObservable = new BABYLON.Observable();
  16256. /**
  16257. * An event triggered before rendering a camera
  16258. * @type {BABYLON.Observable}
  16259. */
  16260. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  16261. /**
  16262. * An event triggered after rendering a camera
  16263. * @type {BABYLON.Observable}
  16264. */
  16265. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  16266. /**
  16267. * An event triggered when a camera is created
  16268. * @type {BABYLON.Observable}
  16269. */
  16270. this.onNewCameraAddedObservable = new BABYLON.Observable();
  16271. /**
  16272. * An event triggered when a camera is removed
  16273. * @type {BABYLON.Observable}
  16274. */
  16275. this.onCameraRemovedObservable = new BABYLON.Observable();
  16276. /**
  16277. * An event triggered when a light is created
  16278. * @type {BABYLON.Observable}
  16279. */
  16280. this.onNewLightAddedObservable = new BABYLON.Observable();
  16281. /**
  16282. * An event triggered when a light is removed
  16283. * @type {BABYLON.Observable}
  16284. */
  16285. this.onLightRemovedObservable = new BABYLON.Observable();
  16286. /**
  16287. * An event triggered when a geometry is created
  16288. * @type {BABYLON.Observable}
  16289. */
  16290. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  16291. /**
  16292. * An event triggered when a geometry is removed
  16293. * @type {BABYLON.Observable}
  16294. */
  16295. this.onGeometryRemovedObservable = new BABYLON.Observable();
  16296. /**
  16297. * An event triggered when a mesh is created
  16298. * @type {BABYLON.Observable}
  16299. */
  16300. this.onNewMeshAddedObservable = new BABYLON.Observable();
  16301. /**
  16302. * An event triggered when a mesh is removed
  16303. * @type {BABYLON.Observable}
  16304. */
  16305. this.onMeshRemovedObservable = new BABYLON.Observable();
  16306. /**
  16307. * An event triggered before calculating deterministic simulation step
  16308. * @type {BABYLON.Observable}
  16309. */
  16310. this.onBeforeStepObservable = new BABYLON.Observable();
  16311. /**
  16312. * An event triggered after calculating deterministic simulation step
  16313. * @type {BABYLON.Observable}
  16314. */
  16315. this.onAfterStepObservable = new BABYLON.Observable();
  16316. /**
  16317. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  16318. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  16319. * 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)
  16320. */
  16321. this.onRenderingGroupObservable = new BABYLON.Observable();
  16322. // Animations
  16323. this.animations = [];
  16324. /**
  16325. * 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).
  16326. * You have the possibility to skip the 3D Engine process and the call to onPointerObservable by setting PointerInfoBase.skipOnPointerObservable to true
  16327. */
  16328. this.onPrePointerObservable = new BABYLON.Observable();
  16329. /**
  16330. * Observable event triggered each time an input event is received from the rendering canvas
  16331. */
  16332. this.onPointerObservable = new BABYLON.Observable();
  16333. this._meshPickProceed = false;
  16334. this._previousHasSwiped = false;
  16335. this._currentPickResult = null;
  16336. this._previousPickResult = null;
  16337. this._isButtonPressed = false;
  16338. this._doubleClickOccured = false;
  16339. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  16340. this.cameraToUseForPointers = null;
  16341. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  16342. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  16343. this._startingPointerTime = 0;
  16344. this._previousStartingPointerTime = 0;
  16345. // Deterministic lockstep
  16346. this._timeAccumulator = 0;
  16347. this._currentStepId = 0;
  16348. this._currentInternalStep = 0;
  16349. // Coordinate system
  16350. /**
  16351. * use right-handed coordinate system on this scene.
  16352. * @type {boolean}
  16353. */
  16354. this._useRightHandedSystem = false;
  16355. // Fog
  16356. this._fogEnabled = true;
  16357. this._fogMode = Scene.FOGMODE_NONE;
  16358. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  16359. this.fogDensity = 0.1;
  16360. this.fogStart = 0;
  16361. this.fogEnd = 1000.0;
  16362. // Lights
  16363. /**
  16364. * is shadow enabled on this scene.
  16365. * @type {boolean}
  16366. */
  16367. this._shadowsEnabled = true;
  16368. /**
  16369. * is light enabled on this scene.
  16370. * @type {boolean}
  16371. */
  16372. this._lightsEnabled = true;
  16373. /**
  16374. * All of the lights added to this scene.
  16375. * @see BABYLON.Light
  16376. * @type {BABYLON.Light[]}
  16377. */
  16378. this.lights = new Array();
  16379. // Cameras
  16380. /** All of the cameras added to this scene. */
  16381. this.cameras = new Array();
  16382. /** All of the active cameras added to this scene. */
  16383. this.activeCameras = new Array();
  16384. // Meshes
  16385. /**
  16386. * All of the (abstract) meshes added to this scene.
  16387. * @see BABYLON.AbstractMesh
  16388. * @type {BABYLON.AbstractMesh[]}
  16389. */
  16390. this.meshes = new Array();
  16391. // Geometries
  16392. this._geometries = new Array();
  16393. this.materials = new Array();
  16394. this.multiMaterials = new Array();
  16395. // Textures
  16396. this._texturesEnabled = true;
  16397. this.textures = new Array();
  16398. // Particles
  16399. this.particlesEnabled = true;
  16400. this.particleSystems = new Array();
  16401. // Sprites
  16402. this.spritesEnabled = true;
  16403. this.spriteManagers = new Array();
  16404. // Layers
  16405. this.layers = new Array();
  16406. this.highlightLayers = new Array();
  16407. // Skeletons
  16408. this._skeletonsEnabled = true;
  16409. this.skeletons = new Array();
  16410. // Morph targets
  16411. this.morphTargetManagers = new Array();
  16412. // Lens flares
  16413. this.lensFlaresEnabled = true;
  16414. this.lensFlareSystems = new Array();
  16415. // Collisions
  16416. this.collisionsEnabled = true;
  16417. /** Defines the gravity applied to this scene */
  16418. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  16419. // Postprocesses
  16420. this.postProcesses = new Array();
  16421. this.postProcessesEnabled = true;
  16422. // Customs render targets
  16423. this.renderTargetsEnabled = true;
  16424. this.dumpNextRenderTargets = false;
  16425. this.customRenderTargets = new Array();
  16426. // Imported meshes
  16427. this.importedMeshesFiles = new Array();
  16428. // Probes
  16429. this.probesEnabled = true;
  16430. this.reflectionProbes = new Array();
  16431. this._actionManagers = new Array();
  16432. this._meshesForIntersections = new BABYLON.SmartArray(256);
  16433. // Procedural textures
  16434. this.proceduralTexturesEnabled = true;
  16435. this._proceduralTextures = new Array();
  16436. this.soundTracks = new Array();
  16437. this._audioEnabled = true;
  16438. this._headphone = false;
  16439. // Performance counters
  16440. this._totalMeshesCounter = new BABYLON.PerfCounter();
  16441. this._totalLightsCounter = new BABYLON.PerfCounter();
  16442. this._totalMaterialsCounter = new BABYLON.PerfCounter();
  16443. this._totalTexturesCounter = new BABYLON.PerfCounter();
  16444. this._totalVertices = new BABYLON.PerfCounter();
  16445. this._activeIndices = new BABYLON.PerfCounter();
  16446. this._activeParticles = new BABYLON.PerfCounter();
  16447. this._lastFrameDuration = new BABYLON.PerfCounter();
  16448. this._evaluateActiveMeshesDuration = new BABYLON.PerfCounter();
  16449. this._renderTargetsDuration = new BABYLON.PerfCounter();
  16450. this._particlesDuration = new BABYLON.PerfCounter();
  16451. this._renderDuration = new BABYLON.PerfCounter();
  16452. this._spritesDuration = new BABYLON.PerfCounter();
  16453. this._activeBones = new BABYLON.PerfCounter();
  16454. this._animationTime = 0;
  16455. this.animationTimeScale = 1;
  16456. this._renderId = 0;
  16457. this._executeWhenReadyTimeoutId = -1;
  16458. this._intermediateRendering = false;
  16459. this._viewUpdateFlag = -1;
  16460. this._projectionUpdateFlag = -1;
  16461. this._toBeDisposed = new BABYLON.SmartArray(256);
  16462. this._pendingData = []; //ANY
  16463. this._activeMeshes = new BABYLON.SmartArray(256);
  16464. this._processedMaterials = new BABYLON.SmartArray(256);
  16465. this._renderTargets = new BABYLON.SmartArray(256);
  16466. this._activeParticleSystems = new BABYLON.SmartArray(256);
  16467. this._activeSkeletons = new BABYLON.SmartArray(32);
  16468. this._softwareSkinnedMeshes = new BABYLON.SmartArray(32);
  16469. this._activeAnimatables = new Array();
  16470. this._transformMatrix = BABYLON.Matrix.Zero();
  16471. this.requireLightSorting = false;
  16472. this._uniqueIdCounter = 0;
  16473. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  16474. this._engine.scenes.push(this);
  16475. this._uid = null;
  16476. this._renderingManager = new BABYLON.RenderingManager(this);
  16477. this.postProcessManager = new BABYLON.PostProcessManager(this);
  16478. if (BABYLON.OutlineRenderer) {
  16479. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  16480. }
  16481. this.attachControl();
  16482. if (BABYLON.SoundTrack) {
  16483. this.mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  16484. }
  16485. //simplification queue
  16486. if (BABYLON.SimplificationQueue) {
  16487. this.simplificationQueue = new BABYLON.SimplificationQueue();
  16488. }
  16489. //collision coordinator initialization. For now legacy per default.
  16490. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  16491. // Uniform Buffer
  16492. this._createUbo();
  16493. // Default Image processing definition.
  16494. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  16495. }
  16496. Object.defineProperty(Scene, "FOGMODE_NONE", {
  16497. /** The fog is deactivated */
  16498. get: function () {
  16499. return Scene._FOGMODE_NONE;
  16500. },
  16501. enumerable: true,
  16502. configurable: true
  16503. });
  16504. Object.defineProperty(Scene, "FOGMODE_EXP", {
  16505. /** The fog density is following an exponential function */
  16506. get: function () {
  16507. return Scene._FOGMODE_EXP;
  16508. },
  16509. enumerable: true,
  16510. configurable: true
  16511. });
  16512. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  16513. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  16514. get: function () {
  16515. return Scene._FOGMODE_EXP2;
  16516. },
  16517. enumerable: true,
  16518. configurable: true
  16519. });
  16520. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  16521. /** The fog density is following a linear function. */
  16522. get: function () {
  16523. return Scene._FOGMODE_LINEAR;
  16524. },
  16525. enumerable: true,
  16526. configurable: true
  16527. });
  16528. Object.defineProperty(Scene.prototype, "environmentTexture", {
  16529. /**
  16530. * Texture used in all pbr material as the reflection texture.
  16531. * As in the majority of the scene they are the same (exception for multi room and so on),
  16532. * this is easier to reference from here than from all the materials.
  16533. */
  16534. get: function () {
  16535. return this._environmentTexture;
  16536. },
  16537. /**
  16538. * Texture used in all pbr material as the reflection texture.
  16539. * As in the majority of the scene they are the same (exception for multi room and so on),
  16540. * this is easier to set here than in all the materials.
  16541. */
  16542. set: function (value) {
  16543. this._environmentTexture = value;
  16544. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16545. },
  16546. enumerable: true,
  16547. configurable: true
  16548. });
  16549. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  16550. /**
  16551. * Default image processing configuration used either in the rendering
  16552. * Forward main pass or through the imageProcessingPostProcess if present.
  16553. * As in the majority of the scene they are the same (exception for multi camera),
  16554. * this is easier to reference from here than from all the materials and post process.
  16555. *
  16556. * No setter as we it is a shared configuration, you can set the values instead.
  16557. */
  16558. get: function () {
  16559. return this._imageProcessingConfiguration;
  16560. },
  16561. enumerable: true,
  16562. configurable: true
  16563. });
  16564. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  16565. get: function () {
  16566. return this._forcePointsCloud;
  16567. },
  16568. set: function (value) {
  16569. if (this._forcePointsCloud === value) {
  16570. return;
  16571. }
  16572. this._forcePointsCloud = value;
  16573. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16574. },
  16575. enumerable: true,
  16576. configurable: true
  16577. });
  16578. Object.defineProperty(Scene.prototype, "onDispose", {
  16579. /** A function to be executed when this scene is disposed. */
  16580. set: function (callback) {
  16581. if (this._onDisposeObserver) {
  16582. this.onDisposeObservable.remove(this._onDisposeObserver);
  16583. }
  16584. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  16585. },
  16586. enumerable: true,
  16587. configurable: true
  16588. });
  16589. Object.defineProperty(Scene.prototype, "beforeRender", {
  16590. /** A function to be executed before rendering this scene */
  16591. set: function (callback) {
  16592. if (this._onBeforeRenderObserver) {
  16593. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  16594. }
  16595. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  16596. },
  16597. enumerable: true,
  16598. configurable: true
  16599. });
  16600. Object.defineProperty(Scene.prototype, "afterRender", {
  16601. /** A function to be executed after rendering this scene */
  16602. set: function (callback) {
  16603. if (this._onAfterRenderObserver) {
  16604. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  16605. }
  16606. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  16607. },
  16608. enumerable: true,
  16609. configurable: true
  16610. });
  16611. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  16612. set: function (callback) {
  16613. if (this._onBeforeCameraRenderObserver) {
  16614. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  16615. }
  16616. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  16617. },
  16618. enumerable: true,
  16619. configurable: true
  16620. });
  16621. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  16622. set: function (callback) {
  16623. if (this._onAfterCameraRenderObserver) {
  16624. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  16625. }
  16626. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  16627. },
  16628. enumerable: true,
  16629. configurable: true
  16630. });
  16631. Object.defineProperty(Scene.prototype, "gamepadManager", {
  16632. get: function () {
  16633. if (!this._gamepadManager) {
  16634. this._gamepadManager = new BABYLON.GamepadManager();
  16635. }
  16636. return this._gamepadManager;
  16637. },
  16638. enumerable: true,
  16639. configurable: true
  16640. });
  16641. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  16642. get: function () {
  16643. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  16644. },
  16645. enumerable: true,
  16646. configurable: true
  16647. });
  16648. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  16649. get: function () {
  16650. return this._useRightHandedSystem;
  16651. },
  16652. set: function (value) {
  16653. if (this._useRightHandedSystem === value) {
  16654. return;
  16655. }
  16656. this._useRightHandedSystem = value;
  16657. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16658. },
  16659. enumerable: true,
  16660. configurable: true
  16661. });
  16662. Scene.prototype.setStepId = function (newStepId) {
  16663. this._currentStepId = newStepId;
  16664. };
  16665. ;
  16666. Scene.prototype.getStepId = function () {
  16667. return this._currentStepId;
  16668. };
  16669. ;
  16670. Scene.prototype.getInternalStep = function () {
  16671. return this._currentInternalStep;
  16672. };
  16673. ;
  16674. Object.defineProperty(Scene.prototype, "fogEnabled", {
  16675. get: function () {
  16676. return this._fogEnabled;
  16677. },
  16678. /**
  16679. * is fog enabled on this scene.
  16680. */
  16681. set: function (value) {
  16682. if (this._fogEnabled === value) {
  16683. return;
  16684. }
  16685. this._fogEnabled = value;
  16686. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16687. },
  16688. enumerable: true,
  16689. configurable: true
  16690. });
  16691. Object.defineProperty(Scene.prototype, "fogMode", {
  16692. get: function () {
  16693. return this._fogMode;
  16694. },
  16695. set: function (value) {
  16696. if (this._fogMode === value) {
  16697. return;
  16698. }
  16699. this._fogMode = value;
  16700. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  16701. },
  16702. enumerable: true,
  16703. configurable: true
  16704. });
  16705. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  16706. get: function () {
  16707. return this._shadowsEnabled;
  16708. },
  16709. set: function (value) {
  16710. if (this._shadowsEnabled === value) {
  16711. return;
  16712. }
  16713. this._shadowsEnabled = value;
  16714. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16715. },
  16716. enumerable: true,
  16717. configurable: true
  16718. });
  16719. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  16720. get: function () {
  16721. return this._lightsEnabled;
  16722. },
  16723. set: function (value) {
  16724. if (this._lightsEnabled === value) {
  16725. return;
  16726. }
  16727. this._lightsEnabled = value;
  16728. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  16729. },
  16730. enumerable: true,
  16731. configurable: true
  16732. });
  16733. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  16734. /** The default material used on meshes when no material is affected */
  16735. get: function () {
  16736. if (!this._defaultMaterial) {
  16737. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  16738. }
  16739. return this._defaultMaterial;
  16740. },
  16741. /** The default material used on meshes when no material is affected */
  16742. set: function (value) {
  16743. this._defaultMaterial = value;
  16744. },
  16745. enumerable: true,
  16746. configurable: true
  16747. });
  16748. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  16749. get: function () {
  16750. return this._texturesEnabled;
  16751. },
  16752. set: function (value) {
  16753. if (this._texturesEnabled === value) {
  16754. return;
  16755. }
  16756. this._texturesEnabled = value;
  16757. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  16758. },
  16759. enumerable: true,
  16760. configurable: true
  16761. });
  16762. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  16763. get: function () {
  16764. return this._skeletonsEnabled;
  16765. },
  16766. set: function (value) {
  16767. if (this._skeletonsEnabled === value) {
  16768. return;
  16769. }
  16770. this._skeletonsEnabled = value;
  16771. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  16772. },
  16773. enumerable: true,
  16774. configurable: true
  16775. });
  16776. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  16777. get: function () {
  16778. if (!this._postProcessRenderPipelineManager) {
  16779. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  16780. }
  16781. return this._postProcessRenderPipelineManager;
  16782. },
  16783. enumerable: true,
  16784. configurable: true
  16785. });
  16786. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  16787. get: function () {
  16788. return this._frustumPlanes;
  16789. },
  16790. enumerable: true,
  16791. configurable: true
  16792. });
  16793. Object.defineProperty(Scene.prototype, "debugLayer", {
  16794. // Properties
  16795. get: function () {
  16796. if (!this._debugLayer) {
  16797. this._debugLayer = new BABYLON.DebugLayer(this);
  16798. }
  16799. return this._debugLayer;
  16800. },
  16801. enumerable: true,
  16802. configurable: true
  16803. });
  16804. Object.defineProperty(Scene.prototype, "workerCollisions", {
  16805. get: function () {
  16806. return this._workerCollisions;
  16807. },
  16808. set: function (enabled) {
  16809. if (!BABYLON.CollisionCoordinatorLegacy) {
  16810. return;
  16811. }
  16812. enabled = (enabled && !!Worker);
  16813. this._workerCollisions = enabled;
  16814. if (this.collisionCoordinator) {
  16815. this.collisionCoordinator.destroy();
  16816. }
  16817. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  16818. this.collisionCoordinator.init(this);
  16819. },
  16820. enumerable: true,
  16821. configurable: true
  16822. });
  16823. Object.defineProperty(Scene.prototype, "selectionOctree", {
  16824. get: function () {
  16825. return this._selectionOctree;
  16826. },
  16827. enumerable: true,
  16828. configurable: true
  16829. });
  16830. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  16831. /**
  16832. * The mesh that is currently under the pointer.
  16833. * @return {BABYLON.AbstractMesh} mesh under the pointer/mouse cursor or null if none.
  16834. */
  16835. get: function () {
  16836. return this._pointerOverMesh;
  16837. },
  16838. enumerable: true,
  16839. configurable: true
  16840. });
  16841. Object.defineProperty(Scene.prototype, "pointerX", {
  16842. /**
  16843. * Current on-screen X position of the pointer
  16844. * @return {number} X position of the pointer
  16845. */
  16846. get: function () {
  16847. return this._pointerX;
  16848. },
  16849. enumerable: true,
  16850. configurable: true
  16851. });
  16852. Object.defineProperty(Scene.prototype, "pointerY", {
  16853. /**
  16854. * Current on-screen Y position of the pointer
  16855. * @return {number} Y position of the pointer
  16856. */
  16857. get: function () {
  16858. return this._pointerY;
  16859. },
  16860. enumerable: true,
  16861. configurable: true
  16862. });
  16863. Scene.prototype.getCachedMaterial = function () {
  16864. return this._cachedMaterial;
  16865. };
  16866. Scene.prototype.getCachedEffect = function () {
  16867. return this._cachedEffect;
  16868. };
  16869. Scene.prototype.getCachedVisibility = function () {
  16870. return this._cachedVisibility;
  16871. };
  16872. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  16873. if (visibility === void 0) { visibility = 1; }
  16874. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  16875. };
  16876. Scene.prototype.getBoundingBoxRenderer = function () {
  16877. if (!this._boundingBoxRenderer) {
  16878. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  16879. }
  16880. return this._boundingBoxRenderer;
  16881. };
  16882. Scene.prototype.getOutlineRenderer = function () {
  16883. return this._outlineRenderer;
  16884. };
  16885. Scene.prototype.getEngine = function () {
  16886. return this._engine;
  16887. };
  16888. Scene.prototype.getTotalVertices = function () {
  16889. return this._totalVertices.current;
  16890. };
  16891. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  16892. get: function () {
  16893. return this._totalVertices;
  16894. },
  16895. enumerable: true,
  16896. configurable: true
  16897. });
  16898. Scene.prototype.getActiveIndices = function () {
  16899. return this._activeIndices.current;
  16900. };
  16901. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  16902. get: function () {
  16903. return this._activeIndices;
  16904. },
  16905. enumerable: true,
  16906. configurable: true
  16907. });
  16908. Scene.prototype.getActiveParticles = function () {
  16909. return this._activeParticles.current;
  16910. };
  16911. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  16912. get: function () {
  16913. return this._activeParticles;
  16914. },
  16915. enumerable: true,
  16916. configurable: true
  16917. });
  16918. Scene.prototype.getActiveBones = function () {
  16919. return this._activeBones.current;
  16920. };
  16921. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  16922. get: function () {
  16923. return this._activeBones;
  16924. },
  16925. enumerable: true,
  16926. configurable: true
  16927. });
  16928. // Stats
  16929. Scene.prototype.getLastFrameDuration = function () {
  16930. return this._lastFrameDuration.current;
  16931. };
  16932. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  16933. get: function () {
  16934. return this._lastFrameDuration;
  16935. },
  16936. enumerable: true,
  16937. configurable: true
  16938. });
  16939. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  16940. return this._evaluateActiveMeshesDuration.current;
  16941. };
  16942. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  16943. get: function () {
  16944. return this._evaluateActiveMeshesDuration;
  16945. },
  16946. enumerable: true,
  16947. configurable: true
  16948. });
  16949. Scene.prototype.getActiveMeshes = function () {
  16950. return this._activeMeshes;
  16951. };
  16952. Scene.prototype.getRenderTargetsDuration = function () {
  16953. return this._renderTargetsDuration.current;
  16954. };
  16955. Scene.prototype.getRenderDuration = function () {
  16956. return this._renderDuration.current;
  16957. };
  16958. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  16959. get: function () {
  16960. return this._renderDuration;
  16961. },
  16962. enumerable: true,
  16963. configurable: true
  16964. });
  16965. Scene.prototype.getParticlesDuration = function () {
  16966. return this._particlesDuration.current;
  16967. };
  16968. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  16969. get: function () {
  16970. return this._particlesDuration;
  16971. },
  16972. enumerable: true,
  16973. configurable: true
  16974. });
  16975. Scene.prototype.getSpritesDuration = function () {
  16976. return this._spritesDuration.current;
  16977. };
  16978. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  16979. get: function () {
  16980. return this._spritesDuration;
  16981. },
  16982. enumerable: true,
  16983. configurable: true
  16984. });
  16985. Scene.prototype.getAnimationRatio = function () {
  16986. return this._animationRatio;
  16987. };
  16988. Scene.prototype.getRenderId = function () {
  16989. return this._renderId;
  16990. };
  16991. Scene.prototype.incrementRenderId = function () {
  16992. this._renderId++;
  16993. };
  16994. Scene.prototype._updatePointerPosition = function (evt) {
  16995. var canvasRect = this._engine.getRenderingCanvasClientRect();
  16996. this._pointerX = evt.clientX - canvasRect.left;
  16997. this._pointerY = evt.clientY - canvasRect.top;
  16998. this._unTranslatedPointerX = this._pointerX;
  16999. this._unTranslatedPointerY = this._pointerY;
  17000. };
  17001. Scene.prototype._createUbo = function () {
  17002. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, null, true);
  17003. this._sceneUbo.addUniform("viewProjection", 16);
  17004. this._sceneUbo.addUniform("view", 16);
  17005. };
  17006. // Pointers handling
  17007. /**
  17008. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  17009. * @param attachUp defines if you want to attach events to pointerup
  17010. * @param attachDown defines if you want to attach events to pointerdown
  17011. * @param attachMove defines if you want to attach events to pointermove
  17012. */
  17013. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  17014. var _this = this;
  17015. if (attachUp === void 0) { attachUp = true; }
  17016. if (attachDown === void 0) { attachDown = true; }
  17017. if (attachMove === void 0) { attachMove = true; }
  17018. this._initActionManager = function (act, clickInfo) {
  17019. if (!_this._meshPickProceed) {
  17020. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17021. _this._currentPickResult = pickResult;
  17022. if (pickResult) {
  17023. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  17024. }
  17025. _this._meshPickProceed = true;
  17026. }
  17027. return act;
  17028. };
  17029. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  17030. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  17031. if ((new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  17032. btn !== _this._previousButtonPressed) {
  17033. _this._doubleClickOccured = false;
  17034. clickInfo.singleClick = true;
  17035. clickInfo.ignore = false;
  17036. cb(clickInfo, _this._currentPickResult);
  17037. }
  17038. };
  17039. this._initClickEvent = function (obs1, obs2, evt, cb) {
  17040. var clickInfo = new ClickInfo();
  17041. _this._currentPickResult = null;
  17042. var act;
  17043. var checkPicking = obs1.hasSpecificMask(PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(PointerEventTypes.POINTERPICK)
  17044. || obs1.hasSpecificMask(PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERTAP)
  17045. || obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17046. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  17047. act = _this._initActionManager(act, clickInfo);
  17048. if (act)
  17049. checkPicking = act.hasPickTriggers;
  17050. }
  17051. if (checkPicking) {
  17052. var btn = evt.button;
  17053. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  17054. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  17055. if (!clickInfo.hasSwiped) {
  17056. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  17057. if (!checkSingleClickImmediately) {
  17058. checkSingleClickImmediately = !obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) &&
  17059. !obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17060. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17061. act = _this._initActionManager(act, clickInfo);
  17062. if (act)
  17063. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17064. }
  17065. }
  17066. if (checkSingleClickImmediately) {
  17067. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  17068. if (new Date().getTime() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  17069. btn !== _this._previousButtonPressed) {
  17070. clickInfo.singleClick = true;
  17071. cb(clickInfo, _this._currentPickResult);
  17072. }
  17073. }
  17074. else {
  17075. // wait that no double click has been raised during the double click delay
  17076. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17077. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  17078. }
  17079. var checkDoubleClick = obs1.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP) ||
  17080. obs2.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP);
  17081. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17082. act = _this._initActionManager(act, clickInfo);
  17083. if (act)
  17084. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  17085. }
  17086. if (checkDoubleClick) {
  17087. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  17088. if (btn === _this._previousButtonPressed &&
  17089. new Date().getTime() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  17090. !_this._doubleClickOccured) {
  17091. // pointer has not moved for 2 clicks, it's a double click
  17092. if (!clickInfo.hasSwiped &&
  17093. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  17094. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  17095. _this._previousStartingPointerTime = 0;
  17096. _this._doubleClickOccured = true;
  17097. clickInfo.doubleClick = true;
  17098. clickInfo.ignore = false;
  17099. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout)
  17100. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17101. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17102. cb(clickInfo, _this._currentPickResult);
  17103. }
  17104. else {
  17105. _this._doubleClickOccured = false;
  17106. _this._previousStartingPointerTime = _this._startingPointerTime;
  17107. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17108. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17109. _this._previousButtonPressed = btn;
  17110. _this._previousHasSwiped = clickInfo.hasSwiped;
  17111. if (Scene.ExclusiveDoubleClickMode) {
  17112. if (_this._previousDelayedSimpleClickTimeout && _this._previousDelayedSimpleClickTimeout.clearTimeout) {
  17113. _this._previousDelayedSimpleClickTimeout.clearTimeout();
  17114. }
  17115. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  17116. cb(clickInfo, _this._previousPickResult);
  17117. }
  17118. else {
  17119. cb(clickInfo, _this._currentPickResult);
  17120. }
  17121. }
  17122. }
  17123. else {
  17124. _this._doubleClickOccured = false;
  17125. _this._previousStartingPointerTime = _this._startingPointerTime;
  17126. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  17127. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  17128. _this._previousButtonPressed = btn;
  17129. _this._previousHasSwiped = clickInfo.hasSwiped;
  17130. }
  17131. }
  17132. }
  17133. }
  17134. clickInfo.ignore = true;
  17135. cb(clickInfo, _this._currentPickResult);
  17136. };
  17137. var spritePredicate = function (sprite) {
  17138. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  17139. };
  17140. this._onPointerMove = function (evt) {
  17141. _this._updatePointerPosition(evt);
  17142. // PreObservable support
  17143. if (_this.onPrePointerObservable.hasObservers()) {
  17144. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17145. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17146. _this.onPrePointerObservable.notifyObservers(pi, type);
  17147. if (pi.skipOnPointerObservable) {
  17148. return;
  17149. }
  17150. }
  17151. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17152. return;
  17153. }
  17154. var canvas = _this._engine.getRenderingCanvas();
  17155. if (!_this.pointerMovePredicate) {
  17156. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  17157. }
  17158. // Meshes
  17159. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  17160. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17161. _this.setPointerOverSprite(null);
  17162. _this.setPointerOverMesh(pickResult.pickedMesh);
  17163. if (_this._pointerOverMesh.actionManager && _this._pointerOverMesh.actionManager.hasPointerTriggers) {
  17164. if (_this._pointerOverMesh.actionManager.hoverCursor) {
  17165. canvas.style.cursor = _this._pointerOverMesh.actionManager.hoverCursor;
  17166. }
  17167. else {
  17168. canvas.style.cursor = _this.hoverCursor;
  17169. }
  17170. }
  17171. else {
  17172. canvas.style.cursor = _this.defaultCursor;
  17173. }
  17174. }
  17175. else {
  17176. _this.setPointerOverMesh(null);
  17177. // Sprites
  17178. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17179. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17180. _this.setPointerOverSprite(pickResult.pickedSprite);
  17181. if (_this._pointerOverSprite.actionManager && _this._pointerOverSprite.actionManager.hoverCursor) {
  17182. canvas.style.cursor = _this._pointerOverSprite.actionManager.hoverCursor;
  17183. }
  17184. else {
  17185. canvas.style.cursor = _this.hoverCursor;
  17186. }
  17187. }
  17188. else {
  17189. _this.setPointerOverSprite(null);
  17190. // Restore pointer
  17191. canvas.style.cursor = _this.defaultCursor;
  17192. }
  17193. }
  17194. if (_this.onPointerMove) {
  17195. _this.onPointerMove(evt, pickResult);
  17196. }
  17197. if (_this.onPointerObservable.hasObservers()) {
  17198. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? PointerEventTypes.POINTERWHEEL : PointerEventTypes.POINTERMOVE;
  17199. var pi = new PointerInfo(type, evt, pickResult);
  17200. _this.onPointerObservable.notifyObservers(pi, type);
  17201. }
  17202. };
  17203. this._onPointerDown = function (evt) {
  17204. _this._isButtonPressed = true;
  17205. _this._pickedDownMesh = null;
  17206. _this._meshPickProceed = false;
  17207. _this._updatePointerPosition(evt);
  17208. // PreObservable support
  17209. if (_this.onPrePointerObservable.hasObservers()) {
  17210. var type = PointerEventTypes.POINTERDOWN;
  17211. var pi = new PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  17212. _this.onPrePointerObservable.notifyObservers(pi, type);
  17213. if (pi.skipOnPointerObservable) {
  17214. return;
  17215. }
  17216. }
  17217. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  17218. return;
  17219. }
  17220. _this._startingPointerPosition.x = _this._pointerX;
  17221. _this._startingPointerPosition.y = _this._pointerY;
  17222. _this._startingPointerTime = new Date().getTime();
  17223. if (!_this.pointerDownPredicate) {
  17224. _this.pointerDownPredicate = function (mesh) {
  17225. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17226. };
  17227. }
  17228. // Meshes
  17229. _this._pickedDownMesh = null;
  17230. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  17231. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17232. _this._pickedDownMesh = pickResult.pickedMesh;
  17233. var actionManager = pickResult.pickedMesh.actionManager;
  17234. if (actionManager) {
  17235. if (actionManager.hasPickTriggers) {
  17236. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17237. switch (evt.button) {
  17238. case 0:
  17239. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17240. break;
  17241. case 1:
  17242. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17243. break;
  17244. case 2:
  17245. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17246. break;
  17247. }
  17248. }
  17249. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  17250. window.setTimeout((function () {
  17251. var _this = this;
  17252. var pickResult = this.pick(this._unTranslatedPointerX, this._unTranslatedPointerY, function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.actionManager && mesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger) && mesh == _this._pickedDownMesh; }, false, this.cameraToUseForPointers);
  17253. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  17254. if (this._isButtonPressed &&
  17255. ((new Date().getTime() - this._startingPointerTime) > Scene.LongPressDelay) &&
  17256. (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold &&
  17257. Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold)) {
  17258. this._startingPointerTime = 0;
  17259. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17260. }
  17261. }
  17262. }).bind(_this), Scene.LongPressDelay);
  17263. }
  17264. }
  17265. }
  17266. if (_this.onPointerDown) {
  17267. _this.onPointerDown(evt, pickResult);
  17268. }
  17269. if (_this.onPointerObservable.hasObservers()) {
  17270. var type = PointerEventTypes.POINTERDOWN;
  17271. var pi = new PointerInfo(type, evt, pickResult);
  17272. _this.onPointerObservable.notifyObservers(pi, type);
  17273. }
  17274. // Sprites
  17275. _this._pickedDownSprite = null;
  17276. if (_this.spriteManagers.length > 0) {
  17277. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, spritePredicate, false, _this.cameraToUseForPointers);
  17278. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  17279. if (pickResult.pickedSprite.actionManager) {
  17280. _this._pickedDownSprite = pickResult.pickedSprite;
  17281. switch (evt.button) {
  17282. case 0:
  17283. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17284. break;
  17285. case 1:
  17286. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17287. break;
  17288. case 2:
  17289. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17290. break;
  17291. }
  17292. if (pickResult.pickedSprite.actionManager) {
  17293. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  17294. }
  17295. }
  17296. }
  17297. }
  17298. };
  17299. this._onPointerUp = function (evt) {
  17300. _this._isButtonPressed = false;
  17301. _this._pickedUpMesh = null;
  17302. _this._meshPickProceed = false;
  17303. _this._updatePointerPosition(evt);
  17304. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, (function (clickInfo, pickResult) {
  17305. // PreObservable support
  17306. if (this.onPrePointerObservable.hasObservers()) {
  17307. if (!clickInfo.ignore) {
  17308. if (!clickInfo.hasSwiped) {
  17309. if (clickInfo.singleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17310. var type = PointerEventTypes.POINTERTAP;
  17311. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17312. this.onPrePointerObservable.notifyObservers(pi, type);
  17313. if (pi.skipOnPointerObservable) {
  17314. return;
  17315. }
  17316. }
  17317. if (clickInfo.doubleClick && this.onPrePointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17318. var type = PointerEventTypes.POINTERDOUBLETAP;
  17319. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17320. this.onPrePointerObservable.notifyObservers(pi, type);
  17321. if (pi.skipOnPointerObservable) {
  17322. return;
  17323. }
  17324. }
  17325. }
  17326. }
  17327. else {
  17328. var type = PointerEventTypes.POINTERUP;
  17329. var pi = new PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  17330. this.onPrePointerObservable.notifyObservers(pi, type);
  17331. if (pi.skipOnPointerObservable) {
  17332. return;
  17333. }
  17334. }
  17335. }
  17336. if (!this.cameraToUseForPointers && !this.activeCamera) {
  17337. return;
  17338. }
  17339. if (!this.pointerUpPredicate) {
  17340. this.pointerUpPredicate = function (mesh) {
  17341. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  17342. };
  17343. }
  17344. // Meshes
  17345. if (!this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || this.onPointerObservable.hasObservers())) {
  17346. this._initActionManager(null, clickInfo);
  17347. }
  17348. if (!pickResult) {
  17349. pickResult = this._currentPickResult;
  17350. }
  17351. if (pickResult && pickResult && pickResult.pickedMesh) {
  17352. this._pickedUpMesh = pickResult.pickedMesh;
  17353. if (this._pickedDownMesh === this._pickedUpMesh) {
  17354. if (this.onPointerPick) {
  17355. this.onPointerPick(evt, pickResult);
  17356. }
  17357. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  17358. var type = PointerEventTypes.POINTERPICK;
  17359. var pi = new PointerInfo(type, evt, pickResult);
  17360. this.onPointerObservable.notifyObservers(pi, type);
  17361. }
  17362. }
  17363. if (pickResult.pickedMesh.actionManager) {
  17364. if (clickInfo.ignore) {
  17365. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17366. }
  17367. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  17368. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17369. }
  17370. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  17371. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  17372. }
  17373. }
  17374. }
  17375. if (this._pickedDownMesh &&
  17376. this._pickedDownMesh.actionManager &&
  17377. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  17378. this._pickedDownMesh !== this._pickedUpMesh) {
  17379. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  17380. }
  17381. if (this.onPointerUp) {
  17382. this.onPointerUp(evt, pickResult);
  17383. }
  17384. if (this.onPointerObservable.hasObservers()) {
  17385. if (!clickInfo.ignore) {
  17386. if (!clickInfo.hasSwiped) {
  17387. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERTAP)) {
  17388. var type = PointerEventTypes.POINTERTAP;
  17389. var pi = new PointerInfo(type, evt, pickResult);
  17390. this.onPointerObservable.notifyObservers(pi, type);
  17391. }
  17392. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(PointerEventTypes.POINTERDOUBLETAP)) {
  17393. var type = PointerEventTypes.POINTERDOUBLETAP;
  17394. var pi = new PointerInfo(type, evt, pickResult);
  17395. this.onPointerObservable.notifyObservers(pi, type);
  17396. }
  17397. }
  17398. }
  17399. else {
  17400. var type = PointerEventTypes.POINTERUP;
  17401. var pi = new PointerInfo(type, evt, pickResult);
  17402. this.onPointerObservable.notifyObservers(pi, type);
  17403. }
  17404. }
  17405. // Sprites
  17406. if (this.spriteManagers.length > 0) {
  17407. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, spritePredicate, false, this.cameraToUseForPointers);
  17408. if (pickResult.hit && pickResult.pickedSprite) {
  17409. if (pickResult.pickedSprite.actionManager) {
  17410. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17411. if (pickResult.pickedSprite.actionManager) {
  17412. if (Math.abs(this._startingPointerPosition.x - this._pointerX) < Scene.DragMovementThreshold && Math.abs(this._startingPointerPosition.y - this._pointerY) < Scene.DragMovementThreshold) {
  17413. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, this, evt));
  17414. }
  17415. }
  17416. }
  17417. }
  17418. if (this._pickedDownSprite && this._pickedDownSprite.actionManager && this._pickedDownSprite !== pickResult.pickedSprite) {
  17419. this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pickedDownSprite, this, evt));
  17420. }
  17421. }
  17422. this._previousPickResult = this._currentPickResult;
  17423. }).bind(_this));
  17424. };
  17425. this._onKeyDown = function (evt) {
  17426. if (_this.actionManager) {
  17427. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17428. }
  17429. };
  17430. this._onKeyUp = function (evt) {
  17431. if (_this.actionManager) {
  17432. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  17433. }
  17434. };
  17435. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17436. var canvas = this._engine.getRenderingCanvas();
  17437. if (attachMove) {
  17438. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  17439. // Wheel
  17440. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  17441. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  17442. }
  17443. if (attachDown) {
  17444. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  17445. }
  17446. if (attachUp) {
  17447. canvas.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  17448. }
  17449. canvas.tabIndex = 1;
  17450. canvas.addEventListener("keydown", this._onKeyDown, false);
  17451. canvas.addEventListener("keyup", this._onKeyUp, false);
  17452. };
  17453. Scene.prototype.detachControl = function () {
  17454. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  17455. var canvas = this._engine.getRenderingCanvas();
  17456. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  17457. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  17458. canvas.removeEventListener(eventPrefix + "up", this._onPointerUp);
  17459. // Wheel
  17460. canvas.removeEventListener('mousewheel', this._onPointerMove);
  17461. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  17462. canvas.removeEventListener("keydown", this._onKeyDown);
  17463. canvas.removeEventListener("keyup", this._onKeyUp);
  17464. };
  17465. // Ready
  17466. Scene.prototype.isReady = function () {
  17467. if (this._pendingData.length > 0) {
  17468. return false;
  17469. }
  17470. var index;
  17471. // Geometries
  17472. for (index = 0; index < this._geometries.length; index++) {
  17473. var geometry = this._geometries[index];
  17474. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  17475. return false;
  17476. }
  17477. }
  17478. // Meshes
  17479. for (index = 0; index < this.meshes.length; index++) {
  17480. var mesh = this.meshes[index];
  17481. if (!mesh.isEnabled()) {
  17482. continue;
  17483. }
  17484. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  17485. continue;
  17486. }
  17487. if (!mesh.isReady()) {
  17488. return false;
  17489. }
  17490. var mat = mesh.material;
  17491. if (mat) {
  17492. if (!mat.isReady(mesh)) {
  17493. return false;
  17494. }
  17495. }
  17496. }
  17497. return true;
  17498. };
  17499. Scene.prototype.resetCachedMaterial = function () {
  17500. this._cachedMaterial = null;
  17501. this._cachedEffect = null;
  17502. this._cachedVisibility = null;
  17503. };
  17504. Scene.prototype.registerBeforeRender = function (func) {
  17505. this.onBeforeRenderObservable.add(func);
  17506. };
  17507. Scene.prototype.unregisterBeforeRender = function (func) {
  17508. this.onBeforeRenderObservable.removeCallback(func);
  17509. };
  17510. Scene.prototype.registerAfterRender = function (func) {
  17511. this.onAfterRenderObservable.add(func);
  17512. };
  17513. Scene.prototype.unregisterAfterRender = function (func) {
  17514. this.onAfterRenderObservable.removeCallback(func);
  17515. };
  17516. Scene.prototype._addPendingData = function (data) {
  17517. this._pendingData.push(data);
  17518. };
  17519. Scene.prototype._removePendingData = function (data) {
  17520. var index = this._pendingData.indexOf(data);
  17521. if (index !== -1) {
  17522. this._pendingData.splice(index, 1);
  17523. }
  17524. };
  17525. Scene.prototype.getWaitingItemsCount = function () {
  17526. return this._pendingData.length;
  17527. };
  17528. /**
  17529. * Registers a function to be executed when the scene is ready.
  17530. * @param {Function} func - the function to be executed.
  17531. */
  17532. Scene.prototype.executeWhenReady = function (func) {
  17533. var _this = this;
  17534. this.onReadyObservable.add(func);
  17535. if (this._executeWhenReadyTimeoutId !== -1) {
  17536. return;
  17537. }
  17538. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17539. _this._checkIsReady();
  17540. }, 150);
  17541. };
  17542. Scene.prototype._checkIsReady = function () {
  17543. var _this = this;
  17544. if (this.isReady()) {
  17545. this.onReadyObservable.notifyObservers(this);
  17546. this.onReadyObservable.clear();
  17547. this._executeWhenReadyTimeoutId = -1;
  17548. return;
  17549. }
  17550. this._executeWhenReadyTimeoutId = setTimeout(function () {
  17551. _this._checkIsReady();
  17552. }, 150);
  17553. };
  17554. // Animations
  17555. /**
  17556. * Will start the animation sequence of a given target
  17557. * @param target - the target
  17558. * @param {number} from - from which frame should animation start
  17559. * @param {number} to - till which frame should animation run.
  17560. * @param {boolean} [loop] - should the animation loop
  17561. * @param {number} [speedRatio] - the speed in which to run the animation
  17562. * @param {Function} [onAnimationEnd] function to be executed when the animation ended.
  17563. * @param {BABYLON.Animatable} [animatable] an animatable object. If not provided a new one will be created from the given params.
  17564. * Returns {BABYLON.Animatable} the animatable object created for this animation
  17565. * See BABYLON.Animatable
  17566. */
  17567. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable) {
  17568. if (speedRatio === void 0) { speedRatio = 1.0; }
  17569. if (from > to && speedRatio > 0) {
  17570. speedRatio *= -1;
  17571. }
  17572. this.stopAnimation(target);
  17573. if (!animatable) {
  17574. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  17575. }
  17576. // Local animations
  17577. if (target.animations) {
  17578. animatable.appendAnimations(target, target.animations);
  17579. }
  17580. // Children animations
  17581. if (target.getAnimatables) {
  17582. var animatables = target.getAnimatables();
  17583. for (var index = 0; index < animatables.length; index++) {
  17584. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable);
  17585. }
  17586. }
  17587. animatable.reset();
  17588. return animatable;
  17589. };
  17590. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  17591. if (speedRatio === undefined) {
  17592. speedRatio = 1.0;
  17593. }
  17594. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  17595. return animatable;
  17596. };
  17597. Scene.prototype.getAnimatableByTarget = function (target) {
  17598. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17599. if (this._activeAnimatables[index].target === target) {
  17600. return this._activeAnimatables[index];
  17601. }
  17602. }
  17603. return null;
  17604. };
  17605. Object.defineProperty(Scene.prototype, "Animatables", {
  17606. get: function () {
  17607. return this._activeAnimatables;
  17608. },
  17609. enumerable: true,
  17610. configurable: true
  17611. });
  17612. /**
  17613. * Will stop the animation of the given target
  17614. * @param target - the target
  17615. * @param animationName - the name of the animation to stop (all animations will be stopped is empty)
  17616. * @see beginAnimation
  17617. */
  17618. Scene.prototype.stopAnimation = function (target, animationName) {
  17619. var animatable = this.getAnimatableByTarget(target);
  17620. if (animatable) {
  17621. animatable.stop(animationName);
  17622. }
  17623. };
  17624. Scene.prototype._animate = function () {
  17625. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  17626. return;
  17627. }
  17628. // Getting time
  17629. var now = BABYLON.Tools.Now;
  17630. if (!this._animationTimeLast) {
  17631. if (this._pendingData.length > 0) {
  17632. return;
  17633. }
  17634. this._animationTimeLast = now;
  17635. }
  17636. var deltaTime = (now - this._animationTimeLast) * this.animationTimeScale;
  17637. this._animationTime += deltaTime;
  17638. this._animationTimeLast = now;
  17639. for (var index = 0; index < this._activeAnimatables.length; index++) {
  17640. this._activeAnimatables[index]._animate(this._animationTime);
  17641. }
  17642. };
  17643. // Matrix
  17644. Scene.prototype.getViewMatrix = function () {
  17645. return this._viewMatrix;
  17646. };
  17647. Scene.prototype.getProjectionMatrix = function () {
  17648. return this._projectionMatrix;
  17649. };
  17650. Scene.prototype.getTransformMatrix = function () {
  17651. return this._transformMatrix;
  17652. };
  17653. Scene.prototype.setTransformMatrix = function (view, projection) {
  17654. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  17655. return;
  17656. }
  17657. this._viewUpdateFlag = view.updateFlag;
  17658. this._projectionUpdateFlag = projection.updateFlag;
  17659. this._viewMatrix = view;
  17660. this._projectionMatrix = projection;
  17661. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  17662. // Update frustum
  17663. if (!this._frustumPlanes) {
  17664. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  17665. }
  17666. else {
  17667. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  17668. }
  17669. if (this._sceneUbo.useUbo) {
  17670. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  17671. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  17672. this._sceneUbo.update();
  17673. }
  17674. };
  17675. Scene.prototype.getSceneUniformBuffer = function () {
  17676. return this._sceneUbo;
  17677. };
  17678. // Methods
  17679. Scene.prototype.getUniqueId = function () {
  17680. var result = this._uniqueIdCounter;
  17681. this._uniqueIdCounter++;
  17682. return result;
  17683. };
  17684. Scene.prototype.addMesh = function (newMesh) {
  17685. newMesh.uniqueId = this.getUniqueId();
  17686. var position = this.meshes.push(newMesh);
  17687. //notify the collision coordinator
  17688. if (this.collisionCoordinator) {
  17689. this.collisionCoordinator.onMeshAdded(newMesh);
  17690. }
  17691. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  17692. };
  17693. Scene.prototype.removeMesh = function (toRemove) {
  17694. var index = this.meshes.indexOf(toRemove);
  17695. if (index !== -1) {
  17696. // Remove from the scene if mesh found
  17697. this.meshes.splice(index, 1);
  17698. }
  17699. //notify the collision coordinator
  17700. if (this.collisionCoordinator) {
  17701. this.collisionCoordinator.onMeshRemoved(toRemove);
  17702. }
  17703. this.onMeshRemovedObservable.notifyObservers(toRemove);
  17704. return index;
  17705. };
  17706. Scene.prototype.removeSkeleton = function (toRemove) {
  17707. var index = this.skeletons.indexOf(toRemove);
  17708. if (index !== -1) {
  17709. // Remove from the scene if found
  17710. this.skeletons.splice(index, 1);
  17711. }
  17712. return index;
  17713. };
  17714. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  17715. var index = this.morphTargetManagers.indexOf(toRemove);
  17716. if (index !== -1) {
  17717. // Remove from the scene if found
  17718. this.morphTargetManagers.splice(index, 1);
  17719. }
  17720. return index;
  17721. };
  17722. Scene.prototype.removeLight = function (toRemove) {
  17723. var index = this.lights.indexOf(toRemove);
  17724. if (index !== -1) {
  17725. // Remove from the scene if mesh found
  17726. this.lights.splice(index, 1);
  17727. this.sortLightsByPriority();
  17728. }
  17729. this.onLightRemovedObservable.notifyObservers(toRemove);
  17730. return index;
  17731. };
  17732. Scene.prototype.removeCamera = function (toRemove) {
  17733. var index = this.cameras.indexOf(toRemove);
  17734. if (index !== -1) {
  17735. // Remove from the scene if mesh found
  17736. this.cameras.splice(index, 1);
  17737. }
  17738. // Remove from activeCameras
  17739. var index2 = this.activeCameras.indexOf(toRemove);
  17740. if (index2 !== -1) {
  17741. // Remove from the scene if mesh found
  17742. this.activeCameras.splice(index2, 1);
  17743. }
  17744. // Reset the activeCamera
  17745. if (this.activeCamera === toRemove) {
  17746. if (this.cameras.length > 0) {
  17747. this.activeCamera = this.cameras[0];
  17748. }
  17749. else {
  17750. this.activeCamera = null;
  17751. }
  17752. }
  17753. this.onCameraRemovedObservable.notifyObservers(toRemove);
  17754. return index;
  17755. };
  17756. Scene.prototype.addLight = function (newLight) {
  17757. newLight.uniqueId = this.getUniqueId();
  17758. this.lights.push(newLight);
  17759. this.sortLightsByPriority();
  17760. this.onNewLightAddedObservable.notifyObservers(newLight);
  17761. };
  17762. Scene.prototype.sortLightsByPriority = function () {
  17763. if (this.requireLightSorting) {
  17764. this.lights.sort(BABYLON.Light.compareLightsPriority);
  17765. }
  17766. };
  17767. Scene.prototype.addCamera = function (newCamera) {
  17768. newCamera.uniqueId = this.getUniqueId();
  17769. var position = this.cameras.push(newCamera);
  17770. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  17771. };
  17772. /**
  17773. * Switch active camera
  17774. * @param {Camera} newCamera - new active camera
  17775. * @param {boolean} attachControl - call attachControl for the new active camera (default: true)
  17776. */
  17777. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  17778. if (attachControl === void 0) { attachControl = true; }
  17779. var canvas = this._engine.getRenderingCanvas();
  17780. this.activeCamera.detachControl(canvas);
  17781. this.activeCamera = newCamera;
  17782. if (attachControl) {
  17783. newCamera.attachControl(canvas);
  17784. }
  17785. };
  17786. /**
  17787. * sets the active camera of the scene using its ID
  17788. * @param {string} id - the camera's ID
  17789. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17790. * @see activeCamera
  17791. */
  17792. Scene.prototype.setActiveCameraByID = function (id) {
  17793. var camera = this.getCameraByID(id);
  17794. if (camera) {
  17795. this.activeCamera = camera;
  17796. return camera;
  17797. }
  17798. return null;
  17799. };
  17800. /**
  17801. * sets the active camera of the scene using its name
  17802. * @param {string} name - the camera's name
  17803. * @return {BABYLON.Camera|null} the new active camera or null if none found.
  17804. * @see activeCamera
  17805. */
  17806. Scene.prototype.setActiveCameraByName = function (name) {
  17807. var camera = this.getCameraByName(name);
  17808. if (camera) {
  17809. this.activeCamera = camera;
  17810. return camera;
  17811. }
  17812. return null;
  17813. };
  17814. /**
  17815. * get a material using its id
  17816. * @param {string} the material's ID
  17817. * @return {BABYLON.Material|null} the material or null if none found.
  17818. */
  17819. Scene.prototype.getMaterialByID = function (id) {
  17820. for (var index = 0; index < this.materials.length; index++) {
  17821. if (this.materials[index].id === id) {
  17822. return this.materials[index];
  17823. }
  17824. }
  17825. return null;
  17826. };
  17827. /**
  17828. * get a material using its name
  17829. * @param {string} the material's name
  17830. * @return {BABYLON.Material|null} the material or null if none found.
  17831. */
  17832. Scene.prototype.getMaterialByName = function (name) {
  17833. for (var index = 0; index < this.materials.length; index++) {
  17834. if (this.materials[index].name === name) {
  17835. return this.materials[index];
  17836. }
  17837. }
  17838. return null;
  17839. };
  17840. Scene.prototype.getLensFlareSystemByName = function (name) {
  17841. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17842. if (this.lensFlareSystems[index].name === name) {
  17843. return this.lensFlareSystems[index];
  17844. }
  17845. }
  17846. return null;
  17847. };
  17848. Scene.prototype.getLensFlareSystemByID = function (id) {
  17849. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  17850. if (this.lensFlareSystems[index].id === id) {
  17851. return this.lensFlareSystems[index];
  17852. }
  17853. }
  17854. return null;
  17855. };
  17856. Scene.prototype.getCameraByID = function (id) {
  17857. for (var index = 0; index < this.cameras.length; index++) {
  17858. if (this.cameras[index].id === id) {
  17859. return this.cameras[index];
  17860. }
  17861. }
  17862. return null;
  17863. };
  17864. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  17865. for (var index = 0; index < this.cameras.length; index++) {
  17866. if (this.cameras[index].uniqueId === uniqueId) {
  17867. return this.cameras[index];
  17868. }
  17869. }
  17870. return null;
  17871. };
  17872. /**
  17873. * get a camera using its name
  17874. * @param {string} the camera's name
  17875. * @return {BABYLON.Camera|null} the camera or null if none found.
  17876. */
  17877. Scene.prototype.getCameraByName = function (name) {
  17878. for (var index = 0; index < this.cameras.length; index++) {
  17879. if (this.cameras[index].name === name) {
  17880. return this.cameras[index];
  17881. }
  17882. }
  17883. return null;
  17884. };
  17885. /**
  17886. * get a bone using its id
  17887. * @param {string} the bone's id
  17888. * @return {BABYLON.Bone|null} the bone or null if not found
  17889. */
  17890. Scene.prototype.getBoneByID = function (id) {
  17891. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17892. var skeleton = this.skeletons[skeletonIndex];
  17893. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17894. if (skeleton.bones[boneIndex].id === id) {
  17895. return skeleton.bones[boneIndex];
  17896. }
  17897. }
  17898. }
  17899. return null;
  17900. };
  17901. /**
  17902. * get a bone using its id
  17903. * @param {string} the bone's name
  17904. * @return {BABYLON.Bone|null} the bone or null if not found
  17905. */
  17906. Scene.prototype.getBoneByName = function (name) {
  17907. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  17908. var skeleton = this.skeletons[skeletonIndex];
  17909. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  17910. if (skeleton.bones[boneIndex].name === name) {
  17911. return skeleton.bones[boneIndex];
  17912. }
  17913. }
  17914. }
  17915. return null;
  17916. };
  17917. /**
  17918. * get a light node using its name
  17919. * @param {string} the light's name
  17920. * @return {BABYLON.Light|null} the light or null if none found.
  17921. */
  17922. Scene.prototype.getLightByName = function (name) {
  17923. for (var index = 0; index < this.lights.length; index++) {
  17924. if (this.lights[index].name === name) {
  17925. return this.lights[index];
  17926. }
  17927. }
  17928. return null;
  17929. };
  17930. /**
  17931. * get a light node using its ID
  17932. * @param {string} the light's id
  17933. * @return {BABYLON.Light|null} the light or null if none found.
  17934. */
  17935. Scene.prototype.getLightByID = function (id) {
  17936. for (var index = 0; index < this.lights.length; index++) {
  17937. if (this.lights[index].id === id) {
  17938. return this.lights[index];
  17939. }
  17940. }
  17941. return null;
  17942. };
  17943. /**
  17944. * get a light node using its scene-generated unique ID
  17945. * @param {number} the light's unique id
  17946. * @return {BABYLON.Light|null} the light or null if none found.
  17947. */
  17948. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  17949. for (var index = 0; index < this.lights.length; index++) {
  17950. if (this.lights[index].uniqueId === uniqueId) {
  17951. return this.lights[index];
  17952. }
  17953. }
  17954. return null;
  17955. };
  17956. /**
  17957. * get a particle system by id
  17958. * @param id {number} the particle system id
  17959. * @return {BABYLON.IParticleSystem|null} the corresponding system or null if none found.
  17960. */
  17961. Scene.prototype.getParticleSystemByID = function (id) {
  17962. for (var index = 0; index < this.particleSystems.length; index++) {
  17963. if (this.particleSystems[index].id === id) {
  17964. return this.particleSystems[index];
  17965. }
  17966. }
  17967. return null;
  17968. };
  17969. /**
  17970. * get a geometry using its ID
  17971. * @param {string} the geometry's id
  17972. * @return {BABYLON.Geometry|null} the geometry or null if none found.
  17973. */
  17974. Scene.prototype.getGeometryByID = function (id) {
  17975. for (var index = 0; index < this._geometries.length; index++) {
  17976. if (this._geometries[index].id === id) {
  17977. return this._geometries[index];
  17978. }
  17979. }
  17980. return null;
  17981. };
  17982. /**
  17983. * add a new geometry to this scene.
  17984. * @param {BABYLON.Geometry} geometry - the geometry to be added to the scene.
  17985. * @param {boolean} [force] - force addition, even if a geometry with this ID already exists
  17986. * @return {boolean} was the geometry added or not
  17987. */
  17988. Scene.prototype.pushGeometry = function (geometry, force) {
  17989. if (!force && this.getGeometryByID(geometry.id)) {
  17990. return false;
  17991. }
  17992. this._geometries.push(geometry);
  17993. //notify the collision coordinator
  17994. if (this.collisionCoordinator) {
  17995. this.collisionCoordinator.onGeometryAdded(geometry);
  17996. }
  17997. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  17998. return true;
  17999. };
  18000. /**
  18001. * Removes an existing geometry
  18002. * @param {BABYLON.Geometry} geometry - the geometry to be removed from the scene.
  18003. * @return {boolean} was the geometry removed or not
  18004. */
  18005. Scene.prototype.removeGeometry = function (geometry) {
  18006. var index = this._geometries.indexOf(geometry);
  18007. if (index > -1) {
  18008. this._geometries.splice(index, 1);
  18009. //notify the collision coordinator
  18010. if (this.collisionCoordinator) {
  18011. this.collisionCoordinator.onGeometryDeleted(geometry);
  18012. }
  18013. this.onGeometryRemovedObservable.notifyObservers(geometry);
  18014. return true;
  18015. }
  18016. return false;
  18017. };
  18018. Scene.prototype.getGeometries = function () {
  18019. return this._geometries;
  18020. };
  18021. /**
  18022. * Get the first added mesh found of a given ID
  18023. * @param {string} id - the id to search for
  18024. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18025. */
  18026. Scene.prototype.getMeshByID = function (id) {
  18027. for (var index = 0; index < this.meshes.length; index++) {
  18028. if (this.meshes[index].id === id) {
  18029. return this.meshes[index];
  18030. }
  18031. }
  18032. return null;
  18033. };
  18034. Scene.prototype.getMeshesByID = function (id) {
  18035. return this.meshes.filter(function (m) {
  18036. return m.id === id;
  18037. });
  18038. };
  18039. /**
  18040. * Get a mesh with its auto-generated unique id
  18041. * @param {number} uniqueId - the unique id to search for
  18042. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18043. */
  18044. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  18045. for (var index = 0; index < this.meshes.length; index++) {
  18046. if (this.meshes[index].uniqueId === uniqueId) {
  18047. return this.meshes[index];
  18048. }
  18049. }
  18050. return null;
  18051. };
  18052. /**
  18053. * Get a the last added mesh found of a given ID
  18054. * @param {string} id - the id to search for
  18055. * @return {BABYLON.AbstractMesh|null} the mesh found or null if not found at all.
  18056. */
  18057. Scene.prototype.getLastMeshByID = function (id) {
  18058. for (var index = this.meshes.length - 1; index >= 0; index--) {
  18059. if (this.meshes[index].id === id) {
  18060. return this.meshes[index];
  18061. }
  18062. }
  18063. return null;
  18064. };
  18065. /**
  18066. * Get a the last added node (Mesh, Camera, Light) found of a given ID
  18067. * @param {string} id - the id to search for
  18068. * @return {BABYLON.Node|null} the node found or null if not found at all.
  18069. */
  18070. Scene.prototype.getLastEntryByID = function (id) {
  18071. var index;
  18072. for (index = this.meshes.length - 1; index >= 0; index--) {
  18073. if (this.meshes[index].id === id) {
  18074. return this.meshes[index];
  18075. }
  18076. }
  18077. for (index = this.cameras.length - 1; index >= 0; index--) {
  18078. if (this.cameras[index].id === id) {
  18079. return this.cameras[index];
  18080. }
  18081. }
  18082. for (index = this.lights.length - 1; index >= 0; index--) {
  18083. if (this.lights[index].id === id) {
  18084. return this.lights[index];
  18085. }
  18086. }
  18087. return null;
  18088. };
  18089. Scene.prototype.getNodeByID = function (id) {
  18090. var mesh = this.getMeshByID(id);
  18091. if (mesh) {
  18092. return mesh;
  18093. }
  18094. var light = this.getLightByID(id);
  18095. if (light) {
  18096. return light;
  18097. }
  18098. var camera = this.getCameraByID(id);
  18099. if (camera) {
  18100. return camera;
  18101. }
  18102. var bone = this.getBoneByID(id);
  18103. return bone;
  18104. };
  18105. Scene.prototype.getNodeByName = function (name) {
  18106. var mesh = this.getMeshByName(name);
  18107. if (mesh) {
  18108. return mesh;
  18109. }
  18110. var light = this.getLightByName(name);
  18111. if (light) {
  18112. return light;
  18113. }
  18114. var camera = this.getCameraByName(name);
  18115. if (camera) {
  18116. return camera;
  18117. }
  18118. var bone = this.getBoneByName(name);
  18119. return bone;
  18120. };
  18121. Scene.prototype.getMeshByName = function (name) {
  18122. for (var index = 0; index < this.meshes.length; index++) {
  18123. if (this.meshes[index].name === name) {
  18124. return this.meshes[index];
  18125. }
  18126. }
  18127. return null;
  18128. };
  18129. Scene.prototype.getSoundByName = function (name) {
  18130. var index;
  18131. if (BABYLON.AudioEngine) {
  18132. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  18133. if (this.mainSoundTrack.soundCollection[index].name === name) {
  18134. return this.mainSoundTrack.soundCollection[index];
  18135. }
  18136. }
  18137. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  18138. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  18139. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  18140. return this.soundTracks[sdIndex].soundCollection[index];
  18141. }
  18142. }
  18143. }
  18144. }
  18145. return null;
  18146. };
  18147. Scene.prototype.getLastSkeletonByID = function (id) {
  18148. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  18149. if (this.skeletons[index].id === id) {
  18150. return this.skeletons[index];
  18151. }
  18152. }
  18153. return null;
  18154. };
  18155. Scene.prototype.getSkeletonById = function (id) {
  18156. for (var index = 0; index < this.skeletons.length; index++) {
  18157. if (this.skeletons[index].id === id) {
  18158. return this.skeletons[index];
  18159. }
  18160. }
  18161. return null;
  18162. };
  18163. Scene.prototype.getSkeletonByName = function (name) {
  18164. for (var index = 0; index < this.skeletons.length; index++) {
  18165. if (this.skeletons[index].name === name) {
  18166. return this.skeletons[index];
  18167. }
  18168. }
  18169. return null;
  18170. };
  18171. Scene.prototype.getMorphTargetManagerById = function (id) {
  18172. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  18173. if (this.morphTargetManagers[index].uniqueId === id) {
  18174. return this.morphTargetManagers[index];
  18175. }
  18176. }
  18177. return null;
  18178. };
  18179. Scene.prototype.isActiveMesh = function (mesh) {
  18180. return (this._activeMeshes.indexOf(mesh) !== -1);
  18181. };
  18182. /**
  18183. * Return a the first highlight layer of the scene with a given name.
  18184. * @param name The name of the highlight layer to look for.
  18185. * @return The highlight layer if found otherwise null.
  18186. */
  18187. Scene.prototype.getHighlightLayerByName = function (name) {
  18188. for (var index = 0; index < this.highlightLayers.length; index++) {
  18189. if (this.highlightLayers[index].name === name) {
  18190. return this.highlightLayers[index];
  18191. }
  18192. }
  18193. return null;
  18194. };
  18195. Object.defineProperty(Scene.prototype, "uid", {
  18196. /**
  18197. * Return a unique id as a string which can serve as an identifier for the scene
  18198. */
  18199. get: function () {
  18200. if (!this._uid) {
  18201. this._uid = BABYLON.Tools.RandomId();
  18202. }
  18203. return this._uid;
  18204. },
  18205. enumerable: true,
  18206. configurable: true
  18207. });
  18208. /**
  18209. * Add an externaly attached data from its key.
  18210. * This method call will fail and return false, if such key already exists.
  18211. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  18212. * @param key the unique key that identifies the data
  18213. * @param data the data object to associate to the key for this Engine instance
  18214. * @return true if no such key were already present and the data was added successfully, false otherwise
  18215. */
  18216. Scene.prototype.addExternalData = function (key, data) {
  18217. if (!this._externalData) {
  18218. this._externalData = new BABYLON.StringDictionary();
  18219. }
  18220. return this._externalData.add(key, data);
  18221. };
  18222. /**
  18223. * Get an externaly attached data from its key
  18224. * @param key the unique key that identifies the data
  18225. * @return the associated data, if present (can be null), or undefined if not present
  18226. */
  18227. Scene.prototype.getExternalData = function (key) {
  18228. if (!this._externalData) {
  18229. return null;
  18230. }
  18231. return this._externalData.get(key);
  18232. };
  18233. /**
  18234. * Get an externaly attached data from its key, create it using a factory if it's not already present
  18235. * @param key the unique key that identifies the data
  18236. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  18237. * @return the associated data, can be null if the factory returned null.
  18238. */
  18239. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  18240. if (!this._externalData) {
  18241. this._externalData = new BABYLON.StringDictionary();
  18242. }
  18243. return this._externalData.getOrAddWithFactory(key, factory);
  18244. };
  18245. /**
  18246. * Remove an externaly attached data from the Engine instance
  18247. * @param key the unique key that identifies the data
  18248. * @return true if the data was successfully removed, false if it doesn't exist
  18249. */
  18250. Scene.prototype.removeExternalData = function (key) {
  18251. return this._externalData.remove(key);
  18252. };
  18253. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  18254. if (mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  18255. var material = subMesh.getMaterial();
  18256. if (mesh.showSubMeshesBoundingBox) {
  18257. this.getBoundingBoxRenderer().renderList.push(subMesh.getBoundingInfo().boundingBox);
  18258. }
  18259. if (material) {
  18260. // Render targets
  18261. if (material.getRenderTargetTextures) {
  18262. if (this._processedMaterials.indexOf(material) === -1) {
  18263. this._processedMaterials.push(material);
  18264. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  18265. }
  18266. }
  18267. // Dispatch
  18268. this._activeIndices.addCount(subMesh.indexCount, false);
  18269. this._renderingManager.dispatch(subMesh);
  18270. }
  18271. }
  18272. };
  18273. Scene.prototype._isInIntermediateRendering = function () {
  18274. return this._intermediateRendering;
  18275. };
  18276. Scene.prototype._evaluateActiveMeshes = function () {
  18277. this.activeCamera._activeMeshes.reset();
  18278. this._activeMeshes.reset();
  18279. this._renderingManager.reset();
  18280. this._processedMaterials.reset();
  18281. this._activeParticleSystems.reset();
  18282. this._activeSkeletons.reset();
  18283. this._softwareSkinnedMeshes.reset();
  18284. if (this._boundingBoxRenderer) {
  18285. this._boundingBoxRenderer.reset();
  18286. }
  18287. // Meshes
  18288. var meshes;
  18289. var len;
  18290. if (this._selectionOctree) {
  18291. var selection = this._selectionOctree.select(this._frustumPlanes);
  18292. meshes = selection.data;
  18293. len = selection.length;
  18294. }
  18295. else {
  18296. len = this.meshes.length;
  18297. meshes = this.meshes;
  18298. }
  18299. for (var meshIndex = 0; meshIndex < len; meshIndex++) {
  18300. var mesh = meshes[meshIndex];
  18301. if (mesh.isBlocked) {
  18302. continue;
  18303. }
  18304. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  18305. if (!mesh.isReady() || !mesh.isEnabled()) {
  18306. continue;
  18307. }
  18308. mesh.computeWorldMatrix();
  18309. // Intersections
  18310. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  18311. this._meshesForIntersections.pushNoDuplicate(mesh);
  18312. }
  18313. // Switch to current LOD
  18314. var meshLOD = mesh.getLOD(this.activeCamera);
  18315. if (!meshLOD) {
  18316. continue;
  18317. }
  18318. mesh._preActivate();
  18319. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  18320. this._activeMeshes.push(mesh);
  18321. this.activeCamera._activeMeshes.push(mesh);
  18322. mesh._activate(this._renderId);
  18323. if (meshLOD !== mesh) {
  18324. meshLOD._activate(this._renderId);
  18325. }
  18326. this._activeMesh(mesh, meshLOD);
  18327. }
  18328. }
  18329. // Particle systems
  18330. this._particlesDuration.beginMonitoring();
  18331. var beforeParticlesDate = BABYLON.Tools.Now;
  18332. if (this.particlesEnabled) {
  18333. BABYLON.Tools.StartPerformanceCounter("Particles", this.particleSystems.length > 0);
  18334. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  18335. var particleSystem = this.particleSystems[particleIndex];
  18336. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  18337. continue;
  18338. }
  18339. var emitter = particleSystem.emitter;
  18340. if (!emitter.position || emitter.isEnabled()) {
  18341. this._activeParticleSystems.push(particleSystem);
  18342. particleSystem.animate();
  18343. this._renderingManager.dispatchParticles(particleSystem);
  18344. }
  18345. }
  18346. BABYLON.Tools.EndPerformanceCounter("Particles", this.particleSystems.length > 0);
  18347. }
  18348. this._particlesDuration.endMonitoring(false);
  18349. };
  18350. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  18351. if (mesh.skeleton && this.skeletonsEnabled) {
  18352. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  18353. mesh.skeleton.prepare();
  18354. }
  18355. if (!mesh.computeBonesUsingShaders) {
  18356. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  18357. }
  18358. }
  18359. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  18360. this.getBoundingBoxRenderer().renderList.push(sourceMesh.getBoundingInfo().boundingBox);
  18361. }
  18362. if (mesh && mesh.subMeshes) {
  18363. // Submeshes Octrees
  18364. var len;
  18365. var subMeshes;
  18366. if (mesh._submeshesOctree && mesh.useOctreeForRenderingSelection) {
  18367. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  18368. len = intersections.length;
  18369. subMeshes = intersections.data;
  18370. }
  18371. else {
  18372. subMeshes = mesh.subMeshes;
  18373. len = subMeshes.length;
  18374. }
  18375. for (var subIndex = 0; subIndex < len; subIndex++) {
  18376. var subMesh = subMeshes[subIndex];
  18377. this._evaluateSubMesh(subMesh, mesh);
  18378. }
  18379. }
  18380. };
  18381. Scene.prototype.updateTransformMatrix = function (force) {
  18382. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  18383. };
  18384. Scene.prototype._renderForCamera = function (camera) {
  18385. var engine = this._engine;
  18386. var startTime = BABYLON.Tools.Now;
  18387. this.activeCamera = camera;
  18388. if (!this.activeCamera)
  18389. throw new Error("Active camera not set");
  18390. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18391. // Viewport
  18392. engine.setViewport(this.activeCamera.viewport);
  18393. // Camera
  18394. this.resetCachedMaterial();
  18395. this._renderId++;
  18396. this.updateTransformMatrix();
  18397. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  18398. // Meshes
  18399. this._evaluateActiveMeshesDuration.beginMonitoring();
  18400. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  18401. this._evaluateActiveMeshes();
  18402. this._evaluateActiveMeshesDuration.endMonitoring(false);
  18403. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  18404. // Software skinning
  18405. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  18406. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  18407. mesh.applySkeleton(mesh.skeleton);
  18408. }
  18409. // Render targets
  18410. this._renderTargetsDuration.beginMonitoring();
  18411. var needsRestoreFrameBuffer = false;
  18412. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18413. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  18414. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  18415. }
  18416. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  18417. this._intermediateRendering = true;
  18418. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18419. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  18420. var renderTarget = this._renderTargets.data[renderIndex];
  18421. if (renderTarget._shouldRender()) {
  18422. this._renderId++;
  18423. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  18424. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  18425. }
  18426. }
  18427. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  18428. this._intermediateRendering = false;
  18429. this._renderId++;
  18430. needsRestoreFrameBuffer = true; // Restore back buffer
  18431. }
  18432. // Render HighlightLayer Texture
  18433. var stencilState = this._engine.getStencilBuffer();
  18434. var renderhighlights = false;
  18435. if (this.renderTargetsEnabled && this.highlightLayers && this.highlightLayers.length > 0) {
  18436. this._intermediateRendering = true;
  18437. for (var i = 0; i < this.highlightLayers.length; i++) {
  18438. var highlightLayer = this.highlightLayers[i];
  18439. if (highlightLayer.shouldRender() &&
  18440. (!highlightLayer.camera ||
  18441. (highlightLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === highlightLayer.camera) ||
  18442. (highlightLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && highlightLayer.camera._rigCameras.indexOf(camera) > -1))) {
  18443. renderhighlights = true;
  18444. var renderTarget = highlightLayer._mainTexture;
  18445. if (renderTarget._shouldRender()) {
  18446. this._renderId++;
  18447. renderTarget.render(false, false);
  18448. needsRestoreFrameBuffer = true;
  18449. }
  18450. }
  18451. }
  18452. this._intermediateRendering = false;
  18453. this._renderId++;
  18454. }
  18455. if (needsRestoreFrameBuffer) {
  18456. engine.restoreDefaultFramebuffer(); // Restore back buffer
  18457. }
  18458. this._renderTargetsDuration.endMonitoring(false);
  18459. // Prepare Frame
  18460. this.postProcessManager._prepareFrame();
  18461. this._renderDuration.beginMonitoring();
  18462. // Backgrounds
  18463. var layerIndex;
  18464. var layer;
  18465. if (this.layers.length) {
  18466. engine.setDepthBuffer(false);
  18467. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18468. layer = this.layers[layerIndex];
  18469. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18470. layer.render();
  18471. }
  18472. }
  18473. engine.setDepthBuffer(true);
  18474. }
  18475. // Render
  18476. BABYLON.Tools.StartPerformanceCounter("Main render");
  18477. // Activate HighlightLayer stencil
  18478. if (renderhighlights) {
  18479. this._engine.setStencilBuffer(true);
  18480. }
  18481. this._renderingManager.render(null, null, true, true);
  18482. // Restore HighlightLayer stencil
  18483. if (renderhighlights) {
  18484. this._engine.setStencilBuffer(stencilState);
  18485. }
  18486. BABYLON.Tools.EndPerformanceCounter("Main render");
  18487. // Bounding boxes
  18488. if (this._boundingBoxRenderer) {
  18489. this._boundingBoxRenderer.render();
  18490. }
  18491. // Lens flares
  18492. if (this.lensFlaresEnabled) {
  18493. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18494. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  18495. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  18496. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  18497. lensFlareSystem.render();
  18498. }
  18499. }
  18500. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  18501. }
  18502. // Foregrounds
  18503. if (this.layers.length) {
  18504. engine.setDepthBuffer(false);
  18505. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  18506. layer = this.layers[layerIndex];
  18507. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  18508. layer.render();
  18509. }
  18510. }
  18511. engine.setDepthBuffer(true);
  18512. }
  18513. // Highlight Layer
  18514. if (renderhighlights) {
  18515. engine.setDepthBuffer(false);
  18516. for (var i = 0; i < this.highlightLayers.length; i++) {
  18517. if (this.highlightLayers[i].shouldRender()) {
  18518. this.highlightLayers[i].render();
  18519. }
  18520. }
  18521. engine.setDepthBuffer(true);
  18522. }
  18523. this._renderDuration.endMonitoring(false);
  18524. // Finalize frame
  18525. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  18526. // Update camera
  18527. this.activeCamera._updateFromScene();
  18528. // Reset some special arrays
  18529. this._renderTargets.reset();
  18530. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  18531. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  18532. };
  18533. Scene.prototype._processSubCameras = function (camera) {
  18534. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  18535. this._renderForCamera(camera);
  18536. return;
  18537. }
  18538. // rig cameras
  18539. for (var index = 0; index < camera._rigCameras.length; index++) {
  18540. this._renderForCamera(camera._rigCameras[index]);
  18541. }
  18542. this.activeCamera = camera;
  18543. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  18544. // Update camera
  18545. this.activeCamera._updateFromScene();
  18546. };
  18547. Scene.prototype._checkIntersections = function () {
  18548. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  18549. var sourceMesh = this._meshesForIntersections.data[index];
  18550. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  18551. var action = sourceMesh.actionManager.actions[actionIndex];
  18552. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18553. var parameters = action.getTriggerParameter();
  18554. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  18555. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  18556. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  18557. if (areIntersecting && currentIntersectionInProgress === -1) {
  18558. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  18559. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18560. sourceMesh._intersectionsInProgress.push(otherMesh);
  18561. }
  18562. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18563. sourceMesh._intersectionsInProgress.push(otherMesh);
  18564. }
  18565. }
  18566. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  18567. //They intersected, and now they don't.
  18568. //is this trigger an exit trigger? execute an event.
  18569. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18570. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, null, otherMesh));
  18571. }
  18572. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  18573. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  18574. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  18575. }
  18576. }
  18577. }
  18578. }
  18579. }
  18580. };
  18581. Scene.prototype.render = function () {
  18582. if (this.isDisposed) {
  18583. return;
  18584. }
  18585. this._lastFrameDuration.beginMonitoring();
  18586. this._particlesDuration.fetchNewFrame();
  18587. this._spritesDuration.fetchNewFrame();
  18588. this._activeParticles.fetchNewFrame();
  18589. this._renderDuration.fetchNewFrame();
  18590. this._renderTargetsDuration.fetchNewFrame();
  18591. this._evaluateActiveMeshesDuration.fetchNewFrame();
  18592. this._totalVertices.fetchNewFrame();
  18593. this._activeIndices.fetchNewFrame();
  18594. this._activeBones.fetchNewFrame();
  18595. this.getEngine().drawCallsPerfCounter.fetchNewFrame();
  18596. this._meshesForIntersections.reset();
  18597. this.resetCachedMaterial();
  18598. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  18599. // Actions
  18600. if (this.actionManager) {
  18601. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger, null);
  18602. }
  18603. //Simplification Queue
  18604. if (this.simplificationQueue && !this.simplificationQueue.running) {
  18605. this.simplificationQueue.executeNext();
  18606. }
  18607. if (this._engine.isDeterministicLockStep()) {
  18608. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) / 1000;
  18609. var defaultTimeStep = (60.0 / 1000.0);
  18610. if (this._physicsEngine) {
  18611. defaultTimeStep = this._physicsEngine.getTimeStep();
  18612. }
  18613. var maxSubSteps = this._engine.getLockstepMaxSteps();
  18614. this._timeAccumulator += deltaTime;
  18615. // compute the amount of fixed steps we should have taken since the last step
  18616. var internalSteps = Math.floor(this._timeAccumulator / defaultTimeStep);
  18617. internalSteps = Math.min(internalSteps, maxSubSteps);
  18618. for (this._currentInternalStep = 0; this._currentInternalStep < internalSteps; this._currentInternalStep++) {
  18619. this.onBeforeStepObservable.notifyObservers(this);
  18620. // Animations
  18621. this._animationRatio = defaultTimeStep * (60.0 / 1000.0);
  18622. this._animate();
  18623. // Physics
  18624. if (this._physicsEngine) {
  18625. BABYLON.Tools.StartPerformanceCounter("Physics");
  18626. this._physicsEngine._step(defaultTimeStep);
  18627. BABYLON.Tools.EndPerformanceCounter("Physics");
  18628. }
  18629. this._timeAccumulator -= defaultTimeStep;
  18630. this.onAfterStepObservable.notifyObservers(this);
  18631. this._currentStepId++;
  18632. if ((internalSteps > 1) && (this._currentInternalStep != internalSteps - 1)) {
  18633. // Q: can this be optimized by putting some code in the afterStep callback?
  18634. // I had to put this code here, otherwise mesh attached to bones of another mesh skeleton,
  18635. // would return incorrect positions for internal stepIds (non-rendered steps)
  18636. this._evaluateActiveMeshes();
  18637. }
  18638. }
  18639. }
  18640. else {
  18641. // Animations
  18642. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  18643. this._animationRatio = deltaTime * (60.0 / 1000.0);
  18644. this._animate();
  18645. // Physics
  18646. if (this._physicsEngine) {
  18647. BABYLON.Tools.StartPerformanceCounter("Physics");
  18648. this._physicsEngine._step(deltaTime / 1000.0);
  18649. BABYLON.Tools.EndPerformanceCounter("Physics");
  18650. }
  18651. }
  18652. // Before render
  18653. this.onBeforeRenderObservable.notifyObservers(this);
  18654. // Customs render targets
  18655. this._renderTargetsDuration.beginMonitoring();
  18656. var beforeRenderTargetDate = BABYLON.Tools.Now;
  18657. var engine = this.getEngine();
  18658. var currentActiveCamera = this.activeCamera;
  18659. if (this.renderTargetsEnabled) {
  18660. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18661. this._intermediateRendering = true;
  18662. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  18663. var renderTarget = this.customRenderTargets[customIndex];
  18664. if (renderTarget._shouldRender()) {
  18665. this._renderId++;
  18666. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  18667. if (!this.activeCamera)
  18668. throw new Error("Active camera not set");
  18669. // Viewport
  18670. engine.setViewport(this.activeCamera.viewport);
  18671. // Camera
  18672. this.updateTransformMatrix();
  18673. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  18674. }
  18675. }
  18676. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  18677. this._intermediateRendering = false;
  18678. this._renderId++;
  18679. }
  18680. // Restore back buffer
  18681. if (this.customRenderTargets.length > 0) {
  18682. engine.restoreDefaultFramebuffer();
  18683. }
  18684. this._renderTargetsDuration.endMonitoring();
  18685. this.activeCamera = currentActiveCamera;
  18686. // Procedural textures
  18687. if (this.proceduralTexturesEnabled) {
  18688. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18689. for (var proceduralIndex = 0; proceduralIndex < this._proceduralTextures.length; proceduralIndex++) {
  18690. var proceduralTexture = this._proceduralTextures[proceduralIndex];
  18691. if (proceduralTexture._shouldRender()) {
  18692. proceduralTexture.render();
  18693. }
  18694. }
  18695. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this._proceduralTextures.length > 0);
  18696. }
  18697. // Clear
  18698. if (this.autoClearDepthAndStencil || this.autoClear) {
  18699. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  18700. }
  18701. // Shadows
  18702. if (this.shadowsEnabled) {
  18703. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  18704. var light = this.lights[lightIndex];
  18705. var shadowGenerator = light.getShadowGenerator();
  18706. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  18707. var shadowMap = shadowGenerator.getShadowMap();
  18708. if (shadowMap.getScene().textures.indexOf(shadowMap) !== -1) {
  18709. this._renderTargets.push(shadowMap);
  18710. }
  18711. }
  18712. }
  18713. }
  18714. // Depth renderer
  18715. if (this._depthRenderer) {
  18716. this._renderTargets.push(this._depthRenderer.getDepthMap());
  18717. }
  18718. // Geometry renderer
  18719. if (this._geometryBufferRenderer) {
  18720. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  18721. }
  18722. // RenderPipeline
  18723. if (this._postProcessRenderPipelineManager) {
  18724. this._postProcessRenderPipelineManager.update();
  18725. }
  18726. // Multi-cameras?
  18727. if (this.activeCameras.length > 0) {
  18728. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  18729. if (cameraIndex > 0) {
  18730. this._engine.clear(null, false, true, true);
  18731. }
  18732. this._processSubCameras(this.activeCameras[cameraIndex]);
  18733. }
  18734. }
  18735. else {
  18736. if (!this.activeCamera) {
  18737. throw new Error("No camera defined");
  18738. }
  18739. this._processSubCameras(this.activeCamera);
  18740. }
  18741. // Intersection checks
  18742. this._checkIntersections();
  18743. // Update the audio listener attached to the camera
  18744. if (BABYLON.AudioEngine) {
  18745. this._updateAudioParameters();
  18746. }
  18747. // After render
  18748. if (this.afterRender) {
  18749. this.afterRender();
  18750. }
  18751. this.onAfterRenderObservable.notifyObservers(this);
  18752. // Cleaning
  18753. for (var index = 0; index < this._toBeDisposed.length; index++) {
  18754. this._toBeDisposed.data[index].dispose();
  18755. this._toBeDisposed[index] = null;
  18756. }
  18757. this._toBeDisposed.reset();
  18758. if (this.dumpNextRenderTargets) {
  18759. this.dumpNextRenderTargets = false;
  18760. }
  18761. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  18762. this._lastFrameDuration.endMonitoring();
  18763. this._totalMeshesCounter.addCount(this.meshes.length, true);
  18764. this._totalLightsCounter.addCount(this.lights.length, true);
  18765. this._totalMaterialsCounter.addCount(this.materials.length, true);
  18766. this._totalTexturesCounter.addCount(this.textures.length, true);
  18767. this._activeBones.addCount(0, true);
  18768. this._activeIndices.addCount(0, true);
  18769. this._activeParticles.addCount(0, true);
  18770. };
  18771. Scene.prototype._updateAudioParameters = function () {
  18772. if (!this.audioEnabled || (this.mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  18773. return;
  18774. }
  18775. var listeningCamera;
  18776. var audioEngine = BABYLON.Engine.audioEngine;
  18777. if (this.activeCameras.length > 0) {
  18778. listeningCamera = this.activeCameras[0];
  18779. }
  18780. else {
  18781. listeningCamera = this.activeCamera;
  18782. }
  18783. if (listeningCamera && audioEngine.canUseWebAudio) {
  18784. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  18785. // for VR cameras
  18786. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  18787. listeningCamera = listeningCamera.rigCameras[0];
  18788. }
  18789. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  18790. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  18791. cameraDirection.normalize();
  18792. // To avoid some errors on GearVR
  18793. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  18794. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  18795. }
  18796. var i;
  18797. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18798. var sound = this.mainSoundTrack.soundCollection[i];
  18799. if (sound.useCustomAttenuation) {
  18800. sound.updateDistanceFromListener();
  18801. }
  18802. }
  18803. for (i = 0; i < this.soundTracks.length; i++) {
  18804. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18805. sound = this.soundTracks[i].soundCollection[j];
  18806. if (sound.useCustomAttenuation) {
  18807. sound.updateDistanceFromListener();
  18808. }
  18809. }
  18810. }
  18811. }
  18812. };
  18813. Object.defineProperty(Scene.prototype, "audioEnabled", {
  18814. // Audio
  18815. get: function () {
  18816. return this._audioEnabled;
  18817. },
  18818. set: function (value) {
  18819. this._audioEnabled = value;
  18820. if (BABYLON.AudioEngine) {
  18821. if (this._audioEnabled) {
  18822. this._enableAudio();
  18823. }
  18824. else {
  18825. this._disableAudio();
  18826. }
  18827. }
  18828. },
  18829. enumerable: true,
  18830. configurable: true
  18831. });
  18832. Scene.prototype._disableAudio = function () {
  18833. var i;
  18834. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18835. this.mainSoundTrack.soundCollection[i].pause();
  18836. }
  18837. for (i = 0; i < this.soundTracks.length; i++) {
  18838. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18839. this.soundTracks[i].soundCollection[j].pause();
  18840. }
  18841. }
  18842. };
  18843. Scene.prototype._enableAudio = function () {
  18844. var i;
  18845. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  18846. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  18847. this.mainSoundTrack.soundCollection[i].play();
  18848. }
  18849. }
  18850. for (i = 0; i < this.soundTracks.length; i++) {
  18851. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  18852. if (this.soundTracks[i].soundCollection[j].isPaused) {
  18853. this.soundTracks[i].soundCollection[j].play();
  18854. }
  18855. }
  18856. }
  18857. };
  18858. Object.defineProperty(Scene.prototype, "headphone", {
  18859. get: function () {
  18860. return this._headphone;
  18861. },
  18862. set: function (value) {
  18863. this._headphone = value;
  18864. if (BABYLON.AudioEngine) {
  18865. if (this._headphone) {
  18866. this._switchAudioModeForHeadphones();
  18867. }
  18868. else {
  18869. this._switchAudioModeForNormalSpeakers();
  18870. }
  18871. }
  18872. },
  18873. enumerable: true,
  18874. configurable: true
  18875. });
  18876. Scene.prototype._switchAudioModeForHeadphones = function () {
  18877. this.mainSoundTrack.switchPanningModelToHRTF();
  18878. for (var i = 0; i < this.soundTracks.length; i++) {
  18879. this.soundTracks[i].switchPanningModelToHRTF();
  18880. }
  18881. };
  18882. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  18883. this.mainSoundTrack.switchPanningModelToEqualPower();
  18884. for (var i = 0; i < this.soundTracks.length; i++) {
  18885. this.soundTracks[i].switchPanningModelToEqualPower();
  18886. }
  18887. };
  18888. Scene.prototype.enableDepthRenderer = function () {
  18889. if (this._depthRenderer) {
  18890. return this._depthRenderer;
  18891. }
  18892. this._depthRenderer = new BABYLON.DepthRenderer(this);
  18893. return this._depthRenderer;
  18894. };
  18895. Scene.prototype.disableDepthRenderer = function () {
  18896. if (!this._depthRenderer) {
  18897. return;
  18898. }
  18899. this._depthRenderer.dispose();
  18900. this._depthRenderer = null;
  18901. };
  18902. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  18903. if (ratio === void 0) { ratio = 1; }
  18904. if (this._geometryBufferRenderer) {
  18905. return this._geometryBufferRenderer;
  18906. }
  18907. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  18908. if (!this._geometryBufferRenderer.isSupported) {
  18909. this._geometryBufferRenderer = null;
  18910. }
  18911. return this._geometryBufferRenderer;
  18912. };
  18913. Scene.prototype.disableGeometryBufferRenderer = function () {
  18914. if (!this._geometryBufferRenderer) {
  18915. return;
  18916. }
  18917. this._geometryBufferRenderer.dispose();
  18918. this._geometryBufferRenderer = null;
  18919. };
  18920. Scene.prototype.freezeMaterials = function () {
  18921. for (var i = 0; i < this.materials.length; i++) {
  18922. this.materials[i].freeze();
  18923. }
  18924. };
  18925. Scene.prototype.unfreezeMaterials = function () {
  18926. for (var i = 0; i < this.materials.length; i++) {
  18927. this.materials[i].unfreeze();
  18928. }
  18929. };
  18930. Scene.prototype.dispose = function () {
  18931. this.beforeRender = null;
  18932. this.afterRender = null;
  18933. this.skeletons = [];
  18934. this.morphTargetManagers = [];
  18935. this.importedMeshesFiles = new Array();
  18936. this.resetCachedMaterial();
  18937. if (this._depthRenderer) {
  18938. this._depthRenderer.dispose();
  18939. }
  18940. if (this._gamepadManager) {
  18941. this._gamepadManager.dispose();
  18942. this._gamepadManager = null;
  18943. }
  18944. // Smart arrays
  18945. if (this.activeCamera) {
  18946. this.activeCamera._activeMeshes.dispose();
  18947. this.activeCamera = null;
  18948. }
  18949. this._activeMeshes.dispose();
  18950. this._renderingManager.dispose();
  18951. this._processedMaterials.dispose();
  18952. this._activeParticleSystems.dispose();
  18953. this._activeSkeletons.dispose();
  18954. this._softwareSkinnedMeshes.dispose();
  18955. this._renderTargets.dispose();
  18956. if (this._boundingBoxRenderer) {
  18957. this._boundingBoxRenderer.dispose();
  18958. }
  18959. this._meshesForIntersections.dispose();
  18960. this._toBeDisposed.dispose();
  18961. // Debug layer
  18962. if (this._debugLayer) {
  18963. this._debugLayer.hide();
  18964. }
  18965. // Events
  18966. this.onDisposeObservable.notifyObservers(this);
  18967. this.onDisposeObservable.clear();
  18968. this.onBeforeRenderObservable.clear();
  18969. this.onAfterRenderObservable.clear();
  18970. this.detachControl();
  18971. // Release sounds & sounds tracks
  18972. if (BABYLON.AudioEngine) {
  18973. this.disposeSounds();
  18974. }
  18975. // VR Helper
  18976. if (this.VRHelper) {
  18977. this.VRHelper.dispose();
  18978. }
  18979. // Detach cameras
  18980. var canvas = this._engine.getRenderingCanvas();
  18981. var index;
  18982. for (index = 0; index < this.cameras.length; index++) {
  18983. this.cameras[index].detachControl(canvas);
  18984. }
  18985. // Release lights
  18986. while (this.lights.length) {
  18987. this.lights[0].dispose();
  18988. }
  18989. // Release meshes
  18990. while (this.meshes.length) {
  18991. this.meshes[0].dispose(true);
  18992. }
  18993. // Release cameras
  18994. while (this.cameras.length) {
  18995. this.cameras[0].dispose();
  18996. }
  18997. // Release materials
  18998. if (this.defaultMaterial) {
  18999. this.defaultMaterial.dispose();
  19000. }
  19001. while (this.multiMaterials.length) {
  19002. this.multiMaterials[0].dispose();
  19003. }
  19004. while (this.materials.length) {
  19005. this.materials[0].dispose();
  19006. }
  19007. // Release particles
  19008. while (this.particleSystems.length) {
  19009. this.particleSystems[0].dispose();
  19010. }
  19011. // Release sprites
  19012. while (this.spriteManagers.length) {
  19013. this.spriteManagers[0].dispose();
  19014. }
  19015. // Release postProcesses
  19016. while (this.postProcesses.length) {
  19017. this.postProcesses[0].dispose();
  19018. }
  19019. // Release layers
  19020. while (this.layers.length) {
  19021. this.layers[0].dispose();
  19022. }
  19023. while (this.highlightLayers.length) {
  19024. this.highlightLayers[0].dispose();
  19025. }
  19026. // Release textures
  19027. while (this.textures.length) {
  19028. this.textures[0].dispose();
  19029. }
  19030. // Release UBO
  19031. this._sceneUbo.dispose();
  19032. // Post-processes
  19033. this.postProcessManager.dispose();
  19034. // Physics
  19035. if (this._physicsEngine) {
  19036. this.disablePhysicsEngine();
  19037. }
  19038. // Remove from engine
  19039. index = this._engine.scenes.indexOf(this);
  19040. if (index > -1) {
  19041. this._engine.scenes.splice(index, 1);
  19042. }
  19043. this._engine.wipeCaches();
  19044. this._engine = null;
  19045. this.defaultMaterial = null;
  19046. this.multiMaterials = null;
  19047. this.materials = null;
  19048. };
  19049. Object.defineProperty(Scene.prototype, "isDisposed", {
  19050. get: function () {
  19051. return !this._engine;
  19052. },
  19053. enumerable: true,
  19054. configurable: true
  19055. });
  19056. // Release sounds & sounds tracks
  19057. Scene.prototype.disposeSounds = function () {
  19058. this.mainSoundTrack.dispose();
  19059. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  19060. this.soundTracks[scIndex].dispose();
  19061. }
  19062. };
  19063. // Octrees
  19064. Scene.prototype.getWorldExtends = function () {
  19065. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  19066. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  19067. for (var index = 0; index < this.meshes.length; index++) {
  19068. var mesh = this.meshes[index];
  19069. mesh.computeWorldMatrix(true);
  19070. var minBox = mesh.getBoundingInfo().boundingBox.minimumWorld;
  19071. var maxBox = mesh.getBoundingInfo().boundingBox.maximumWorld;
  19072. BABYLON.Tools.CheckExtends(minBox, min, max);
  19073. BABYLON.Tools.CheckExtends(maxBox, min, max);
  19074. }
  19075. return {
  19076. min: min,
  19077. max: max
  19078. };
  19079. };
  19080. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  19081. if (maxCapacity === void 0) { maxCapacity = 64; }
  19082. if (maxDepth === void 0) { maxDepth = 2; }
  19083. if (!this._selectionOctree) {
  19084. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  19085. }
  19086. var worldExtends = this.getWorldExtends();
  19087. // Update octree
  19088. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  19089. return this._selectionOctree;
  19090. };
  19091. // Picking
  19092. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  19093. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  19094. var engine = this._engine;
  19095. if (!camera) {
  19096. if (!this.activeCamera)
  19097. throw new Error("Active camera not set");
  19098. camera = this.activeCamera;
  19099. }
  19100. var cameraViewport = camera.viewport;
  19101. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19102. // Moving coordinates to local viewport world
  19103. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19104. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19105. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  19106. // return BABYLON.Ray.CreateNew(x / window.devicePixelRatio, y / window.devicePixelRatio, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), camera.getViewMatrix(), camera.getProjectionMatrix());
  19107. };
  19108. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  19109. if (!BABYLON.PickingInfo) {
  19110. return null;
  19111. }
  19112. var engine = this._engine;
  19113. if (!camera) {
  19114. if (!this.activeCamera)
  19115. throw new Error("Active camera not set");
  19116. camera = this.activeCamera;
  19117. }
  19118. var cameraViewport = camera.viewport;
  19119. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  19120. var identity = BABYLON.Matrix.Identity();
  19121. // Moving coordinates to local viewport world
  19122. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  19123. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  19124. return BABYLON.Ray.CreateNew(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  19125. };
  19126. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  19127. if (!BABYLON.PickingInfo) {
  19128. return null;
  19129. }
  19130. var pickingInfo = null;
  19131. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19132. var mesh = this.meshes[meshIndex];
  19133. if (predicate) {
  19134. if (!predicate(mesh)) {
  19135. continue;
  19136. }
  19137. }
  19138. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19139. continue;
  19140. }
  19141. var world = mesh.getWorldMatrix();
  19142. var ray = rayFunction(world);
  19143. var result = mesh.intersects(ray, fastCheck);
  19144. if (!result || !result.hit)
  19145. continue;
  19146. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19147. continue;
  19148. pickingInfo = result;
  19149. if (fastCheck) {
  19150. break;
  19151. }
  19152. }
  19153. return pickingInfo || new BABYLON.PickingInfo();
  19154. };
  19155. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  19156. if (!BABYLON.PickingInfo) {
  19157. return null;
  19158. }
  19159. var pickingInfos = new Array();
  19160. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  19161. var mesh = this.meshes[meshIndex];
  19162. if (predicate) {
  19163. if (!predicate(mesh)) {
  19164. continue;
  19165. }
  19166. }
  19167. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  19168. continue;
  19169. }
  19170. var world = mesh.getWorldMatrix();
  19171. var ray = rayFunction(world);
  19172. var result = mesh.intersects(ray, false);
  19173. if (!result || !result.hit)
  19174. continue;
  19175. pickingInfos.push(result);
  19176. }
  19177. return pickingInfos;
  19178. };
  19179. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  19180. if (!BABYLON.PickingInfo) {
  19181. return null;
  19182. }
  19183. var pickingInfo = null;
  19184. camera = camera || this.activeCamera;
  19185. if (this.spriteManagers.length > 0) {
  19186. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  19187. var spriteManager = this.spriteManagers[spriteIndex];
  19188. if (!spriteManager.isPickable) {
  19189. continue;
  19190. }
  19191. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  19192. if (!result || !result.hit)
  19193. continue;
  19194. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  19195. continue;
  19196. pickingInfo = result;
  19197. if (fastCheck) {
  19198. break;
  19199. }
  19200. }
  19201. }
  19202. return pickingInfo || new BABYLON.PickingInfo();
  19203. };
  19204. /** Launch a ray to try to pick a mesh in the scene
  19205. * @param x position on screen
  19206. * @param y position on screen
  19207. * @param 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
  19208. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19209. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19210. */
  19211. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  19212. var _this = this;
  19213. return this._internalPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate, fastCheck);
  19214. };
  19215. /** Launch a ray to try to pick a sprite in the scene
  19216. * @param x position on screen
  19217. * @param y position on screen
  19218. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19219. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19220. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19221. */
  19222. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  19223. return this._internalPickSprites(this.createPickingRayInCameraSpace(x, y, camera), predicate, fastCheck, camera);
  19224. };
  19225. /** Use the given ray to pick a mesh in the scene
  19226. * @param ray The ray to use to pick meshes
  19227. * @param predicate Predicate function used to determine eligible sprites. Can be set to null. In this case, a sprite must have isPickable set to true
  19228. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  19229. */
  19230. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  19231. var _this = this;
  19232. return this._internalPick(function (world) {
  19233. if (!_this._pickWithRayInverseMatrix) {
  19234. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19235. }
  19236. world.invertToRef(_this._pickWithRayInverseMatrix);
  19237. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19238. }, predicate, fastCheck);
  19239. };
  19240. /**
  19241. * Launch a ray to try to pick a mesh in the scene
  19242. * @param x X position on screen
  19243. * @param y Y position on screen
  19244. * @param 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
  19245. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  19246. */
  19247. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  19248. var _this = this;
  19249. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera); }, predicate);
  19250. };
  19251. /**
  19252. * Launch a ray to try to pick a mesh in the scene
  19253. * @param ray Ray to use
  19254. * @param 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
  19255. */
  19256. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  19257. var _this = this;
  19258. return this._internalMultiPick(function (world) {
  19259. if (!_this._pickWithRayInverseMatrix) {
  19260. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  19261. }
  19262. world.invertToRef(_this._pickWithRayInverseMatrix);
  19263. return BABYLON.Ray.Transform(ray, _this._pickWithRayInverseMatrix);
  19264. }, predicate);
  19265. };
  19266. Scene.prototype.setPointerOverMesh = function (mesh) {
  19267. if (this._pointerOverMesh === mesh) {
  19268. return;
  19269. }
  19270. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19271. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19272. }
  19273. this._pointerOverMesh = mesh;
  19274. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  19275. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  19276. }
  19277. };
  19278. Scene.prototype.getPointerOverMesh = function () {
  19279. return this._pointerOverMesh;
  19280. };
  19281. Scene.prototype.setPointerOverSprite = function (sprite) {
  19282. if (this._pointerOverSprite === sprite) {
  19283. return;
  19284. }
  19285. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19286. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19287. }
  19288. this._pointerOverSprite = sprite;
  19289. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  19290. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  19291. }
  19292. };
  19293. Scene.prototype.getPointerOverSprite = function () {
  19294. return this._pointerOverSprite;
  19295. };
  19296. // Physics
  19297. Scene.prototype.getPhysicsEngine = function () {
  19298. return this._physicsEngine;
  19299. };
  19300. /**
  19301. * Enables physics to the current scene
  19302. * @param {BABYLON.Vector3} [gravity] - the scene's gravity for the physics engine
  19303. * @param {BABYLON.IPhysicsEnginePlugin} [plugin] - The physics engine to be used. defaults to OimoJS.
  19304. * @return {boolean} was the physics engine initialized
  19305. */
  19306. Scene.prototype.enablePhysics = function (gravity, plugin) {
  19307. if (this._physicsEngine) {
  19308. return true;
  19309. }
  19310. try {
  19311. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  19312. return true;
  19313. }
  19314. catch (e) {
  19315. BABYLON.Tools.Error(e.message);
  19316. return false;
  19317. }
  19318. };
  19319. Scene.prototype.disablePhysicsEngine = function () {
  19320. if (!this._physicsEngine) {
  19321. return;
  19322. }
  19323. this._physicsEngine.dispose();
  19324. this._physicsEngine = undefined;
  19325. };
  19326. Scene.prototype.isPhysicsEnabled = function () {
  19327. return this._physicsEngine !== undefined;
  19328. };
  19329. Scene.prototype.deleteCompoundImpostor = function (compound) {
  19330. var mesh = compound.parts[0].mesh;
  19331. mesh.physicsImpostor.dispose();
  19332. mesh.physicsImpostor = null;
  19333. };
  19334. // Misc.
  19335. Scene.prototype._rebuildGeometries = function () {
  19336. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  19337. var geometry = _a[_i];
  19338. geometry._rebuild();
  19339. }
  19340. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  19341. var mesh = _c[_b];
  19342. mesh._rebuild();
  19343. }
  19344. for (var _d = 0, _e = this.postProcesses; _d < _e.length; _d++) {
  19345. var postprocess = _e[_d];
  19346. postprocess._rebuild();
  19347. }
  19348. for (var _f = 0, _g = this.layers; _f < _g.length; _f++) {
  19349. var layer = _g[_f];
  19350. layer._rebuild();
  19351. }
  19352. };
  19353. Scene.prototype._rebuildTextures = function () {
  19354. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  19355. var texture = _a[_i];
  19356. texture._rebuild();
  19357. }
  19358. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  19359. };
  19360. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  19361. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  19362. if (replace === void 0) { replace = false; }
  19363. if (attachCameraControls === void 0) { attachCameraControls = false; }
  19364. // Dispose existing camera or light in replace mode.
  19365. if (replace) {
  19366. if (this.activeCamera) {
  19367. this.activeCamera.dispose();
  19368. this.activeCamera = null;
  19369. }
  19370. if (this.lights) {
  19371. for (var i = 0; i < this.lights.length; i++) {
  19372. this.lights[i].dispose();
  19373. }
  19374. }
  19375. }
  19376. // Light
  19377. if (this.lights.length === 0) {
  19378. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  19379. }
  19380. // Camera
  19381. if (!this.activeCamera) {
  19382. var worldExtends = this.getWorldExtends();
  19383. var worldSize = worldExtends.max.subtract(worldExtends.min);
  19384. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  19385. var camera;
  19386. var radius = worldSize.length() * 1.5;
  19387. if (createArcRotateCamera) {
  19388. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  19389. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  19390. arcRotateCamera.wheelPrecision = 100 / radius;
  19391. camera = arcRotateCamera;
  19392. }
  19393. else {
  19394. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  19395. freeCamera.setTarget(worldCenter);
  19396. camera = freeCamera;
  19397. }
  19398. camera.minZ = radius * 0.01;
  19399. camera.maxZ = radius * 100;
  19400. camera.speed = radius * 0.2;
  19401. this.activeCamera = camera;
  19402. if (attachCameraControls) {
  19403. camera.attachControl(this.getEngine().getRenderingCanvas());
  19404. }
  19405. }
  19406. };
  19407. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur) {
  19408. if (pbr === void 0) { pbr = false; }
  19409. if (scale === void 0) { scale = 1000; }
  19410. if (blur === void 0) { blur = 0; }
  19411. if (environmentTexture) {
  19412. this.environmentTexture = environmentTexture;
  19413. }
  19414. if (!this.environmentTexture) {
  19415. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  19416. return;
  19417. }
  19418. // Skybox
  19419. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  19420. if (pbr) {
  19421. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  19422. hdrSkyboxMaterial.backFaceCulling = false;
  19423. hdrSkyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19424. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19425. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  19426. hdrSkyboxMaterial.disableLighting = true;
  19427. hdrSkyboxMaterial.twoSidedLighting = true;
  19428. hdrSkybox.infiniteDistance = true;
  19429. hdrSkybox.material = hdrSkyboxMaterial;
  19430. }
  19431. else {
  19432. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  19433. skyboxMaterial.backFaceCulling = false;
  19434. skyboxMaterial.reflectionTexture = this.environmentTexture.clone();
  19435. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  19436. skyboxMaterial.disableLighting = true;
  19437. hdrSkybox.infiniteDistance = true;
  19438. hdrSkybox.material = skyboxMaterial;
  19439. }
  19440. return hdrSkybox;
  19441. };
  19442. Scene.prototype.createDefaultVRExperience = function () {
  19443. this.VRHelper = new BABYLON.VRExperienceHelper(this, null);
  19444. };
  19445. // Tags
  19446. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  19447. if (tagsQuery === undefined) {
  19448. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  19449. return list;
  19450. }
  19451. var listByTags = [];
  19452. forEach = forEach || (function (item) { return; });
  19453. for (var i in list) {
  19454. var item = list[i];
  19455. if (BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  19456. listByTags.push(item);
  19457. forEach(item);
  19458. }
  19459. }
  19460. return listByTags;
  19461. };
  19462. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  19463. return this._getByTags(this.meshes, tagsQuery, forEach);
  19464. };
  19465. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  19466. return this._getByTags(this.cameras, tagsQuery, forEach);
  19467. };
  19468. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  19469. return this._getByTags(this.lights, tagsQuery, forEach);
  19470. };
  19471. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  19472. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  19473. };
  19474. /**
  19475. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  19476. * This allowed control for front to back rendering or reversly depending of the special needs.
  19477. *
  19478. * @param renderingGroupId The rendering group id corresponding to its index
  19479. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  19480. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  19481. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  19482. */
  19483. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  19484. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  19485. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  19486. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  19487. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  19488. };
  19489. /**
  19490. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  19491. *
  19492. * @param renderingGroupId The rendering group id corresponding to its index
  19493. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  19494. * @param depth Automatically clears depth between groups if true and autoClear is true.
  19495. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  19496. */
  19497. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  19498. if (depth === void 0) { depth = true; }
  19499. if (stencil === void 0) { stencil = true; }
  19500. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  19501. };
  19502. /**
  19503. * Will flag all materials as dirty to trigger new shader compilation
  19504. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  19505. */
  19506. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  19507. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  19508. var material = _a[_i];
  19509. if (predicate && !predicate(material)) {
  19510. continue;
  19511. }
  19512. material.markAsDirty(flag);
  19513. }
  19514. };
  19515. // Statics
  19516. Scene._FOGMODE_NONE = 0;
  19517. Scene._FOGMODE_EXP = 1;
  19518. Scene._FOGMODE_EXP2 = 2;
  19519. Scene._FOGMODE_LINEAR = 3;
  19520. Scene.MinDeltaTime = 1.0;
  19521. Scene.MaxDeltaTime = 1000.0;
  19522. /** The distance in pixel that you have to move to prevent some events */
  19523. Scene.DragMovementThreshold = 10; // in pixels
  19524. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  19525. Scene.LongPressDelay = 500; // in milliseconds
  19526. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  19527. Scene.DoubleClickDelay = 300; // in milliseconds
  19528. /** If you need to check double click without raising a single click at first click, enable this flag */
  19529. Scene.ExclusiveDoubleClickMode = false;
  19530. return Scene;
  19531. }());
  19532. BABYLON.Scene = Scene;
  19533. })(BABYLON || (BABYLON = {}));
  19534. //# sourceMappingURL=babylon.scene.js.map
  19535. var BABYLON;
  19536. (function (BABYLON) {
  19537. var Buffer = (function () {
  19538. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced) {
  19539. if (engine instanceof BABYLON.Mesh) {
  19540. this._engine = engine.getScene().getEngine();
  19541. }
  19542. else {
  19543. this._engine = engine;
  19544. }
  19545. this._updatable = updatable;
  19546. this._data = data;
  19547. this._strideSize = stride;
  19548. if (!postponeInternalCreation) {
  19549. this.create();
  19550. }
  19551. this._instanced = instanced;
  19552. this._instanceDivisor = instanced ? 1 : 0;
  19553. }
  19554. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride) {
  19555. // a lot of these parameters are ignored as they are overriden by the buffer
  19556. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, stride ? stride : this._strideSize, this._instanced, offset, size);
  19557. };
  19558. // Properties
  19559. Buffer.prototype.isUpdatable = function () {
  19560. return this._updatable;
  19561. };
  19562. Buffer.prototype.getData = function () {
  19563. return this._data;
  19564. };
  19565. Buffer.prototype.getBuffer = function () {
  19566. return this._buffer;
  19567. };
  19568. Buffer.prototype.getStrideSize = function () {
  19569. return this._strideSize;
  19570. };
  19571. Buffer.prototype.getIsInstanced = function () {
  19572. return this._instanced;
  19573. };
  19574. Object.defineProperty(Buffer.prototype, "instanceDivisor", {
  19575. get: function () {
  19576. return this._instanceDivisor;
  19577. },
  19578. set: function (value) {
  19579. this._instanceDivisor = value;
  19580. if (value == 0) {
  19581. this._instanced = false;
  19582. }
  19583. else {
  19584. this._instanced = true;
  19585. }
  19586. },
  19587. enumerable: true,
  19588. configurable: true
  19589. });
  19590. // Methods
  19591. Buffer.prototype.create = function (data) {
  19592. if (!data && this._buffer) {
  19593. return; // nothing to do
  19594. }
  19595. data = data || this._data;
  19596. if (!this._buffer) {
  19597. if (this._updatable) {
  19598. this._buffer = this._engine.createDynamicVertexBuffer(data);
  19599. this._data = data;
  19600. }
  19601. else {
  19602. this._buffer = this._engine.createVertexBuffer(data);
  19603. }
  19604. }
  19605. else if (this._updatable) {
  19606. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  19607. this._data = data;
  19608. }
  19609. };
  19610. Buffer.prototype._rebuild = function () {
  19611. this._buffer = null;
  19612. this.create(this._data);
  19613. };
  19614. Buffer.prototype.update = function (data) {
  19615. this.create(data);
  19616. };
  19617. Buffer.prototype.updateDirectly = function (data, offset, vertexCount) {
  19618. if (!this._buffer) {
  19619. return;
  19620. }
  19621. if (this._updatable) {
  19622. this._engine.updateDynamicVertexBuffer(this._buffer, data, offset, (vertexCount ? vertexCount * this.getStrideSize() : undefined));
  19623. this._data = null;
  19624. }
  19625. };
  19626. Buffer.prototype.dispose = function () {
  19627. if (!this._buffer) {
  19628. return;
  19629. }
  19630. if (this._engine._releaseBuffer(this._buffer)) {
  19631. this._buffer = null;
  19632. }
  19633. };
  19634. return Buffer;
  19635. }());
  19636. BABYLON.Buffer = Buffer;
  19637. })(BABYLON || (BABYLON = {}));
  19638. //# sourceMappingURL=babylon.buffer.js.map
  19639. var BABYLON;
  19640. (function (BABYLON) {
  19641. var VertexBuffer = (function () {
  19642. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size) {
  19643. if (!stride) {
  19644. // Deduce stride from kind
  19645. switch (kind) {
  19646. case VertexBuffer.PositionKind:
  19647. stride = 3;
  19648. break;
  19649. case VertexBuffer.NormalKind:
  19650. stride = 3;
  19651. break;
  19652. case VertexBuffer.UVKind:
  19653. case VertexBuffer.UV2Kind:
  19654. case VertexBuffer.UV3Kind:
  19655. case VertexBuffer.UV4Kind:
  19656. case VertexBuffer.UV5Kind:
  19657. case VertexBuffer.UV6Kind:
  19658. stride = 2;
  19659. break;
  19660. case VertexBuffer.TangentKind:
  19661. case VertexBuffer.ColorKind:
  19662. stride = 4;
  19663. break;
  19664. case VertexBuffer.MatricesIndicesKind:
  19665. case VertexBuffer.MatricesIndicesExtraKind:
  19666. stride = 4;
  19667. break;
  19668. case VertexBuffer.MatricesWeightsKind:
  19669. case VertexBuffer.MatricesWeightsExtraKind:
  19670. stride = 4;
  19671. break;
  19672. }
  19673. }
  19674. if (data instanceof BABYLON.Buffer) {
  19675. if (!stride) {
  19676. stride = data.getStrideSize();
  19677. }
  19678. this._buffer = data;
  19679. this._ownsBuffer = false;
  19680. }
  19681. else {
  19682. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced);
  19683. this._ownsBuffer = true;
  19684. }
  19685. this._stride = stride;
  19686. this._offset = offset ? offset : 0;
  19687. this._size = size ? size : stride;
  19688. this._kind = kind;
  19689. }
  19690. VertexBuffer.prototype._rebuild = function () {
  19691. if (!this._buffer) {
  19692. return;
  19693. }
  19694. this._buffer._rebuild();
  19695. };
  19696. /**
  19697. * Returns the kind of the VertexBuffer (string).
  19698. */
  19699. VertexBuffer.prototype.getKind = function () {
  19700. return this._kind;
  19701. };
  19702. // Properties
  19703. /**
  19704. * Boolean : is the VertexBuffer updatable ?
  19705. */
  19706. VertexBuffer.prototype.isUpdatable = function () {
  19707. return this._buffer.isUpdatable();
  19708. };
  19709. /**
  19710. * Returns an array of numbers or a Float32Array containing the VertexBuffer data.
  19711. */
  19712. VertexBuffer.prototype.getData = function () {
  19713. return this._buffer.getData();
  19714. };
  19715. /**
  19716. * Returns the WebGLBuffer associated to the VertexBuffer.
  19717. */
  19718. VertexBuffer.prototype.getBuffer = function () {
  19719. return this._buffer.getBuffer();
  19720. };
  19721. /**
  19722. * Returns the stride of the VertexBuffer (integer).
  19723. */
  19724. VertexBuffer.prototype.getStrideSize = function () {
  19725. return this._stride;
  19726. };
  19727. /**
  19728. * Returns the offset (integer).
  19729. */
  19730. VertexBuffer.prototype.getOffset = function () {
  19731. return this._offset;
  19732. };
  19733. /**
  19734. * Returns the VertexBuffer total size (integer).
  19735. */
  19736. VertexBuffer.prototype.getSize = function () {
  19737. return this._size;
  19738. };
  19739. /**
  19740. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  19741. */
  19742. VertexBuffer.prototype.getIsInstanced = function () {
  19743. return this._buffer.getIsInstanced();
  19744. };
  19745. /**
  19746. * Returns the instancing divisor, zero for non-instanced (integer).
  19747. */
  19748. VertexBuffer.prototype.getInstanceDivisor = function () {
  19749. return this._buffer.instanceDivisor;
  19750. };
  19751. // Methods
  19752. /**
  19753. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  19754. * Returns the created WebGLBuffer.
  19755. */
  19756. VertexBuffer.prototype.create = function (data) {
  19757. return this._buffer.create(data);
  19758. };
  19759. /**
  19760. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19761. * Returns the updated WebGLBuffer.
  19762. */
  19763. VertexBuffer.prototype.update = function (data) {
  19764. return this._buffer.update(data);
  19765. };
  19766. /**
  19767. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  19768. * Returns the directly updated WebGLBuffer.
  19769. */
  19770. VertexBuffer.prototype.updateDirectly = function (data, offset) {
  19771. return this._buffer.updateDirectly(data, offset);
  19772. };
  19773. /**
  19774. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  19775. */
  19776. VertexBuffer.prototype.dispose = function () {
  19777. if (this._ownsBuffer) {
  19778. this._buffer.dispose();
  19779. }
  19780. };
  19781. Object.defineProperty(VertexBuffer, "PositionKind", {
  19782. get: function () {
  19783. return VertexBuffer._PositionKind;
  19784. },
  19785. enumerable: true,
  19786. configurable: true
  19787. });
  19788. Object.defineProperty(VertexBuffer, "NormalKind", {
  19789. get: function () {
  19790. return VertexBuffer._NormalKind;
  19791. },
  19792. enumerable: true,
  19793. configurable: true
  19794. });
  19795. Object.defineProperty(VertexBuffer, "TangentKind", {
  19796. get: function () {
  19797. return VertexBuffer._TangentKind;
  19798. },
  19799. enumerable: true,
  19800. configurable: true
  19801. });
  19802. Object.defineProperty(VertexBuffer, "UVKind", {
  19803. get: function () {
  19804. return VertexBuffer._UVKind;
  19805. },
  19806. enumerable: true,
  19807. configurable: true
  19808. });
  19809. Object.defineProperty(VertexBuffer, "UV2Kind", {
  19810. get: function () {
  19811. return VertexBuffer._UV2Kind;
  19812. },
  19813. enumerable: true,
  19814. configurable: true
  19815. });
  19816. Object.defineProperty(VertexBuffer, "UV3Kind", {
  19817. get: function () {
  19818. return VertexBuffer._UV3Kind;
  19819. },
  19820. enumerable: true,
  19821. configurable: true
  19822. });
  19823. Object.defineProperty(VertexBuffer, "UV4Kind", {
  19824. get: function () {
  19825. return VertexBuffer._UV4Kind;
  19826. },
  19827. enumerable: true,
  19828. configurable: true
  19829. });
  19830. Object.defineProperty(VertexBuffer, "UV5Kind", {
  19831. get: function () {
  19832. return VertexBuffer._UV5Kind;
  19833. },
  19834. enumerable: true,
  19835. configurable: true
  19836. });
  19837. Object.defineProperty(VertexBuffer, "UV6Kind", {
  19838. get: function () {
  19839. return VertexBuffer._UV6Kind;
  19840. },
  19841. enumerable: true,
  19842. configurable: true
  19843. });
  19844. Object.defineProperty(VertexBuffer, "ColorKind", {
  19845. get: function () {
  19846. return VertexBuffer._ColorKind;
  19847. },
  19848. enumerable: true,
  19849. configurable: true
  19850. });
  19851. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  19852. get: function () {
  19853. return VertexBuffer._MatricesIndicesKind;
  19854. },
  19855. enumerable: true,
  19856. configurable: true
  19857. });
  19858. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  19859. get: function () {
  19860. return VertexBuffer._MatricesWeightsKind;
  19861. },
  19862. enumerable: true,
  19863. configurable: true
  19864. });
  19865. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  19866. get: function () {
  19867. return VertexBuffer._MatricesIndicesExtraKind;
  19868. },
  19869. enumerable: true,
  19870. configurable: true
  19871. });
  19872. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  19873. get: function () {
  19874. return VertexBuffer._MatricesWeightsExtraKind;
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. // Enums
  19880. VertexBuffer._PositionKind = "position";
  19881. VertexBuffer._NormalKind = "normal";
  19882. VertexBuffer._TangentKind = "tangent";
  19883. VertexBuffer._UVKind = "uv";
  19884. VertexBuffer._UV2Kind = "uv2";
  19885. VertexBuffer._UV3Kind = "uv3";
  19886. VertexBuffer._UV4Kind = "uv4";
  19887. VertexBuffer._UV5Kind = "uv5";
  19888. VertexBuffer._UV6Kind = "uv6";
  19889. VertexBuffer._ColorKind = "color";
  19890. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  19891. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  19892. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  19893. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  19894. return VertexBuffer;
  19895. }());
  19896. BABYLON.VertexBuffer = VertexBuffer;
  19897. })(BABYLON || (BABYLON = {}));
  19898. //# sourceMappingURL=babylon.vertexBuffer.js.map
  19899. var BABYLON;
  19900. (function (BABYLON) {
  19901. var InternalTexture = (function () {
  19902. function InternalTexture(engine, dataSource) {
  19903. this.onLoadedObservable = new BABYLON.Observable();
  19904. // Private
  19905. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  19906. this._references = 1;
  19907. this._engine = engine;
  19908. this._dataSource = dataSource;
  19909. this._webGLTexture = engine._createTexture();
  19910. }
  19911. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  19912. get: function () {
  19913. return this._dataSource;
  19914. },
  19915. enumerable: true,
  19916. configurable: true
  19917. });
  19918. InternalTexture.prototype.incrementReferences = function () {
  19919. this._references++;
  19920. };
  19921. InternalTexture.prototype.updateSize = function (width, height) {
  19922. this.width = width;
  19923. this.height = height;
  19924. this._size = width * height;
  19925. this.baseWidth = width;
  19926. this.baseHeight = height;
  19927. };
  19928. InternalTexture.prototype._rebuild = function () {
  19929. var _this = this;
  19930. var proxy;
  19931. this.isReady = false;
  19932. this._cachedCoordinatesMode = null;
  19933. this._cachedWrapU = null;
  19934. this._cachedWrapV = null;
  19935. this._cachedAnisotropicFilteringLevel = null;
  19936. switch (this._dataSource) {
  19937. case InternalTexture.DATASOURCE_TEMP:
  19938. return;
  19939. case InternalTexture.DATASOURCE_URL:
  19940. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  19941. _this.isReady = true;
  19942. }, null, this._buffer, null, this.format);
  19943. proxy._swapAndDie(this);
  19944. return;
  19945. case InternalTexture.DATASOURCE_RAW:
  19946. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  19947. proxy._swapAndDie(this);
  19948. this.isReady = true;
  19949. return;
  19950. case InternalTexture.DATASOURCE_DYNAMIC:
  19951. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  19952. proxy._swapAndDie(this);
  19953. // The engine will make sure to update content so no need to flag it as isReady = true
  19954. return;
  19955. case InternalTexture.DATASOURCE_RENDERTARGET:
  19956. var options = new BABYLON.RenderTargetCreationOptions();
  19957. options.generateDepthBuffer = this._generateDepthBuffer;
  19958. options.generateMipMaps = this.generateMipMaps;
  19959. options.generateStencilBuffer = this._generateStencilBuffer;
  19960. options.samplingMode = this.samplingMode;
  19961. options.type = this.type;
  19962. if (this.isCube) {
  19963. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  19964. }
  19965. else {
  19966. var size = {
  19967. width: this.width,
  19968. height: this.height
  19969. };
  19970. proxy = this._engine.createRenderTargetTexture(size, options);
  19971. }
  19972. proxy._swapAndDie(this);
  19973. this.isReady = true;
  19974. return;
  19975. case InternalTexture.DATASOURCE_CUBE:
  19976. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  19977. _this.isReady = true;
  19978. }, null, this.format, this._extension);
  19979. proxy._swapAndDie(this);
  19980. return;
  19981. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  19982. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  19983. proxy._swapAndDie(_this);
  19984. _this.isReady = true;
  19985. }, null, this.format, this._extension);
  19986. return;
  19987. }
  19988. };
  19989. InternalTexture.prototype._swapAndDie = function (target) {
  19990. target._webGLTexture = this._webGLTexture;
  19991. if (this._framebuffer) {
  19992. target._framebuffer = this._framebuffer;
  19993. }
  19994. if (this._depthStencilBuffer) {
  19995. target._depthStencilBuffer = this._depthStencilBuffer;
  19996. }
  19997. if (this._lodTextureHigh) {
  19998. if (target._lodTextureHigh) {
  19999. target._lodTextureHigh.dispose();
  20000. }
  20001. target._lodTextureHigh = this._lodTextureHigh;
  20002. }
  20003. if (this._lodTextureMid) {
  20004. if (target._lodTextureMid) {
  20005. target._lodTextureMid.dispose();
  20006. }
  20007. target._lodTextureMid = this._lodTextureMid;
  20008. }
  20009. if (this._lodTextureLow) {
  20010. if (target._lodTextureLow) {
  20011. target._lodTextureLow.dispose();
  20012. }
  20013. target._lodTextureLow = this._lodTextureLow;
  20014. }
  20015. var cache = this._engine.getLoadedTexturesCache();
  20016. var index = cache.indexOf(this);
  20017. if (index !== -1) {
  20018. cache.splice(index, 1);
  20019. }
  20020. };
  20021. InternalTexture.prototype.dispose = function () {
  20022. if (!this._webGLTexture) {
  20023. return;
  20024. }
  20025. this._references--;
  20026. if (this._references === 0) {
  20027. this._engine._releaseTexture(this);
  20028. this._webGLTexture = null;
  20029. }
  20030. };
  20031. InternalTexture.DATASOURCE_UNKNOWN = 0;
  20032. InternalTexture.DATASOURCE_URL = 1;
  20033. InternalTexture.DATASOURCE_TEMP = 2;
  20034. InternalTexture.DATASOURCE_RAW = 3;
  20035. InternalTexture.DATASOURCE_DYNAMIC = 4;
  20036. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  20037. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  20038. InternalTexture.DATASOURCE_CUBE = 7;
  20039. InternalTexture.DATASOURCE_CUBERAW = 8;
  20040. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  20041. return InternalTexture;
  20042. }());
  20043. BABYLON.InternalTexture = InternalTexture;
  20044. })(BABYLON || (BABYLON = {}));
  20045. //# sourceMappingURL=babylon.internalTexture.js.map
  20046. var BABYLON;
  20047. (function (BABYLON) {
  20048. var BaseTexture = (function () {
  20049. function BaseTexture(scene) {
  20050. this._hasAlpha = false;
  20051. this.getAlphaFromRGB = false;
  20052. this.level = 1;
  20053. this.coordinatesIndex = 0;
  20054. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  20055. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  20056. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  20057. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  20058. this.isCube = false;
  20059. this.gammaSpace = true;
  20060. this.invertZ = false;
  20061. this.lodLevelInAlpha = false;
  20062. this.lodGenerationOffset = 0.0;
  20063. this.lodGenerationScale = 0.8;
  20064. this.isRenderTarget = false;
  20065. this.animations = new Array();
  20066. /**
  20067. * An event triggered when the texture is disposed.
  20068. * @type {BABYLON.Observable}
  20069. */
  20070. this.onDisposeObservable = new BABYLON.Observable();
  20071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20072. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  20073. this._scene.textures.push(this);
  20074. this._uid = null;
  20075. }
  20076. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  20077. get: function () {
  20078. return this._hasAlpha;
  20079. },
  20080. set: function (value) {
  20081. if (this._hasAlpha === value) {
  20082. return;
  20083. }
  20084. this._hasAlpha = value;
  20085. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20086. },
  20087. enumerable: true,
  20088. configurable: true
  20089. });
  20090. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  20091. get: function () {
  20092. return this._coordinatesMode;
  20093. },
  20094. set: function (value) {
  20095. if (this._coordinatesMode === value) {
  20096. return;
  20097. }
  20098. this._coordinatesMode = value;
  20099. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  20100. },
  20101. enumerable: true,
  20102. configurable: true
  20103. });
  20104. Object.defineProperty(BaseTexture.prototype, "uid", {
  20105. get: function () {
  20106. if (!this._uid) {
  20107. this._uid = BABYLON.Tools.RandomId();
  20108. }
  20109. return this._uid;
  20110. },
  20111. enumerable: true,
  20112. configurable: true
  20113. });
  20114. BaseTexture.prototype.toString = function () {
  20115. return this.name;
  20116. };
  20117. BaseTexture.prototype.getClassName = function () {
  20118. return "BaseTexture";
  20119. };
  20120. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  20121. set: function (callback) {
  20122. if (this._onDisposeObserver) {
  20123. this.onDisposeObservable.remove(this._onDisposeObserver);
  20124. }
  20125. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  20126. },
  20127. enumerable: true,
  20128. configurable: true
  20129. });
  20130. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  20131. get: function () {
  20132. return true;
  20133. },
  20134. enumerable: true,
  20135. configurable: true
  20136. });
  20137. BaseTexture.prototype.getScene = function () {
  20138. return this._scene;
  20139. };
  20140. BaseTexture.prototype.getTextureMatrix = function () {
  20141. return null;
  20142. };
  20143. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  20144. return null;
  20145. };
  20146. BaseTexture.prototype.getInternalTexture = function () {
  20147. return this._texture;
  20148. };
  20149. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  20150. return !this.isBlocking || this.isReady();
  20151. };
  20152. BaseTexture.prototype.isReady = function () {
  20153. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20154. this.delayLoad();
  20155. return false;
  20156. }
  20157. if (this._texture) {
  20158. return this._texture.isReady;
  20159. }
  20160. return false;
  20161. };
  20162. BaseTexture.prototype.getSize = function () {
  20163. if (this._texture.width) {
  20164. return new BABYLON.Size(this._texture.width, this._texture.height);
  20165. }
  20166. if (this._texture._size) {
  20167. return new BABYLON.Size(this._texture._size, this._texture._size);
  20168. }
  20169. return BABYLON.Size.Zero();
  20170. };
  20171. BaseTexture.prototype.getBaseSize = function () {
  20172. if (!this.isReady() || !this._texture)
  20173. return BABYLON.Size.Zero();
  20174. if (this._texture._size) {
  20175. return new BABYLON.Size(this._texture._size, this._texture._size);
  20176. }
  20177. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  20178. };
  20179. BaseTexture.prototype.scale = function (ratio) {
  20180. };
  20181. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  20182. get: function () {
  20183. return false;
  20184. },
  20185. enumerable: true,
  20186. configurable: true
  20187. });
  20188. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  20189. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  20190. for (var index = 0; index < texturesCache.length; index++) {
  20191. var texturesCacheEntry = texturesCache[index];
  20192. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  20193. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  20194. texturesCacheEntry.incrementReferences();
  20195. return texturesCacheEntry;
  20196. }
  20197. }
  20198. }
  20199. return null;
  20200. };
  20201. BaseTexture.prototype._rebuild = function () {
  20202. };
  20203. BaseTexture.prototype.delayLoad = function () {
  20204. };
  20205. BaseTexture.prototype.clone = function () {
  20206. return null;
  20207. };
  20208. Object.defineProperty(BaseTexture.prototype, "textureType", {
  20209. get: function () {
  20210. if (!this._texture) {
  20211. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20212. }
  20213. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  20214. },
  20215. enumerable: true,
  20216. configurable: true
  20217. });
  20218. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  20219. get: function () {
  20220. if (!this._texture) {
  20221. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20222. }
  20223. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  20224. },
  20225. enumerable: true,
  20226. configurable: true
  20227. });
  20228. BaseTexture.prototype.readPixels = function (faceIndex) {
  20229. if (faceIndex === void 0) { faceIndex = 0; }
  20230. if (!this._texture) {
  20231. return null;
  20232. }
  20233. var size = this.getSize();
  20234. var engine = this.getScene().getEngine();
  20235. if (this._texture.isCube) {
  20236. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  20237. }
  20238. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  20239. };
  20240. BaseTexture.prototype.releaseInternalTexture = function () {
  20241. if (this._texture) {
  20242. this._texture.dispose();
  20243. this._texture = null;
  20244. }
  20245. };
  20246. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  20247. get: function () {
  20248. if (!this._texture || !BABYLON.Internals.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  20249. return null;
  20250. }
  20251. if (!this._texture._sphericalPolynomial) {
  20252. this._texture._sphericalPolynomial =
  20253. BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  20254. }
  20255. return this._texture._sphericalPolynomial;
  20256. },
  20257. set: function (value) {
  20258. if (this._texture) {
  20259. this._texture._sphericalPolynomial = value;
  20260. }
  20261. },
  20262. enumerable: true,
  20263. configurable: true
  20264. });
  20265. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  20266. get: function () {
  20267. if (this._texture) {
  20268. return this._texture._lodTextureHigh;
  20269. }
  20270. return null;
  20271. },
  20272. enumerable: true,
  20273. configurable: true
  20274. });
  20275. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  20276. get: function () {
  20277. if (this._texture) {
  20278. return this._texture._lodTextureMid;
  20279. }
  20280. return null;
  20281. },
  20282. enumerable: true,
  20283. configurable: true
  20284. });
  20285. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  20286. get: function () {
  20287. if (this._texture) {
  20288. return this._texture._lodTextureLow;
  20289. }
  20290. return null;
  20291. },
  20292. enumerable: true,
  20293. configurable: true
  20294. });
  20295. BaseTexture.prototype.dispose = function () {
  20296. // Animations
  20297. this.getScene().stopAnimation(this);
  20298. // Remove from scene
  20299. this._scene._removePendingData(this);
  20300. var index = this._scene.textures.indexOf(this);
  20301. if (index >= 0) {
  20302. this._scene.textures.splice(index, 1);
  20303. }
  20304. if (this._texture === undefined) {
  20305. return;
  20306. }
  20307. // Release
  20308. this.releaseInternalTexture();
  20309. // Callback
  20310. this.onDisposeObservable.notifyObservers(this);
  20311. this.onDisposeObservable.clear();
  20312. };
  20313. BaseTexture.prototype.serialize = function () {
  20314. if (!this.name) {
  20315. return null;
  20316. }
  20317. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  20318. // Animations
  20319. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  20320. return serializationObject;
  20321. };
  20322. BaseTexture.WhenAllReady = function (textures, callback) {
  20323. var numRemaining = textures.length;
  20324. if (numRemaining === 0) {
  20325. callback();
  20326. return;
  20327. }
  20328. var _loop_1 = function () {
  20329. texture = textures[i];
  20330. if (texture.isReady()) {
  20331. if (--numRemaining === 0) {
  20332. callback();
  20333. }
  20334. }
  20335. else {
  20336. onLoadObservable = texture.onLoadObservable;
  20337. var onLoadCallback_1 = function () {
  20338. onLoadObservable.removeCallback(onLoadCallback_1);
  20339. if (--numRemaining === 0) {
  20340. callback();
  20341. }
  20342. };
  20343. onLoadObservable.add(onLoadCallback_1);
  20344. }
  20345. };
  20346. var texture, onLoadObservable;
  20347. for (var i = 0; i < textures.length; i++) {
  20348. _loop_1();
  20349. }
  20350. };
  20351. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  20352. __decorate([
  20353. BABYLON.serialize()
  20354. ], BaseTexture.prototype, "name", void 0);
  20355. __decorate([
  20356. BABYLON.serialize("hasAlpha")
  20357. ], BaseTexture.prototype, "_hasAlpha", void 0);
  20358. __decorate([
  20359. BABYLON.serialize()
  20360. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  20361. __decorate([
  20362. BABYLON.serialize()
  20363. ], BaseTexture.prototype, "level", void 0);
  20364. __decorate([
  20365. BABYLON.serialize()
  20366. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  20367. __decorate([
  20368. BABYLON.serialize("coordinatesMode")
  20369. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  20370. __decorate([
  20371. BABYLON.serialize()
  20372. ], BaseTexture.prototype, "wrapU", void 0);
  20373. __decorate([
  20374. BABYLON.serialize()
  20375. ], BaseTexture.prototype, "wrapV", void 0);
  20376. __decorate([
  20377. BABYLON.serialize()
  20378. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  20379. __decorate([
  20380. BABYLON.serialize()
  20381. ], BaseTexture.prototype, "isCube", void 0);
  20382. __decorate([
  20383. BABYLON.serialize()
  20384. ], BaseTexture.prototype, "gammaSpace", void 0);
  20385. __decorate([
  20386. BABYLON.serialize()
  20387. ], BaseTexture.prototype, "invertZ", void 0);
  20388. __decorate([
  20389. BABYLON.serialize()
  20390. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  20391. __decorate([
  20392. BABYLON.serialize()
  20393. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  20394. __decorate([
  20395. BABYLON.serialize()
  20396. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  20397. __decorate([
  20398. BABYLON.serialize()
  20399. ], BaseTexture.prototype, "isRenderTarget", void 0);
  20400. return BaseTexture;
  20401. }());
  20402. BABYLON.BaseTexture = BaseTexture;
  20403. })(BABYLON || (BABYLON = {}));
  20404. //# sourceMappingURL=babylon.baseTexture.js.map
  20405. var BABYLON;
  20406. (function (BABYLON) {
  20407. var Texture = (function (_super) {
  20408. __extends(Texture, _super);
  20409. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  20410. if (noMipmap === void 0) { noMipmap = false; }
  20411. if (invertY === void 0) { invertY = true; }
  20412. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20413. if (onLoad === void 0) { onLoad = null; }
  20414. if (onError === void 0) { onError = null; }
  20415. if (buffer === void 0) { buffer = null; }
  20416. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20417. var _this = _super.call(this, scene) || this;
  20418. _this.uOffset = 0;
  20419. _this.vOffset = 0;
  20420. _this.uScale = 1.0;
  20421. _this.vScale = 1.0;
  20422. _this.uAng = 0;
  20423. _this.vAng = 0;
  20424. _this.wAng = 0;
  20425. _this._isBlocking = true;
  20426. _this.name = url;
  20427. _this.url = url;
  20428. _this._noMipmap = noMipmap;
  20429. _this._invertY = invertY;
  20430. _this._samplingMode = samplingMode;
  20431. _this._buffer = buffer;
  20432. _this._deleteBuffer = deleteBuffer;
  20433. _this._format = format;
  20434. scene = _this.getScene();
  20435. var load = function () {
  20436. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  20437. _this.onLoadObservable.notifyObservers(_this);
  20438. }
  20439. if (onLoad) {
  20440. onLoad();
  20441. }
  20442. if (!_this.isBlocking) {
  20443. scene.resetCachedMaterial();
  20444. }
  20445. };
  20446. if (!url) {
  20447. _this._delayedOnLoad = load;
  20448. _this._delayedOnError = onError;
  20449. return _this;
  20450. }
  20451. _this._texture = _this._getFromCache(url, noMipmap, samplingMode);
  20452. if (!_this._texture) {
  20453. if (!scene.useDelayedTextureLoading) {
  20454. _this._texture = scene.getEngine().createTexture(url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, null, _this._format);
  20455. if (deleteBuffer) {
  20456. delete _this._buffer;
  20457. }
  20458. }
  20459. else {
  20460. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20461. _this._delayedOnLoad = load;
  20462. _this._delayedOnError = onError;
  20463. }
  20464. }
  20465. else {
  20466. if (_this._texture.isReady) {
  20467. BABYLON.Tools.SetImmediate(function () { return load(); });
  20468. }
  20469. else {
  20470. _this._texture.onLoadedObservable.add(load);
  20471. }
  20472. }
  20473. return _this;
  20474. }
  20475. Object.defineProperty(Texture.prototype, "noMipmap", {
  20476. get: function () {
  20477. return this._noMipmap;
  20478. },
  20479. enumerable: true,
  20480. configurable: true
  20481. });
  20482. Object.defineProperty(Texture.prototype, "isBlocking", {
  20483. get: function () {
  20484. return this._isBlocking;
  20485. },
  20486. set: function (value) {
  20487. this._isBlocking = value;
  20488. },
  20489. enumerable: true,
  20490. configurable: true
  20491. });
  20492. Object.defineProperty(Texture.prototype, "samplingMode", {
  20493. get: function () {
  20494. return this._samplingMode;
  20495. },
  20496. enumerable: true,
  20497. configurable: true
  20498. });
  20499. Texture.prototype.updateURL = function (url) {
  20500. this.url = url;
  20501. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  20502. this.delayLoad();
  20503. };
  20504. Texture.prototype.delayLoad = function () {
  20505. var _this = this;
  20506. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  20507. return;
  20508. }
  20509. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  20510. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  20511. if (!this._texture) {
  20512. this._texture = this.getScene().getEngine().createTexture(this.url, this._noMipmap, this._invertY, this.getScene(), this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  20513. if (this._deleteBuffer) {
  20514. delete this._buffer;
  20515. }
  20516. }
  20517. else {
  20518. if (this._texture.isReady) {
  20519. BABYLON.Tools.SetImmediate(function () { return _this._delayedOnLoad(); });
  20520. }
  20521. else {
  20522. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  20523. }
  20524. }
  20525. };
  20526. Texture.prototype.updateSamplingMode = function (samplingMode) {
  20527. if (!this._texture) {
  20528. return;
  20529. }
  20530. this._samplingMode = samplingMode;
  20531. this.getScene().getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  20532. };
  20533. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  20534. x *= this.uScale;
  20535. y *= this.vScale;
  20536. x -= 0.5 * this.uScale;
  20537. y -= 0.5 * this.vScale;
  20538. z -= 0.5;
  20539. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  20540. t.x += 0.5 * this.uScale + this.uOffset;
  20541. t.y += 0.5 * this.vScale + this.vOffset;
  20542. t.z += 0.5;
  20543. };
  20544. Texture.prototype.getTextureMatrix = function () {
  20545. var _this = this;
  20546. if (this.uOffset === this._cachedUOffset &&
  20547. this.vOffset === this._cachedVOffset &&
  20548. this.uScale === this._cachedUScale &&
  20549. this.vScale === this._cachedVScale &&
  20550. this.uAng === this._cachedUAng &&
  20551. this.vAng === this._cachedVAng &&
  20552. this.wAng === this._cachedWAng) {
  20553. return this._cachedTextureMatrix;
  20554. }
  20555. this._cachedUOffset = this.uOffset;
  20556. this._cachedVOffset = this.vOffset;
  20557. this._cachedUScale = this.uScale;
  20558. this._cachedVScale = this.vScale;
  20559. this._cachedUAng = this.uAng;
  20560. this._cachedVAng = this.vAng;
  20561. this._cachedWAng = this.wAng;
  20562. if (!this._cachedTextureMatrix) {
  20563. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20564. this._rowGenerationMatrix = new BABYLON.Matrix();
  20565. this._t0 = BABYLON.Vector3.Zero();
  20566. this._t1 = BABYLON.Vector3.Zero();
  20567. this._t2 = BABYLON.Vector3.Zero();
  20568. }
  20569. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  20570. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  20571. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  20572. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  20573. this._t1.subtractInPlace(this._t0);
  20574. this._t2.subtractInPlace(this._t0);
  20575. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20576. this._cachedTextureMatrix.m[0] = this._t1.x;
  20577. this._cachedTextureMatrix.m[1] = this._t1.y;
  20578. this._cachedTextureMatrix.m[2] = this._t1.z;
  20579. this._cachedTextureMatrix.m[4] = this._t2.x;
  20580. this._cachedTextureMatrix.m[5] = this._t2.y;
  20581. this._cachedTextureMatrix.m[6] = this._t2.z;
  20582. this._cachedTextureMatrix.m[8] = this._t0.x;
  20583. this._cachedTextureMatrix.m[9] = this._t0.y;
  20584. this._cachedTextureMatrix.m[10] = this._t0.z;
  20585. this.getScene().markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20586. return mat.hasTexture(_this);
  20587. });
  20588. return this._cachedTextureMatrix;
  20589. };
  20590. Texture.prototype.getReflectionTextureMatrix = function () {
  20591. var _this = this;
  20592. var scene = this.getScene();
  20593. if (this.uOffset === this._cachedUOffset &&
  20594. this.vOffset === this._cachedVOffset &&
  20595. this.uScale === this._cachedUScale &&
  20596. this.vScale === this._cachedVScale &&
  20597. this.coordinatesMode === this._cachedCoordinatesMode) {
  20598. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  20599. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  20600. return this._cachedTextureMatrix;
  20601. }
  20602. }
  20603. else {
  20604. return this._cachedTextureMatrix;
  20605. }
  20606. }
  20607. if (!this._cachedTextureMatrix) {
  20608. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  20609. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  20610. }
  20611. this._cachedUOffset = this.uOffset;
  20612. this._cachedVOffset = this.vOffset;
  20613. this._cachedUScale = this.uScale;
  20614. this._cachedVScale = this.vScale;
  20615. this._cachedCoordinatesMode = this.coordinatesMode;
  20616. switch (this.coordinatesMode) {
  20617. case Texture.PLANAR_MODE:
  20618. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20619. this._cachedTextureMatrix[0] = this.uScale;
  20620. this._cachedTextureMatrix[5] = this.vScale;
  20621. this._cachedTextureMatrix[12] = this.uOffset;
  20622. this._cachedTextureMatrix[13] = this.vOffset;
  20623. break;
  20624. case Texture.PROJECTION_MODE:
  20625. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  20626. this._projectionModeMatrix.m[0] = 0.5;
  20627. this._projectionModeMatrix.m[5] = -0.5;
  20628. this._projectionModeMatrix.m[10] = 0.0;
  20629. this._projectionModeMatrix.m[12] = 0.5;
  20630. this._projectionModeMatrix.m[13] = 0.5;
  20631. this._projectionModeMatrix.m[14] = 1.0;
  20632. this._projectionModeMatrix.m[15] = 1.0;
  20633. var projectionMatrix = scene.getProjectionMatrix();
  20634. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  20635. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  20636. break;
  20637. default:
  20638. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  20639. break;
  20640. }
  20641. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  20642. return (mat.getActiveTextures().indexOf(_this) !== -1);
  20643. });
  20644. return this._cachedTextureMatrix;
  20645. };
  20646. Texture.prototype.clone = function () {
  20647. var _this = this;
  20648. return BABYLON.SerializationHelper.Clone(function () {
  20649. return new Texture(_this._texture.url, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  20650. }, this);
  20651. };
  20652. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  20653. get: function () {
  20654. if (!this._onLoadObservable) {
  20655. this._onLoadObservable = new BABYLON.Observable();
  20656. }
  20657. return this._onLoadObservable;
  20658. },
  20659. enumerable: true,
  20660. configurable: true
  20661. });
  20662. Texture.prototype.serialize = function () {
  20663. var serializationObject = _super.prototype.serialize.call(this);
  20664. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  20665. serializationObject.base64String = this._buffer;
  20666. serializationObject.name = serializationObject.name.replace("data:", "");
  20667. }
  20668. return serializationObject;
  20669. };
  20670. Texture.prototype.getClassName = function () {
  20671. return "Texture";
  20672. };
  20673. Texture.prototype.dispose = function () {
  20674. _super.prototype.dispose.call(this);
  20675. if (this.onLoadObservable) {
  20676. this.onLoadObservable.clear();
  20677. this._onLoadObservable = null;
  20678. }
  20679. this._delayedOnLoad = null;
  20680. this._delayedOnError = null;
  20681. };
  20682. // Statics
  20683. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20684. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20685. if (onLoad === void 0) { onLoad = null; }
  20686. if (onError === void 0) { onError = null; }
  20687. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20688. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  20689. };
  20690. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  20691. if (parsedTexture.customType) {
  20692. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  20693. // Update Sampling Mode
  20694. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  20695. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  20696. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  20697. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  20698. }
  20699. }
  20700. return parsedCustomTexture;
  20701. }
  20702. if (parsedTexture.isCube) {
  20703. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  20704. }
  20705. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  20706. return null;
  20707. }
  20708. var texture = BABYLON.SerializationHelper.Parse(function () {
  20709. if (parsedTexture.mirrorPlane) {
  20710. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20711. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  20712. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  20713. return mirrorTexture;
  20714. }
  20715. else if (parsedTexture.isRenderTarget) {
  20716. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene);
  20717. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  20718. return renderTargetTexture;
  20719. }
  20720. else {
  20721. var texture;
  20722. if (parsedTexture.base64String) {
  20723. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene);
  20724. }
  20725. else {
  20726. texture = new Texture(rootUrl + parsedTexture.name, scene);
  20727. }
  20728. return texture;
  20729. }
  20730. }, parsedTexture, scene);
  20731. // Update Sampling Mode
  20732. if (parsedTexture.samplingMode) {
  20733. var sampling = parsedTexture.samplingMode;
  20734. if (texture._samplingMode !== sampling) {
  20735. texture.updateSamplingMode(sampling);
  20736. }
  20737. }
  20738. // Animations
  20739. if (parsedTexture.animations) {
  20740. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  20741. var parsedAnimation = parsedTexture.animations[animationIndex];
  20742. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  20743. }
  20744. }
  20745. return texture;
  20746. };
  20747. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  20748. if (deleteBuffer === void 0) { deleteBuffer = false; }
  20749. if (noMipmap === void 0) { noMipmap = false; }
  20750. if (invertY === void 0) { invertY = true; }
  20751. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  20752. if (onLoad === void 0) { onLoad = null; }
  20753. if (onError === void 0) { onError = null; }
  20754. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  20755. if (name.substr(0, 5) !== "data:") {
  20756. name = "data:" + name;
  20757. }
  20758. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  20759. };
  20760. // Constants
  20761. Texture.NEAREST_SAMPLINGMODE = 1;
  20762. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  20763. Texture.BILINEAR_SAMPLINGMODE = 2;
  20764. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  20765. Texture.TRILINEAR_SAMPLINGMODE = 3;
  20766. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  20767. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  20768. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  20769. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  20770. Texture.NEAREST_LINEAR = 7;
  20771. Texture.NEAREST_NEAREST = 8;
  20772. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  20773. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  20774. Texture.LINEAR_LINEAR = 11;
  20775. Texture.LINEAR_NEAREST = 12;
  20776. Texture.EXPLICIT_MODE = 0;
  20777. Texture.SPHERICAL_MODE = 1;
  20778. Texture.PLANAR_MODE = 2;
  20779. Texture.CUBIC_MODE = 3;
  20780. Texture.PROJECTION_MODE = 4;
  20781. Texture.SKYBOX_MODE = 5;
  20782. Texture.INVCUBIC_MODE = 6;
  20783. Texture.EQUIRECTANGULAR_MODE = 7;
  20784. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  20785. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  20786. Texture.CLAMP_ADDRESSMODE = 0;
  20787. Texture.WRAP_ADDRESSMODE = 1;
  20788. Texture.MIRROR_ADDRESSMODE = 2;
  20789. __decorate([
  20790. BABYLON.serialize()
  20791. ], Texture.prototype, "url", void 0);
  20792. __decorate([
  20793. BABYLON.serialize()
  20794. ], Texture.prototype, "uOffset", void 0);
  20795. __decorate([
  20796. BABYLON.serialize()
  20797. ], Texture.prototype, "vOffset", void 0);
  20798. __decorate([
  20799. BABYLON.serialize()
  20800. ], Texture.prototype, "uScale", void 0);
  20801. __decorate([
  20802. BABYLON.serialize()
  20803. ], Texture.prototype, "vScale", void 0);
  20804. __decorate([
  20805. BABYLON.serialize()
  20806. ], Texture.prototype, "uAng", void 0);
  20807. __decorate([
  20808. BABYLON.serialize()
  20809. ], Texture.prototype, "vAng", void 0);
  20810. __decorate([
  20811. BABYLON.serialize()
  20812. ], Texture.prototype, "wAng", void 0);
  20813. __decorate([
  20814. BABYLON.serialize()
  20815. ], Texture.prototype, "isBlocking", null);
  20816. return Texture;
  20817. }(BABYLON.BaseTexture));
  20818. BABYLON.Texture = Texture;
  20819. })(BABYLON || (BABYLON = {}));
  20820. //# sourceMappingURL=babylon.texture.js.map
  20821. var BABYLON;
  20822. (function (BABYLON) {
  20823. var _InstancesBatch = (function () {
  20824. function _InstancesBatch() {
  20825. this.mustReturn = false;
  20826. this.visibleInstances = new Array();
  20827. this.renderSelf = new Array();
  20828. }
  20829. return _InstancesBatch;
  20830. }());
  20831. BABYLON._InstancesBatch = _InstancesBatch;
  20832. var Mesh = (function (_super) {
  20833. __extends(Mesh, _super);
  20834. /**
  20835. * @constructor
  20836. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  20837. * @param {Scene} scene The scene to add this mesh to.
  20838. * @param {Node} parent The parent of this mesh, if it has one
  20839. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  20840. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  20841. * When false, achieved by calling a clone(), also passing False.
  20842. * This will make creation of children, recursive.
  20843. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  20844. */
  20845. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  20846. if (parent === void 0) { parent = null; }
  20847. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  20848. var _this = _super.call(this, name, scene) || this;
  20849. // Events
  20850. /**
  20851. * An event triggered before rendering the mesh
  20852. * @type {BABYLON.Observable}
  20853. */
  20854. _this.onBeforeRenderObservable = new BABYLON.Observable();
  20855. /**
  20856. * An event triggered after rendering the mesh
  20857. * @type {BABYLON.Observable}
  20858. */
  20859. _this.onAfterRenderObservable = new BABYLON.Observable();
  20860. /**
  20861. * An event triggered before drawing the mesh
  20862. * @type {BABYLON.Observable}
  20863. */
  20864. _this.onBeforeDrawObservable = new BABYLON.Observable();
  20865. // Members
  20866. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  20867. _this.instances = new Array();
  20868. _this._LODLevels = new Array();
  20869. _this._visibleInstances = {};
  20870. _this._renderIdForInstances = new Array();
  20871. _this._batchCache = new _InstancesBatch();
  20872. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  20873. _this._sideOrientation = Mesh._DEFAULTSIDE;
  20874. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  20875. // Will be used to save a source mesh reference, If any
  20876. _this._source = null;
  20877. if (source) {
  20878. // Source mesh
  20879. _this._source = source;
  20880. // Geometry
  20881. if (source._geometry) {
  20882. source._geometry.applyToMesh(_this);
  20883. }
  20884. // Deep copy
  20885. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId"], ["_poseMatrix"]);
  20886. // Parent
  20887. _this.parent = source.parent;
  20888. // Pivot
  20889. _this.setPivotMatrix(source.getPivotMatrix());
  20890. _this.id = name + "." + source.id;
  20891. // Material
  20892. _this.material = source.material;
  20893. var index;
  20894. if (!doNotCloneChildren) {
  20895. // Children
  20896. for (index = 0; index < scene.meshes.length; index++) {
  20897. var mesh = scene.meshes[index];
  20898. if (mesh.parent === source) {
  20899. // doNotCloneChildren is always going to be False
  20900. var newChild = mesh.clone(name + "." + mesh.name, _this, doNotCloneChildren);
  20901. }
  20902. }
  20903. }
  20904. // Physics clone
  20905. var physicsEngine = _this.getScene().getPhysicsEngine();
  20906. if (clonePhysicsImpostor && physicsEngine) {
  20907. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  20908. if (impostor) {
  20909. _this.physicsImpostor = impostor.clone(_this);
  20910. }
  20911. }
  20912. // Particles
  20913. for (index = 0; index < scene.particleSystems.length; index++) {
  20914. var system = scene.particleSystems[index];
  20915. if (system.emitter === source) {
  20916. system.clone(system.name, _this);
  20917. }
  20918. }
  20919. _this.computeWorldMatrix(true);
  20920. }
  20921. // Parent
  20922. if (parent !== null) {
  20923. _this.parent = parent;
  20924. }
  20925. return _this;
  20926. }
  20927. Object.defineProperty(Mesh, "FRONTSIDE", {
  20928. /**
  20929. * Mesh side orientation : usually the external or front surface
  20930. */
  20931. get: function () {
  20932. return Mesh._FRONTSIDE;
  20933. },
  20934. enumerable: true,
  20935. configurable: true
  20936. });
  20937. Object.defineProperty(Mesh, "BACKSIDE", {
  20938. /**
  20939. * Mesh side orientation : usually the internal or back surface
  20940. */
  20941. get: function () {
  20942. return Mesh._BACKSIDE;
  20943. },
  20944. enumerable: true,
  20945. configurable: true
  20946. });
  20947. Object.defineProperty(Mesh, "DOUBLESIDE", {
  20948. /**
  20949. * Mesh side orientation : both internal and external or front and back surfaces
  20950. */
  20951. get: function () {
  20952. return Mesh._DOUBLESIDE;
  20953. },
  20954. enumerable: true,
  20955. configurable: true
  20956. });
  20957. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  20958. /**
  20959. * Mesh side orientation : by default, `FRONTSIDE`
  20960. */
  20961. get: function () {
  20962. return Mesh._DEFAULTSIDE;
  20963. },
  20964. enumerable: true,
  20965. configurable: true
  20966. });
  20967. Object.defineProperty(Mesh, "NO_CAP", {
  20968. /**
  20969. * Mesh cap setting : no cap
  20970. */
  20971. get: function () {
  20972. return Mesh._NO_CAP;
  20973. },
  20974. enumerable: true,
  20975. configurable: true
  20976. });
  20977. Object.defineProperty(Mesh, "CAP_START", {
  20978. /**
  20979. * Mesh cap setting : one cap at the beginning of the mesh
  20980. */
  20981. get: function () {
  20982. return Mesh._CAP_START;
  20983. },
  20984. enumerable: true,
  20985. configurable: true
  20986. });
  20987. Object.defineProperty(Mesh, "CAP_END", {
  20988. /**
  20989. * Mesh cap setting : one cap at the end of the mesh
  20990. */
  20991. get: function () {
  20992. return Mesh._CAP_END;
  20993. },
  20994. enumerable: true,
  20995. configurable: true
  20996. });
  20997. Object.defineProperty(Mesh, "CAP_ALL", {
  20998. /**
  20999. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  21000. */
  21001. get: function () {
  21002. return Mesh._CAP_ALL;
  21003. },
  21004. enumerable: true,
  21005. configurable: true
  21006. });
  21007. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  21008. set: function (callback) {
  21009. if (this._onBeforeDrawObserver) {
  21010. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  21011. }
  21012. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  21013. },
  21014. enumerable: true,
  21015. configurable: true
  21016. });
  21017. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  21018. get: function () {
  21019. return this._morphTargetManager;
  21020. },
  21021. set: function (value) {
  21022. if (this._morphTargetManager === value) {
  21023. return;
  21024. }
  21025. this._morphTargetManager = value;
  21026. this._syncGeometryWithMorphTargetManager();
  21027. },
  21028. enumerable: true,
  21029. configurable: true
  21030. });
  21031. Object.defineProperty(Mesh.prototype, "source", {
  21032. get: function () {
  21033. return this._source;
  21034. },
  21035. enumerable: true,
  21036. configurable: true
  21037. });
  21038. // Methods
  21039. /**
  21040. * Returns the string "Mesh".
  21041. */
  21042. Mesh.prototype.getClassName = function () {
  21043. return "Mesh";
  21044. };
  21045. /**
  21046. * Returns a string.
  21047. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  21048. */
  21049. Mesh.prototype.toString = function (fullDetails) {
  21050. var ret = _super.prototype.toString.call(this, fullDetails);
  21051. ret += ", n vertices: " + this.getTotalVertices();
  21052. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  21053. if (this.animations) {
  21054. for (var i = 0; i < this.animations.length; i++) {
  21055. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21056. }
  21057. }
  21058. if (fullDetails) {
  21059. ret += ", flat shading: " + (this._geometry ? (this.getVerticesData(BABYLON.VertexBuffer.PositionKind).length / 3 === this.getIndices().length ? "YES" : "NO") : "UNKNOWN");
  21060. }
  21061. return ret;
  21062. };
  21063. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  21064. /**
  21065. * True if the mesh has some Levels Of Details (LOD).
  21066. * Returns a boolean.
  21067. */
  21068. get: function () {
  21069. return this._LODLevels.length > 0;
  21070. },
  21071. enumerable: true,
  21072. configurable: true
  21073. });
  21074. Mesh.prototype._sortLODLevels = function () {
  21075. this._LODLevels.sort(function (a, b) {
  21076. if (a.distance < b.distance) {
  21077. return 1;
  21078. }
  21079. if (a.distance > b.distance) {
  21080. return -1;
  21081. }
  21082. return 0;
  21083. });
  21084. };
  21085. /**
  21086. * Add a mesh as LOD level triggered at the given distance.
  21087. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21088. * @param {number} distance The distance from the center of the object to show this level
  21089. * @param {Mesh} mesh The mesh to be added as LOD level
  21090. * @return {Mesh} This mesh (for chaining)
  21091. */
  21092. Mesh.prototype.addLODLevel = function (distance, mesh) {
  21093. if (mesh && mesh._masterMesh) {
  21094. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  21095. return this;
  21096. }
  21097. var level = new BABYLON.Internals.MeshLODLevel(distance, mesh);
  21098. this._LODLevels.push(level);
  21099. if (mesh) {
  21100. mesh._masterMesh = this;
  21101. }
  21102. this._sortLODLevels();
  21103. return this;
  21104. };
  21105. /**
  21106. * Returns the LOD level mesh at the passed distance or null if not found.
  21107. * It is related to the method `addLODLevel(distance, mesh)`.
  21108. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21109. * Returns an object Mesh or `null`.
  21110. */
  21111. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  21112. for (var index = 0; index < this._LODLevels.length; index++) {
  21113. var level = this._LODLevels[index];
  21114. if (level.distance === distance) {
  21115. return level.mesh;
  21116. }
  21117. }
  21118. return null;
  21119. };
  21120. /**
  21121. * Remove a mesh from the LOD array
  21122. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21123. * @param {Mesh} mesh The mesh to be removed.
  21124. * @return {Mesh} This mesh (for chaining)
  21125. */
  21126. Mesh.prototype.removeLODLevel = function (mesh) {
  21127. for (var index = 0; index < this._LODLevels.length; index++) {
  21128. if (this._LODLevels[index].mesh === mesh) {
  21129. this._LODLevels.splice(index, 1);
  21130. if (mesh) {
  21131. mesh._masterMesh = null;
  21132. }
  21133. }
  21134. }
  21135. this._sortLODLevels();
  21136. return this;
  21137. };
  21138. /**
  21139. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  21140. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  21141. */
  21142. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  21143. if (!this._LODLevels || this._LODLevels.length === 0) {
  21144. return this;
  21145. }
  21146. var distanceToCamera = (boundingSphere ? boundingSphere : this.getBoundingInfo().boundingSphere).centerWorld.subtract(camera.globalPosition).length();
  21147. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  21148. if (this.onLODLevelSelection) {
  21149. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  21150. }
  21151. return this;
  21152. }
  21153. for (var index = 0; index < this._LODLevels.length; index++) {
  21154. var level = this._LODLevels[index];
  21155. if (level.distance < distanceToCamera) {
  21156. if (level.mesh) {
  21157. level.mesh._preActivate();
  21158. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  21159. }
  21160. if (this.onLODLevelSelection) {
  21161. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  21162. }
  21163. return level.mesh;
  21164. }
  21165. }
  21166. if (this.onLODLevelSelection) {
  21167. this.onLODLevelSelection(distanceToCamera, this, this);
  21168. }
  21169. return this;
  21170. };
  21171. Object.defineProperty(Mesh.prototype, "geometry", {
  21172. /**
  21173. * Returns the mesh internal Geometry object.
  21174. */
  21175. get: function () {
  21176. return this._geometry;
  21177. },
  21178. enumerable: true,
  21179. configurable: true
  21180. });
  21181. /**
  21182. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  21183. */
  21184. Mesh.prototype.getTotalVertices = function () {
  21185. if (!this._geometry) {
  21186. return 0;
  21187. }
  21188. return this._geometry.getTotalVertices();
  21189. };
  21190. /**
  21191. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  21192. * 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.
  21193. * You can force the copy with forceCopy === true
  21194. * Returns null if the mesh has no geometry or no vertex buffer.
  21195. * Possible `kind` values :
  21196. * - BABYLON.VertexBuffer.PositionKind
  21197. * - BABYLON.VertexBuffer.UVKind
  21198. * - BABYLON.VertexBuffer.UV2Kind
  21199. * - BABYLON.VertexBuffer.UV3Kind
  21200. * - BABYLON.VertexBuffer.UV4Kind
  21201. * - BABYLON.VertexBuffer.UV5Kind
  21202. * - BABYLON.VertexBuffer.UV6Kind
  21203. * - BABYLON.VertexBuffer.ColorKind
  21204. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21205. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21206. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21207. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21208. */
  21209. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  21210. if (!this._geometry) {
  21211. return null;
  21212. }
  21213. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  21214. };
  21215. /**
  21216. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  21217. * Returns `undefined` if the mesh has no geometry.
  21218. * Possible `kind` values :
  21219. * - BABYLON.VertexBuffer.PositionKind
  21220. * - BABYLON.VertexBuffer.UVKind
  21221. * - BABYLON.VertexBuffer.UV2Kind
  21222. * - BABYLON.VertexBuffer.UV3Kind
  21223. * - BABYLON.VertexBuffer.UV4Kind
  21224. * - BABYLON.VertexBuffer.UV5Kind
  21225. * - BABYLON.VertexBuffer.UV6Kind
  21226. * - BABYLON.VertexBuffer.ColorKind
  21227. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21228. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21229. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21230. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21231. */
  21232. Mesh.prototype.getVertexBuffer = function (kind) {
  21233. if (!this._geometry) {
  21234. return undefined;
  21235. }
  21236. return this._geometry.getVertexBuffer(kind);
  21237. };
  21238. /**
  21239. * Returns a boolean depending on the existence of the Vertex Data for the requested `kind`.
  21240. * Possible `kind` values :
  21241. * - BABYLON.VertexBuffer.PositionKind
  21242. * - BABYLON.VertexBuffer.UVKind
  21243. * - BABYLON.VertexBuffer.UV2Kind
  21244. * - BABYLON.VertexBuffer.UV3Kind
  21245. * - BABYLON.VertexBuffer.UV4Kind
  21246. * - BABYLON.VertexBuffer.UV5Kind
  21247. * - BABYLON.VertexBuffer.UV6Kind
  21248. * - BABYLON.VertexBuffer.ColorKind
  21249. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21250. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21251. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21252. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21253. */
  21254. Mesh.prototype.isVerticesDataPresent = function (kind) {
  21255. if (!this._geometry) {
  21256. if (this._delayInfo) {
  21257. return this._delayInfo.indexOf(kind) !== -1;
  21258. }
  21259. return false;
  21260. }
  21261. return this._geometry.isVerticesDataPresent(kind);
  21262. };
  21263. /**
  21264. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  21265. * Possible `kind` values :
  21266. * - BABYLON.VertexBuffer.PositionKind
  21267. * - BABYLON.VertexBuffer.UVKind
  21268. * - BABYLON.VertexBuffer.UV2Kind
  21269. * - BABYLON.VertexBuffer.UV3Kind
  21270. * - BABYLON.VertexBuffer.UV4Kind
  21271. * - BABYLON.VertexBuffer.UV5Kind
  21272. * - BABYLON.VertexBuffer.UV6Kind
  21273. * - BABYLON.VertexBuffer.ColorKind
  21274. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21275. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21276. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21277. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21278. */
  21279. Mesh.prototype.getVerticesDataKinds = function () {
  21280. if (!this._geometry) {
  21281. var result = [];
  21282. if (this._delayInfo) {
  21283. this._delayInfo.forEach(function (kind, index, array) {
  21284. result.push(kind);
  21285. });
  21286. }
  21287. return result;
  21288. }
  21289. return this._geometry.getVerticesDataKinds();
  21290. };
  21291. /**
  21292. * Returns a positive integer : the total number of indices in this mesh geometry.
  21293. * Returns zero if the mesh has no geometry.
  21294. */
  21295. Mesh.prototype.getTotalIndices = function () {
  21296. if (!this._geometry) {
  21297. return 0;
  21298. }
  21299. return this._geometry.getTotalIndices();
  21300. };
  21301. /**
  21302. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  21303. * 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.
  21304. * Returns an empty array if the mesh has no geometry.
  21305. */
  21306. Mesh.prototype.getIndices = function (copyWhenShared) {
  21307. if (!this._geometry) {
  21308. return [];
  21309. }
  21310. return this._geometry.getIndices(copyWhenShared);
  21311. };
  21312. Object.defineProperty(Mesh.prototype, "isBlocked", {
  21313. get: function () {
  21314. return this._masterMesh !== null && this._masterMesh !== undefined;
  21315. },
  21316. enumerable: true,
  21317. configurable: true
  21318. });
  21319. /**
  21320. * Boolean : true once the mesh is ready after all the delayed process (loading, etc) are complete.
  21321. */
  21322. Mesh.prototype.isReady = function () {
  21323. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21324. return false;
  21325. }
  21326. return _super.prototype.isReady.call(this);
  21327. };
  21328. Object.defineProperty(Mesh.prototype, "sideOrientation", {
  21329. get: function () {
  21330. return this._sideOrientation;
  21331. },
  21332. /**
  21333. * Sets the mesh side orientation : BABYLON.Mesh.FRONTSIDE, BABYLON.Mesh.BACKSIDE, BABYLON.Mesh.DOUBLESIDE or BABYLON.Mesh.DEFAULTSIDE
  21334. * tuto : http://doc.babylonjs.com/tutorials/Discover_Basic_Elements#side-orientation
  21335. */
  21336. set: function (sideO) {
  21337. this._sideOrientation = sideO;
  21338. },
  21339. enumerable: true,
  21340. configurable: true
  21341. });
  21342. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  21343. /**
  21344. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  21345. * This property is pertinent only for updatable parametric shapes.
  21346. */
  21347. get: function () {
  21348. return this._areNormalsFrozen;
  21349. },
  21350. enumerable: true,
  21351. configurable: true
  21352. });
  21353. /**
  21354. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21355. * It has no effect at all on other shapes.
  21356. * It prevents the mesh normals from being recomputed on next `positions` array update.
  21357. * Returns the Mesh.
  21358. */
  21359. Mesh.prototype.freezeNormals = function () {
  21360. this._areNormalsFrozen = true;
  21361. return this;
  21362. };
  21363. /**
  21364. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  21365. * It has no effect at all on other shapes.
  21366. * It reactivates the mesh normals computation if it was previously frozen.
  21367. * Returns the Mesh.
  21368. */
  21369. Mesh.prototype.unfreezeNormals = function () {
  21370. this._areNormalsFrozen = false;
  21371. return this;
  21372. };
  21373. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  21374. /**
  21375. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  21376. */
  21377. set: function (count) {
  21378. this._overridenInstanceCount = count;
  21379. },
  21380. enumerable: true,
  21381. configurable: true
  21382. });
  21383. // Methods
  21384. Mesh.prototype._preActivate = function () {
  21385. var sceneRenderId = this.getScene().getRenderId();
  21386. if (this._preActivateId === sceneRenderId) {
  21387. return this;
  21388. }
  21389. this._preActivateId = sceneRenderId;
  21390. this._visibleInstances = null;
  21391. return this;
  21392. };
  21393. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  21394. if (this._visibleInstances) {
  21395. this._visibleInstances.intermediateDefaultRenderId = renderId;
  21396. }
  21397. return this;
  21398. };
  21399. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  21400. if (!this._visibleInstances) {
  21401. this._visibleInstances = {};
  21402. this._visibleInstances.defaultRenderId = renderId;
  21403. this._visibleInstances.selfDefaultRenderId = this._renderId;
  21404. }
  21405. if (!this._visibleInstances[renderId]) {
  21406. this._visibleInstances[renderId] = new Array();
  21407. }
  21408. this._visibleInstances[renderId].push(instance);
  21409. return this;
  21410. };
  21411. /**
  21412. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  21413. * This means the mesh underlying bounding box and sphere are recomputed.
  21414. * Returns the Mesh.
  21415. */
  21416. Mesh.prototype.refreshBoundingInfo = function () {
  21417. if (this._boundingInfo.isLocked) {
  21418. return;
  21419. }
  21420. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21421. if (data) {
  21422. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  21423. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  21424. }
  21425. if (this.subMeshes) {
  21426. for (var index = 0; index < this.subMeshes.length; index++) {
  21427. this.subMeshes[index].refreshBoundingInfo();
  21428. }
  21429. }
  21430. this._updateBoundingInfo();
  21431. return this;
  21432. };
  21433. Mesh.prototype._createGlobalSubMesh = function (force) {
  21434. var totalVertices = this.getTotalVertices();
  21435. if (!totalVertices || !this.getIndices()) {
  21436. return null;
  21437. }
  21438. // Check if we need to recreate the submeshes
  21439. if (this.subMeshes && this.subMeshes.length > 0) {
  21440. var totalIndices = this.getIndices().length;
  21441. var needToRecreate = false;
  21442. if (force) {
  21443. needToRecreate = true;
  21444. }
  21445. else {
  21446. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  21447. var submesh = _a[_i];
  21448. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  21449. needToRecreate = true;
  21450. break;
  21451. }
  21452. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  21453. needToRecreate = true;
  21454. break;
  21455. }
  21456. }
  21457. }
  21458. if (!needToRecreate) {
  21459. return;
  21460. }
  21461. }
  21462. this.releaseSubMeshes();
  21463. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  21464. };
  21465. Mesh.prototype.subdivide = function (count) {
  21466. if (count < 1) {
  21467. return;
  21468. }
  21469. var totalIndices = this.getTotalIndices();
  21470. var subdivisionSize = (totalIndices / count) | 0;
  21471. var offset = 0;
  21472. // Ensure that subdivisionSize is a multiple of 3
  21473. while (subdivisionSize % 3 !== 0) {
  21474. subdivisionSize++;
  21475. }
  21476. this.releaseSubMeshes();
  21477. for (var index = 0; index < count; index++) {
  21478. if (offset >= totalIndices) {
  21479. break;
  21480. }
  21481. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  21482. offset += subdivisionSize;
  21483. }
  21484. this.synchronizeInstances();
  21485. };
  21486. /**
  21487. * Sets the vertex data of the mesh geometry for the requested `kind`.
  21488. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  21489. * The `data` are either a numeric array either a Float32Array.
  21490. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  21491. * 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).
  21492. * Note that a new underlying VertexBuffer object is created each call.
  21493. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  21494. *
  21495. * Possible `kind` values :
  21496. * - BABYLON.VertexBuffer.PositionKind
  21497. * - BABYLON.VertexBuffer.UVKind
  21498. * - BABYLON.VertexBuffer.UV2Kind
  21499. * - BABYLON.VertexBuffer.UV3Kind
  21500. * - BABYLON.VertexBuffer.UV4Kind
  21501. * - BABYLON.VertexBuffer.UV5Kind
  21502. * - BABYLON.VertexBuffer.UV6Kind
  21503. * - BABYLON.VertexBuffer.ColorKind
  21504. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21505. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21506. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21507. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21508. *
  21509. * Returns the Mesh.
  21510. */
  21511. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  21512. if (!this._geometry) {
  21513. var vertexData = new BABYLON.VertexData();
  21514. vertexData.set(data, kind);
  21515. var scene = this.getScene();
  21516. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  21517. }
  21518. else {
  21519. this._geometry.setVerticesData(kind, data, updatable, stride);
  21520. }
  21521. return this;
  21522. };
  21523. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  21524. if (updatable === void 0) { updatable = true; }
  21525. if (this.getVertexBuffer(kind).isUpdatable() === updatable) {
  21526. return;
  21527. }
  21528. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  21529. };
  21530. /**
  21531. * Sets the mesh VertexBuffer.
  21532. * Returns the Mesh.
  21533. */
  21534. Mesh.prototype.setVerticesBuffer = function (buffer) {
  21535. if (!this._geometry) {
  21536. var scene = this.getScene();
  21537. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene).applyToMesh(this);
  21538. }
  21539. this._geometry.setVerticesBuffer(buffer);
  21540. return this;
  21541. };
  21542. /**
  21543. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  21544. * If the mesh has no geometry, it is simply returned as it is.
  21545. * The `data` are either a numeric array either a Float32Array.
  21546. * No new underlying VertexBuffer object is created.
  21547. * 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.
  21548. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  21549. *
  21550. * Possible `kind` values :
  21551. * - BABYLON.VertexBuffer.PositionKind
  21552. * - BABYLON.VertexBuffer.UVKind
  21553. * - BABYLON.VertexBuffer.UV2Kind
  21554. * - BABYLON.VertexBuffer.UV3Kind
  21555. * - BABYLON.VertexBuffer.UV4Kind
  21556. * - BABYLON.VertexBuffer.UV5Kind
  21557. * - BABYLON.VertexBuffer.UV6Kind
  21558. * - BABYLON.VertexBuffer.ColorKind
  21559. * - BABYLON.VertexBuffer.MatricesIndicesKind
  21560. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  21561. * - BABYLON.VertexBuffer.MatricesWeightsKind
  21562. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  21563. *
  21564. * Returns the Mesh.
  21565. */
  21566. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  21567. if (!this._geometry) {
  21568. return;
  21569. }
  21570. if (!makeItUnique) {
  21571. this._geometry.updateVerticesData(kind, data, updateExtends);
  21572. }
  21573. else {
  21574. this.makeGeometryUnique();
  21575. this.updateVerticesData(kind, data, updateExtends, false);
  21576. }
  21577. return this;
  21578. };
  21579. /**
  21580. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  21581. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  21582. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  21583. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  21584. * Returns the Mesh.
  21585. */
  21586. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  21587. if (computeNormals === void 0) { computeNormals = true; }
  21588. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21589. positionFunction(positions);
  21590. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  21591. if (computeNormals) {
  21592. var indices = this.getIndices();
  21593. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21594. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  21595. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  21596. }
  21597. return this;
  21598. };
  21599. /**
  21600. * Creates a un-shared specific occurence of the geometry for the mesh.
  21601. * Returns the Mesh.
  21602. */
  21603. Mesh.prototype.makeGeometryUnique = function () {
  21604. if (!this._geometry) {
  21605. return;
  21606. }
  21607. var oldGeometry = this._geometry;
  21608. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  21609. oldGeometry.releaseForMesh(this, true);
  21610. geometry.applyToMesh(this);
  21611. return this;
  21612. };
  21613. /**
  21614. * Sets the mesh indices.
  21615. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  21616. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  21617. * This method creates a new index buffer each call.
  21618. * Returns the Mesh.
  21619. */
  21620. Mesh.prototype.setIndices = function (indices, totalVertices) {
  21621. if (!this._geometry) {
  21622. var vertexData = new BABYLON.VertexData();
  21623. vertexData.indices = indices;
  21624. var scene = this.getScene();
  21625. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, false, this);
  21626. }
  21627. else {
  21628. this._geometry.setIndices(indices, totalVertices);
  21629. }
  21630. return this;
  21631. };
  21632. /**
  21633. * Invert the geometry to move from a right handed system to a left handed one.
  21634. * Returns the Mesh.
  21635. */
  21636. Mesh.prototype.toLeftHanded = function () {
  21637. if (!this._geometry) {
  21638. return;
  21639. }
  21640. this._geometry.toLeftHanded();
  21641. return this;
  21642. };
  21643. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  21644. var engine = this.getScene().getEngine();
  21645. // Wireframe
  21646. var indexToBind;
  21647. if (this._unIndexed) {
  21648. indexToBind = null;
  21649. }
  21650. else {
  21651. switch (fillMode) {
  21652. case BABYLON.Material.PointFillMode:
  21653. indexToBind = null;
  21654. break;
  21655. case BABYLON.Material.WireFrameFillMode:
  21656. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  21657. break;
  21658. default:
  21659. case BABYLON.Material.TriangleFillMode:
  21660. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  21661. break;
  21662. }
  21663. }
  21664. // VBOs
  21665. this._geometry._bind(effect, indexToBind);
  21666. return this;
  21667. };
  21668. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  21669. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21670. return this;
  21671. }
  21672. this.onBeforeDrawObservable.notifyObservers(this);
  21673. var engine = this.getScene().getEngine();
  21674. // Draw order
  21675. switch (fillMode) {
  21676. case BABYLON.Material.PointFillMode:
  21677. engine.drawPointClouds(subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21678. break;
  21679. case BABYLON.Material.WireFrameFillMode:
  21680. if (this._unIndexed) {
  21681. engine.drawUnIndexed(false, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21682. }
  21683. else {
  21684. engine.draw(false, 0, subMesh.linesIndexCount, instancesCount);
  21685. }
  21686. break;
  21687. default:
  21688. if (this._unIndexed) {
  21689. engine.drawUnIndexed(true, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  21690. }
  21691. else {
  21692. engine.draw(true, subMesh.indexStart, subMesh.indexCount, instancesCount);
  21693. }
  21694. }
  21695. return this;
  21696. };
  21697. /**
  21698. * Registers for this mesh a javascript function called just before the rendering process.
  21699. * This function is passed the current mesh.
  21700. * Return the Mesh.
  21701. */
  21702. Mesh.prototype.registerBeforeRender = function (func) {
  21703. this.onBeforeRenderObservable.add(func);
  21704. return this;
  21705. };
  21706. /**
  21707. * Disposes a previously registered javascript function called before the rendering.
  21708. * This function is passed the current mesh.
  21709. * Returns the Mesh.
  21710. */
  21711. Mesh.prototype.unregisterBeforeRender = function (func) {
  21712. this.onBeforeRenderObservable.removeCallback(func);
  21713. return this;
  21714. };
  21715. /**
  21716. * Registers for this mesh a javascript function called just after the rendering is complete.
  21717. * This function is passed the current mesh.
  21718. * Returns the Mesh.
  21719. */
  21720. Mesh.prototype.registerAfterRender = function (func) {
  21721. this.onAfterRenderObservable.add(func);
  21722. return this;
  21723. };
  21724. /**
  21725. * Disposes a previously registered javascript function called after the rendering.
  21726. * This function is passed the current mesh.
  21727. * Return the Mesh.
  21728. */
  21729. Mesh.prototype.unregisterAfterRender = function (func) {
  21730. this.onAfterRenderObservable.removeCallback(func);
  21731. return this;
  21732. };
  21733. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  21734. var scene = this.getScene();
  21735. this._batchCache.mustReturn = false;
  21736. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  21737. this._batchCache.visibleInstances[subMeshId] = null;
  21738. if (this._visibleInstances) {
  21739. var currentRenderId = scene.getRenderId();
  21740. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  21741. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  21742. var selfRenderId = this._renderId;
  21743. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  21744. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  21745. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  21746. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  21747. }
  21748. if (this._batchCache.visibleInstances[subMeshId] && this._batchCache.visibleInstances[subMeshId].length) {
  21749. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  21750. this._batchCache.mustReturn = true;
  21751. return this._batchCache;
  21752. }
  21753. if (currentRenderId !== selfRenderId) {
  21754. this._batchCache.renderSelf[subMeshId] = false;
  21755. }
  21756. }
  21757. this._renderIdForInstances[subMeshId] = currentRenderId;
  21758. }
  21759. return this._batchCache;
  21760. };
  21761. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  21762. var visibleInstances = batch.visibleInstances[subMesh._id];
  21763. var matricesCount = visibleInstances.length + 1;
  21764. var bufferSize = matricesCount * 16 * 4;
  21765. var currentInstancesBufferSize = this._instancesBufferSize;
  21766. var instancesBuffer = this._instancesBuffer;
  21767. while (this._instancesBufferSize < bufferSize) {
  21768. this._instancesBufferSize *= 2;
  21769. }
  21770. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  21771. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  21772. }
  21773. var offset = 0;
  21774. var instancesCount = 0;
  21775. var world = this.getWorldMatrix();
  21776. if (batch.renderSelf[subMesh._id]) {
  21777. world.copyToArray(this._instancesData, offset);
  21778. offset += 16;
  21779. instancesCount++;
  21780. }
  21781. if (visibleInstances) {
  21782. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  21783. var instance = visibleInstances[instanceIndex];
  21784. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  21785. offset += 16;
  21786. instancesCount++;
  21787. }
  21788. }
  21789. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  21790. if (instancesBuffer) {
  21791. instancesBuffer.dispose();
  21792. }
  21793. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  21794. this._instancesBuffer = instancesBuffer;
  21795. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  21796. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  21797. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  21798. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  21799. }
  21800. else {
  21801. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  21802. }
  21803. this._bind(subMesh, effect, fillMode);
  21804. this._draw(subMesh, fillMode, instancesCount);
  21805. engine.unbindInstanceAttributes();
  21806. return this;
  21807. };
  21808. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  21809. var scene = this.getScene();
  21810. var engine = scene.getEngine();
  21811. if (hardwareInstancedRendering) {
  21812. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  21813. }
  21814. else {
  21815. if (batch.renderSelf[subMesh._id]) {
  21816. // Draw
  21817. if (onBeforeDraw) {
  21818. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  21819. }
  21820. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  21821. }
  21822. if (batch.visibleInstances[subMesh._id]) {
  21823. for (var instanceIndex = 0; instanceIndex < batch.visibleInstances[subMesh._id].length; instanceIndex++) {
  21824. var instance = batch.visibleInstances[subMesh._id][instanceIndex];
  21825. // World
  21826. var world = instance.getWorldMatrix();
  21827. if (onBeforeDraw) {
  21828. onBeforeDraw(true, world, effectiveMaterial);
  21829. }
  21830. // Draw
  21831. this._draw(subMesh, fillMode);
  21832. }
  21833. }
  21834. }
  21835. return this;
  21836. };
  21837. /**
  21838. * Triggers the draw call for the mesh.
  21839. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  21840. * Returns the Mesh.
  21841. */
  21842. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  21843. this.checkOcclusionQuery();
  21844. if (this._isOccluded) {
  21845. return;
  21846. }
  21847. var scene = this.getScene();
  21848. // Managing instances
  21849. var batch = this._getInstancesRenderList(subMesh._id);
  21850. if (batch.mustReturn) {
  21851. return this;
  21852. }
  21853. // Checking geometry state
  21854. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  21855. return this;
  21856. }
  21857. var callbackIndex;
  21858. this.onBeforeRenderObservable.notifyObservers(this);
  21859. var engine = scene.getEngine();
  21860. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  21861. // Material
  21862. var effectiveMaterial = subMesh.getMaterial();
  21863. if (!effectiveMaterial) {
  21864. return this;
  21865. }
  21866. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21867. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  21868. return this;
  21869. }
  21870. }
  21871. else if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  21872. return this;
  21873. }
  21874. // Alpha mode
  21875. if (enableAlphaMode) {
  21876. engine.setAlphaMode(effectiveMaterial.alphaMode);
  21877. }
  21878. // Outline - step 1
  21879. var savedDepthWrite = engine.getDepthWrite();
  21880. if (this.renderOutline) {
  21881. engine.setDepthWrite(false);
  21882. scene.getOutlineRenderer().render(subMesh, batch);
  21883. engine.setDepthWrite(savedDepthWrite);
  21884. }
  21885. var effect;
  21886. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21887. effect = subMesh.effect;
  21888. }
  21889. else {
  21890. effect = effectiveMaterial.getEffect();
  21891. }
  21892. effectiveMaterial._preBind(effect);
  21893. // Bind
  21894. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : effectiveMaterial.fillMode);
  21895. if (!hardwareInstancedRendering) {
  21896. this._bind(subMesh, effect, fillMode);
  21897. }
  21898. var world = this.getWorldMatrix();
  21899. if (effectiveMaterial.storeEffectOnSubMeshes) {
  21900. effectiveMaterial.bindForSubMesh(world, this, subMesh);
  21901. }
  21902. else {
  21903. effectiveMaterial.bind(world, this);
  21904. }
  21905. // Draw
  21906. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, effectiveMaterial);
  21907. // Unbind
  21908. effectiveMaterial.unbind();
  21909. // Outline - step 2
  21910. if (this.renderOutline && savedDepthWrite) {
  21911. engine.setDepthWrite(true);
  21912. engine.setColorWrite(false);
  21913. scene.getOutlineRenderer().render(subMesh, batch);
  21914. engine.setColorWrite(true);
  21915. }
  21916. // Overlay
  21917. if (this.renderOverlay) {
  21918. var currentMode = engine.getAlphaMode();
  21919. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  21920. scene.getOutlineRenderer().render(subMesh, batch, true);
  21921. engine.setAlphaMode(currentMode);
  21922. }
  21923. this.onAfterRenderObservable.notifyObservers(this);
  21924. return this;
  21925. };
  21926. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  21927. if (isInstance) {
  21928. effectiveMaterial.bindOnlyWorldMatrix(world);
  21929. }
  21930. return this;
  21931. };
  21932. /**
  21933. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  21934. */
  21935. Mesh.prototype.getEmittedParticleSystems = function () {
  21936. var results = new Array();
  21937. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21938. var particleSystem = this.getScene().particleSystems[index];
  21939. if (particleSystem.emitter === this) {
  21940. results.push(particleSystem);
  21941. }
  21942. }
  21943. return results;
  21944. };
  21945. /**
  21946. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  21947. */
  21948. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  21949. var results = new Array();
  21950. var descendants = this.getDescendants();
  21951. descendants.push(this);
  21952. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  21953. var particleSystem = this.getScene().particleSystems[index];
  21954. var emitter = particleSystem.emitter;
  21955. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  21956. results.push(particleSystem);
  21957. }
  21958. }
  21959. return results;
  21960. };
  21961. Mesh.prototype._checkDelayState = function () {
  21962. var scene = this.getScene();
  21963. if (this._geometry) {
  21964. this._geometry.load(scene);
  21965. }
  21966. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  21967. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  21968. this._queueLoad(this, scene);
  21969. }
  21970. return this;
  21971. };
  21972. Mesh.prototype._queueLoad = function (mesh, scene) {
  21973. var _this = this;
  21974. scene._addPendingData(mesh);
  21975. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  21976. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  21977. if (data instanceof ArrayBuffer) {
  21978. _this._delayLoadingFunction(data, _this);
  21979. }
  21980. else {
  21981. _this._delayLoadingFunction(JSON.parse(data), _this);
  21982. }
  21983. _this.instances.forEach(function (instance) {
  21984. instance._syncSubMeshes();
  21985. });
  21986. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  21987. scene._removePendingData(_this);
  21988. }, function () { }, scene.database, getBinaryData);
  21989. return this;
  21990. };
  21991. /**
  21992. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  21993. */
  21994. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  21995. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  21996. return false;
  21997. }
  21998. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  21999. return false;
  22000. }
  22001. this._checkDelayState();
  22002. return true;
  22003. };
  22004. /**
  22005. * Sets the mesh material by the material or multiMaterial `id` property.
  22006. * The material `id` is a string identifying the material or the multiMaterial.
  22007. * This method returns the Mesh.
  22008. */
  22009. Mesh.prototype.setMaterialByID = function (id) {
  22010. var materials = this.getScene().materials;
  22011. var index;
  22012. for (index = materials.length - 1; index > -1; index--) {
  22013. if (materials[index].id === id) {
  22014. this.material = materials[index];
  22015. return this;
  22016. }
  22017. }
  22018. // Multi
  22019. var multiMaterials = this.getScene().multiMaterials;
  22020. for (index = multiMaterials.length - 1; index > -1; index--) {
  22021. if (multiMaterials[index].id === id) {
  22022. this.material = multiMaterials[index];
  22023. return this;
  22024. }
  22025. }
  22026. return this;
  22027. };
  22028. /**
  22029. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  22030. */
  22031. Mesh.prototype.getAnimatables = function () {
  22032. var results = [];
  22033. if (this.material) {
  22034. results.push(this.material);
  22035. }
  22036. if (this.skeleton) {
  22037. results.push(this.skeleton);
  22038. }
  22039. return results;
  22040. };
  22041. /**
  22042. * Modifies the mesh geometry according to the passed transformation matrix.
  22043. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  22044. * The mesh normals are modified accordingly the same transformation.
  22045. * tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22046. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22047. * Returns the Mesh.
  22048. */
  22049. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  22050. // Position
  22051. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  22052. return this;
  22053. }
  22054. var submeshes = this.subMeshes.splice(0);
  22055. this._resetPointsArrayCache();
  22056. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22057. var temp = [];
  22058. var index;
  22059. for (index = 0; index < data.length; index += 3) {
  22060. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  22061. }
  22062. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  22063. // Normals
  22064. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22065. return this;
  22066. }
  22067. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22068. temp = [];
  22069. for (index = 0; index < data.length; index += 3) {
  22070. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  22071. }
  22072. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  22073. // flip faces?
  22074. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  22075. this.flipFaces();
  22076. }
  22077. // Restore submeshes
  22078. this.releaseSubMeshes();
  22079. this.subMeshes = submeshes;
  22080. return this;
  22081. };
  22082. /**
  22083. * Modifies the mesh geometry according to its own current World Matrix.
  22084. * The mesh World Matrix is then reset.
  22085. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  22086. * tuto : tuto : http://doc.babylonjs.com/tutorials/How_Rotations_and_Translations_Work#baking-transform
  22087. * Note that, under the hood, this method sets a new VertexBuffer each call.
  22088. * Returns the Mesh.
  22089. */
  22090. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  22091. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  22092. this.scaling.copyFromFloats(1, 1, 1);
  22093. this.position.copyFromFloats(0, 0, 0);
  22094. this.rotation.copyFromFloats(0, 0, 0);
  22095. //only if quaternion is already set
  22096. if (this.rotationQuaternion) {
  22097. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  22098. }
  22099. this._worldMatrix = BABYLON.Matrix.Identity();
  22100. return this;
  22101. };
  22102. Object.defineProperty(Mesh.prototype, "_positions", {
  22103. // Cache
  22104. get: function () {
  22105. if (this._geometry) {
  22106. return this._geometry._positions;
  22107. }
  22108. return null;
  22109. },
  22110. enumerable: true,
  22111. configurable: true
  22112. });
  22113. Mesh.prototype._resetPointsArrayCache = function () {
  22114. if (this._geometry) {
  22115. this._geometry._resetPointsArrayCache();
  22116. }
  22117. return this;
  22118. };
  22119. Mesh.prototype._generatePointsArray = function () {
  22120. if (this._geometry) {
  22121. return this._geometry._generatePointsArray();
  22122. }
  22123. return false;
  22124. };
  22125. /**
  22126. * Returns a new Mesh object generated from the current mesh properties.
  22127. * This method must not get confused with createInstance().
  22128. * The parameter `name` is a string, the name given to the new mesh.
  22129. * The optional parameter `newParent` can be any Node object (default `null`).
  22130. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  22131. * 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.
  22132. */
  22133. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  22134. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  22135. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  22136. };
  22137. /**
  22138. * Disposes the mesh.
  22139. * This also frees the memory allocated under the hood to all the buffers used by WebGL.
  22140. */
  22141. Mesh.prototype.dispose = function (doNotRecurse) {
  22142. var _this = this;
  22143. this.morphTargetManager = undefined;
  22144. if (this._geometry) {
  22145. this._geometry.releaseForMesh(this, true);
  22146. }
  22147. // Sources
  22148. var meshes = this.getScene().meshes;
  22149. meshes.forEach(function (mesh) {
  22150. if (mesh._source && mesh._source === _this) {
  22151. mesh._source = null;
  22152. }
  22153. });
  22154. this._source = null;
  22155. // Instances
  22156. if (this._instancesBuffer) {
  22157. this._instancesBuffer.dispose();
  22158. this._instancesBuffer = null;
  22159. }
  22160. while (this.instances.length) {
  22161. this.instances[0].dispose();
  22162. }
  22163. // Highlight layers.
  22164. var highlightLayers = this.getScene().highlightLayers;
  22165. for (var i = 0; i < highlightLayers.length; i++) {
  22166. var highlightLayer = highlightLayers[i];
  22167. if (highlightLayer) {
  22168. highlightLayer.removeMesh(this);
  22169. highlightLayer.removeExcludedMesh(this);
  22170. }
  22171. }
  22172. _super.prototype.dispose.call(this, doNotRecurse);
  22173. };
  22174. /**
  22175. * Modifies the mesh geometry according to a displacement map.
  22176. * 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.
  22177. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22178. * This method returns nothing.
  22179. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  22180. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22181. * 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.
  22182. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22183. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22184. *
  22185. * Returns the Mesh.
  22186. */
  22187. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  22188. var _this = this;
  22189. var scene = this.getScene();
  22190. var onload = function (img) {
  22191. // Getting height map data
  22192. var canvas = document.createElement("canvas");
  22193. var context = canvas.getContext("2d");
  22194. var heightMapWidth = img.width;
  22195. var heightMapHeight = img.height;
  22196. canvas.width = heightMapWidth;
  22197. canvas.height = heightMapHeight;
  22198. context.drawImage(img, 0, 0);
  22199. // Create VertexData from map data
  22200. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  22201. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  22202. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  22203. //execute success callback, if set
  22204. if (onSuccess) {
  22205. onSuccess(_this);
  22206. }
  22207. };
  22208. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  22209. return this;
  22210. };
  22211. /**
  22212. * Modifies the mesh geometry according to a displacementMap buffer.
  22213. * 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.
  22214. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  22215. * This method returns nothing.
  22216. * 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.
  22217. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  22218. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  22219. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  22220. * The parameter `uvScale` is an optional vector2 used to scale UV.
  22221. *
  22222. * Returns the Mesh.
  22223. */
  22224. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  22225. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  22226. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  22227. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  22228. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  22229. return this;
  22230. }
  22231. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22232. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  22233. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  22234. var position = BABYLON.Vector3.Zero();
  22235. var normal = BABYLON.Vector3.Zero();
  22236. var uv = BABYLON.Vector2.Zero();
  22237. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  22238. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  22239. for (var index = 0; index < positions.length; index += 3) {
  22240. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  22241. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  22242. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  22243. // Compute height
  22244. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  22245. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  22246. var pos = (u + v * heightMapWidth) * 4;
  22247. var r = buffer[pos] / 255.0;
  22248. var g = buffer[pos + 1] / 255.0;
  22249. var b = buffer[pos + 2] / 255.0;
  22250. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  22251. normal.normalize();
  22252. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  22253. position = position.add(normal);
  22254. position.toArray(positions, index);
  22255. }
  22256. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  22257. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  22258. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  22259. return this;
  22260. };
  22261. /**
  22262. * Modify the mesh to get a flat shading rendering.
  22263. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  22264. * This method returns the Mesh.
  22265. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  22266. */
  22267. Mesh.prototype.convertToFlatShadedMesh = function () {
  22268. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  22269. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22270. var kinds = this.getVerticesDataKinds();
  22271. var vbs = [];
  22272. var data = [];
  22273. var newdata = [];
  22274. var updatableNormals = false;
  22275. var kindIndex;
  22276. var kind;
  22277. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22278. kind = kinds[kindIndex];
  22279. var vertexBuffer = this.getVertexBuffer(kind);
  22280. if (kind === BABYLON.VertexBuffer.NormalKind) {
  22281. updatableNormals = vertexBuffer.isUpdatable();
  22282. kinds.splice(kindIndex, 1);
  22283. kindIndex--;
  22284. continue;
  22285. }
  22286. vbs[kind] = vertexBuffer;
  22287. data[kind] = vbs[kind].getData();
  22288. newdata[kind] = [];
  22289. }
  22290. // Save previous submeshes
  22291. var previousSubmeshes = this.subMeshes.slice(0);
  22292. var indices = this.getIndices();
  22293. var totalIndices = this.getTotalIndices();
  22294. // Generating unique vertices per face
  22295. var index;
  22296. for (index = 0; index < totalIndices; index++) {
  22297. var vertexIndex = indices[index];
  22298. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22299. kind = kinds[kindIndex];
  22300. var stride = vbs[kind].getStrideSize();
  22301. for (var offset = 0; offset < stride; offset++) {
  22302. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22303. }
  22304. }
  22305. }
  22306. // Updating faces & normal
  22307. var normals = [];
  22308. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  22309. for (index = 0; index < totalIndices; index += 3) {
  22310. indices[index] = index;
  22311. indices[index + 1] = index + 1;
  22312. indices[index + 2] = index + 2;
  22313. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  22314. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  22315. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  22316. var p1p2 = p1.subtract(p2);
  22317. var p3p2 = p3.subtract(p2);
  22318. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  22319. // Store same normals for every vertex
  22320. for (var localIndex = 0; localIndex < 3; localIndex++) {
  22321. normals.push(normal.x);
  22322. normals.push(normal.y);
  22323. normals.push(normal.z);
  22324. }
  22325. }
  22326. this.setIndices(indices);
  22327. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  22328. // Updating vertex buffers
  22329. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22330. kind = kinds[kindIndex];
  22331. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22332. }
  22333. // Updating submeshes
  22334. this.releaseSubMeshes();
  22335. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22336. var previousOne = previousSubmeshes[submeshIndex];
  22337. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22338. }
  22339. this.synchronizeInstances();
  22340. return this;
  22341. };
  22342. /**
  22343. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  22344. * In other words, more vertices, no more indices and a single bigger VBO.
  22345. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  22346. * Returns the Mesh.
  22347. */
  22348. Mesh.prototype.convertToUnIndexedMesh = function () {
  22349. /// <summary>Remove indices by unfolding faces into buffers</summary>
  22350. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  22351. var kinds = this.getVerticesDataKinds();
  22352. var vbs = [];
  22353. var data = [];
  22354. var newdata = [];
  22355. var updatableNormals = false;
  22356. var kindIndex;
  22357. var kind;
  22358. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22359. kind = kinds[kindIndex];
  22360. var vertexBuffer = this.getVertexBuffer(kind);
  22361. vbs[kind] = vertexBuffer;
  22362. data[kind] = vbs[kind].getData();
  22363. newdata[kind] = [];
  22364. }
  22365. // Save previous submeshes
  22366. var previousSubmeshes = this.subMeshes.slice(0);
  22367. var indices = this.getIndices();
  22368. var totalIndices = this.getTotalIndices();
  22369. // Generating unique vertices per face
  22370. var index;
  22371. for (index = 0; index < totalIndices; index++) {
  22372. var vertexIndex = indices[index];
  22373. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22374. kind = kinds[kindIndex];
  22375. var stride = vbs[kind].getStrideSize();
  22376. for (var offset = 0; offset < stride; offset++) {
  22377. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  22378. }
  22379. }
  22380. }
  22381. // Updating indices
  22382. for (index = 0; index < totalIndices; index += 3) {
  22383. indices[index] = index;
  22384. indices[index + 1] = index + 1;
  22385. indices[index + 2] = index + 2;
  22386. }
  22387. this.setIndices(indices);
  22388. // Updating vertex buffers
  22389. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  22390. kind = kinds[kindIndex];
  22391. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  22392. }
  22393. // Updating submeshes
  22394. this.releaseSubMeshes();
  22395. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  22396. var previousOne = previousSubmeshes[submeshIndex];
  22397. var subMesh = new BABYLON.SubMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  22398. }
  22399. this._unIndexed = true;
  22400. this.synchronizeInstances();
  22401. return this;
  22402. };
  22403. /**
  22404. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  22405. * This method returns the Mesh.
  22406. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  22407. */
  22408. Mesh.prototype.flipFaces = function (flipNormals) {
  22409. if (flipNormals === void 0) { flipNormals = false; }
  22410. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  22411. var i;
  22412. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  22413. for (i = 0; i < vertex_data.normals.length; i++) {
  22414. vertex_data.normals[i] *= -1;
  22415. }
  22416. }
  22417. var temp;
  22418. for (i = 0; i < vertex_data.indices.length; i += 3) {
  22419. // reassign indices
  22420. temp = vertex_data.indices[i + 1];
  22421. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  22422. vertex_data.indices[i + 2] = temp;
  22423. }
  22424. vertex_data.applyToMesh(this);
  22425. return this;
  22426. };
  22427. // Instances
  22428. /**
  22429. * Creates a new InstancedMesh object from the mesh model.
  22430. * An instance shares the same properties and the same material than its model.
  22431. * Only these properties of each instance can then be set individually :
  22432. * - position
  22433. * - rotation
  22434. * - rotationQuaternion
  22435. * - setPivotMatrix
  22436. * - scaling
  22437. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  22438. * Warning : this method is not supported for Line mesh and LineSystem
  22439. */
  22440. Mesh.prototype.createInstance = function (name) {
  22441. return new BABYLON.InstancedMesh(name, this);
  22442. };
  22443. /**
  22444. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  22445. * After this call, all the mesh instances have the same submeshes than the current mesh.
  22446. * This method returns the Mesh.
  22447. */
  22448. Mesh.prototype.synchronizeInstances = function () {
  22449. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  22450. var instance = this.instances[instanceIndex];
  22451. instance._syncSubMeshes();
  22452. }
  22453. return this;
  22454. };
  22455. /**
  22456. * Simplify the mesh according to the given array of settings.
  22457. * Function will return immediately and will simplify async. It returns the Mesh.
  22458. * @param settings a collection of simplification settings.
  22459. * @param parallelProcessing should all levels calculate parallel or one after the other.
  22460. * @param type the type of simplification to run.
  22461. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  22462. */
  22463. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  22464. if (parallelProcessing === void 0) { parallelProcessing = true; }
  22465. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  22466. this.getScene().simplificationQueue.addTask({
  22467. settings: settings,
  22468. parallelProcessing: parallelProcessing,
  22469. mesh: this,
  22470. simplificationType: simplificationType,
  22471. successCallback: successCallback
  22472. });
  22473. return this;
  22474. };
  22475. /**
  22476. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  22477. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  22478. * This should be used together with the simplification to avoid disappearing triangles.
  22479. * Returns the Mesh.
  22480. * @param successCallback an optional success callback to be called after the optimization finished.
  22481. */
  22482. Mesh.prototype.optimizeIndices = function (successCallback) {
  22483. var _this = this;
  22484. var indices = this.getIndices();
  22485. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  22486. var vectorPositions = [];
  22487. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  22488. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  22489. }
  22490. var dupes = [];
  22491. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  22492. var realPos = vectorPositions.length - 1 - iteration;
  22493. var testedPosition = vectorPositions[realPos];
  22494. for (var j = 0; j < realPos; ++j) {
  22495. var againstPosition = vectorPositions[j];
  22496. if (testedPosition.equals(againstPosition)) {
  22497. dupes[realPos] = j;
  22498. break;
  22499. }
  22500. }
  22501. }, function () {
  22502. for (var i = 0; i < indices.length; ++i) {
  22503. indices[i] = dupes[indices[i]] || indices[i];
  22504. }
  22505. //indices are now reordered
  22506. var originalSubMeshes = _this.subMeshes.slice(0);
  22507. _this.setIndices(indices);
  22508. _this.subMeshes = originalSubMeshes;
  22509. if (successCallback) {
  22510. successCallback(_this);
  22511. }
  22512. });
  22513. return this;
  22514. };
  22515. Mesh.prototype.serialize = function (serializationObject) {
  22516. serializationObject.name = this.name;
  22517. serializationObject.id = this.id;
  22518. serializationObject.type = this.getClassName();
  22519. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  22520. serializationObject.tags = BABYLON.Tags.GetTags(this);
  22521. }
  22522. serializationObject.position = this.position.asArray();
  22523. if (this.rotationQuaternion) {
  22524. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  22525. }
  22526. else if (this.rotation) {
  22527. serializationObject.rotation = this.rotation.asArray();
  22528. }
  22529. serializationObject.scaling = this.scaling.asArray();
  22530. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  22531. serializationObject.isEnabled = this.isEnabled();
  22532. serializationObject.isVisible = this.isVisible;
  22533. serializationObject.infiniteDistance = this.infiniteDistance;
  22534. serializationObject.pickable = this.isPickable;
  22535. serializationObject.receiveShadows = this.receiveShadows;
  22536. serializationObject.billboardMode = this.billboardMode;
  22537. serializationObject.visibility = this.visibility;
  22538. serializationObject.checkCollisions = this.checkCollisions;
  22539. serializationObject.isBlocker = this.isBlocker;
  22540. // Parent
  22541. if (this.parent) {
  22542. serializationObject.parentId = this.parent.id;
  22543. }
  22544. // Geometry
  22545. var geometry = this._geometry;
  22546. if (geometry) {
  22547. var geometryId = geometry.id;
  22548. serializationObject.geometryId = geometryId;
  22549. // SubMeshes
  22550. serializationObject.subMeshes = [];
  22551. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  22552. var subMesh = this.subMeshes[subIndex];
  22553. serializationObject.subMeshes.push({
  22554. materialIndex: subMesh.materialIndex,
  22555. verticesStart: subMesh.verticesStart,
  22556. verticesCount: subMesh.verticesCount,
  22557. indexStart: subMesh.indexStart,
  22558. indexCount: subMesh.indexCount
  22559. });
  22560. }
  22561. }
  22562. // Material
  22563. if (this.material) {
  22564. serializationObject.materialId = this.material.id;
  22565. }
  22566. else {
  22567. this.material = null;
  22568. }
  22569. // Morph targets
  22570. if (this.morphTargetManager) {
  22571. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  22572. }
  22573. // Skeleton
  22574. if (this.skeleton) {
  22575. serializationObject.skeletonId = this.skeleton.id;
  22576. }
  22577. // Physics
  22578. //TODO implement correct serialization for physics impostors.
  22579. if (this.getPhysicsImpostor()) {
  22580. var impostor = this.getPhysicsImpostor();
  22581. serializationObject.physicsMass = impostor.getParam("mass");
  22582. serializationObject.physicsFriction = impostor.getParam("friction");
  22583. serializationObject.physicsRestitution = impostor.getParam("mass");
  22584. serializationObject.physicsImpostor = this.getPhysicsImpostor().type;
  22585. }
  22586. // Metadata
  22587. if (this.metadata) {
  22588. serializationObject.metadata = this.metadata;
  22589. }
  22590. // Instances
  22591. serializationObject.instances = [];
  22592. for (var index = 0; index < this.instances.length; index++) {
  22593. var instance = this.instances[index];
  22594. var serializationInstance = {
  22595. name: instance.name,
  22596. position: instance.position.asArray(),
  22597. scaling: instance.scaling.asArray()
  22598. };
  22599. if (instance.rotationQuaternion) {
  22600. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  22601. }
  22602. else if (instance.rotation) {
  22603. serializationInstance.rotation = instance.rotation.asArray();
  22604. }
  22605. serializationObject.instances.push(serializationInstance);
  22606. // Animations
  22607. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  22608. serializationInstance.ranges = instance.serializeAnimationRanges();
  22609. }
  22610. //
  22611. // Animations
  22612. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22613. serializationObject.ranges = this.serializeAnimationRanges();
  22614. // Layer mask
  22615. serializationObject.layerMask = this.layerMask;
  22616. // Alpha
  22617. serializationObject.alphaIndex = this.alphaIndex;
  22618. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  22619. // Overlay
  22620. serializationObject.overlayAlpha = this.overlayAlpha;
  22621. serializationObject.overlayColor = this.overlayColor.asArray();
  22622. serializationObject.renderOverlay = this.renderOverlay;
  22623. // Fog
  22624. serializationObject.applyFog = this.applyFog;
  22625. // Action Manager
  22626. if (this.actionManager) {
  22627. serializationObject.actions = this.actionManager.serialize(this.name);
  22628. }
  22629. };
  22630. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  22631. if (!this.geometry) {
  22632. return;
  22633. }
  22634. this._markSubMeshesAsAttributesDirty();
  22635. if (this._morphTargetManager && this._morphTargetManager.vertexCount) {
  22636. if (this._morphTargetManager.vertexCount !== this.getTotalVertices()) {
  22637. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  22638. this.morphTargetManager = undefined;
  22639. return;
  22640. }
  22641. for (var index = 0; index < this.morphTargetManager.numInfluencers; index++) {
  22642. var morphTarget = this.morphTargetManager.getActiveTarget(index);
  22643. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, morphTarget.getPositions(), false, 3);
  22644. if (morphTarget.hasNormals) {
  22645. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, morphTarget.getNormals(), false, 3);
  22646. }
  22647. if (morphTarget.hasTangents) {
  22648. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, morphTarget.getTangents(), false, 3);
  22649. }
  22650. }
  22651. }
  22652. else {
  22653. var index = 0;
  22654. // Positions
  22655. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  22656. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  22657. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  22658. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  22659. }
  22660. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  22661. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  22662. }
  22663. index++;
  22664. }
  22665. }
  22666. };
  22667. // Statics
  22668. /**
  22669. * Returns a new Mesh object what is a deep copy of the passed mesh.
  22670. * The parameter `parsedMesh` is the mesh to be copied.
  22671. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  22672. */
  22673. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  22674. var mesh;
  22675. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  22676. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  22677. }
  22678. else {
  22679. mesh = new Mesh(parsedMesh.name, scene);
  22680. }
  22681. mesh.id = parsedMesh.id;
  22682. if (BABYLON.Tags) {
  22683. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  22684. }
  22685. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  22686. if (parsedMesh.metadata !== undefined) {
  22687. mesh.metadata = parsedMesh.metadata;
  22688. }
  22689. if (parsedMesh.rotationQuaternion) {
  22690. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  22691. }
  22692. else if (parsedMesh.rotation) {
  22693. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  22694. }
  22695. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  22696. if (parsedMesh.localMatrix) {
  22697. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  22698. }
  22699. else if (parsedMesh.pivotMatrix) {
  22700. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  22701. }
  22702. mesh.setEnabled(parsedMesh.isEnabled);
  22703. mesh.isVisible = parsedMesh.isVisible;
  22704. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  22705. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  22706. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  22707. if (parsedMesh.applyFog !== undefined) {
  22708. mesh.applyFog = parsedMesh.applyFog;
  22709. }
  22710. if (parsedMesh.pickable !== undefined) {
  22711. mesh.isPickable = parsedMesh.pickable;
  22712. }
  22713. if (parsedMesh.alphaIndex !== undefined) {
  22714. mesh.alphaIndex = parsedMesh.alphaIndex;
  22715. }
  22716. mesh.receiveShadows = parsedMesh.receiveShadows;
  22717. mesh.billboardMode = parsedMesh.billboardMode;
  22718. if (parsedMesh.visibility !== undefined) {
  22719. mesh.visibility = parsedMesh.visibility;
  22720. }
  22721. mesh.checkCollisions = parsedMesh.checkCollisions;
  22722. if (parsedMesh.isBlocker !== undefined) {
  22723. mesh.isBlocker = parsedMesh.isBlocker;
  22724. }
  22725. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  22726. // freezeWorldMatrix
  22727. if (parsedMesh.freezeWorldMatrix) {
  22728. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  22729. }
  22730. // Parent
  22731. if (parsedMesh.parentId) {
  22732. mesh._waitingParentId = parsedMesh.parentId;
  22733. }
  22734. // Actions
  22735. if (parsedMesh.actions !== undefined) {
  22736. mesh._waitingActions = parsedMesh.actions;
  22737. }
  22738. // Overlay
  22739. if (parsedMesh.overlayAlpha !== undefined) {
  22740. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  22741. }
  22742. if (parsedMesh.overlayColor !== undefined) {
  22743. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  22744. }
  22745. if (parsedMesh.renderOverlay !== undefined) {
  22746. mesh.renderOverlay = parsedMesh.renderOverlay;
  22747. }
  22748. // Geometry
  22749. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  22750. if (parsedMesh.delayLoadingFile) {
  22751. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  22752. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  22753. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  22754. if (parsedMesh._binaryInfo) {
  22755. mesh._binaryInfo = parsedMesh._binaryInfo;
  22756. }
  22757. mesh._delayInfo = [];
  22758. if (parsedMesh.hasUVs) {
  22759. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  22760. }
  22761. if (parsedMesh.hasUVs2) {
  22762. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  22763. }
  22764. if (parsedMesh.hasUVs3) {
  22765. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  22766. }
  22767. if (parsedMesh.hasUVs4) {
  22768. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  22769. }
  22770. if (parsedMesh.hasUVs5) {
  22771. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  22772. }
  22773. if (parsedMesh.hasUVs6) {
  22774. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  22775. }
  22776. if (parsedMesh.hasColors) {
  22777. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  22778. }
  22779. if (parsedMesh.hasMatricesIndices) {
  22780. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  22781. }
  22782. if (parsedMesh.hasMatricesWeights) {
  22783. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  22784. }
  22785. mesh._delayLoadingFunction = BABYLON.Geometry.ImportGeometry;
  22786. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  22787. mesh._checkDelayState();
  22788. }
  22789. }
  22790. else {
  22791. BABYLON.Geometry.ImportGeometry(parsedMesh, mesh);
  22792. }
  22793. // Material
  22794. if (parsedMesh.materialId) {
  22795. mesh.setMaterialByID(parsedMesh.materialId);
  22796. }
  22797. else {
  22798. mesh.material = null;
  22799. }
  22800. // Morph targets
  22801. if (parsedMesh.morphTargetManagerId > -1) {
  22802. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  22803. }
  22804. // Skeleton
  22805. if (parsedMesh.skeletonId > -1) {
  22806. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  22807. if (parsedMesh.numBoneInfluencers) {
  22808. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  22809. }
  22810. }
  22811. // Animations
  22812. if (parsedMesh.animations) {
  22813. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22814. var parsedAnimation = parsedMesh.animations[animationIndex];
  22815. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22816. }
  22817. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  22818. }
  22819. if (parsedMesh.autoAnimate) {
  22820. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  22821. }
  22822. // Layer Mask
  22823. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  22824. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  22825. }
  22826. else {
  22827. mesh.layerMask = 0x0FFFFFFF;
  22828. }
  22829. // Physics
  22830. if (parsedMesh.physicsImpostor) {
  22831. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  22832. mass: parsedMesh.physicsMass,
  22833. friction: parsedMesh.physicsFriction,
  22834. restitution: parsedMesh.physicsRestitution
  22835. }, scene);
  22836. }
  22837. // Instances
  22838. if (parsedMesh.instances) {
  22839. for (var index = 0; index < parsedMesh.instances.length; index++) {
  22840. var parsedInstance = parsedMesh.instances[index];
  22841. var instance = mesh.createInstance(parsedInstance.name);
  22842. if (BABYLON.Tags) {
  22843. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  22844. }
  22845. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  22846. if (parsedInstance.parentId) {
  22847. instance._waitingParentId = parsedInstance.parentId;
  22848. }
  22849. if (parsedInstance.rotationQuaternion) {
  22850. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  22851. }
  22852. else if (parsedInstance.rotation) {
  22853. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  22854. }
  22855. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  22856. instance.checkCollisions = mesh.checkCollisions;
  22857. if (parsedMesh.animations) {
  22858. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  22859. parsedAnimation = parsedMesh.animations[animationIndex];
  22860. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22861. }
  22862. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  22863. }
  22864. }
  22865. }
  22866. return mesh;
  22867. };
  22868. /**
  22869. * Creates a ribbon mesh.
  22870. * Please consider using the same method from the MeshBuilder class instead.
  22871. * 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.
  22872. *
  22873. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  22874. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  22875. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  22876. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  22877. * 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.
  22878. * 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.
  22879. * 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
  22880. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22881. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22882. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22883. */
  22884. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  22885. return BABYLON.MeshBuilder.CreateRibbon(name, {
  22886. pathArray: pathArray,
  22887. closeArray: closeArray,
  22888. closePath: closePath,
  22889. offset: offset,
  22890. updatable: updatable,
  22891. sideOrientation: sideOrientation,
  22892. instance: instance
  22893. }, scene);
  22894. };
  22895. /**
  22896. * Creates a plane polygonal mesh. By default, this is a disc.
  22897. * Please consider using the same method from the MeshBuilder class instead.
  22898. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  22899. * 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.
  22900. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22901. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22902. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22903. */
  22904. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  22905. var options = {
  22906. radius: radius,
  22907. tessellation: tessellation,
  22908. sideOrientation: sideOrientation,
  22909. updatable: updatable
  22910. };
  22911. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  22912. };
  22913. /**
  22914. * Creates a box mesh.
  22915. * Please consider using the same method from the MeshBuilder class instead.
  22916. * The parameter `size` sets the size (float) of each box side (default 1).
  22917. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22918. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22919. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22920. */
  22921. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  22922. var options = {
  22923. size: size,
  22924. sideOrientation: sideOrientation,
  22925. updatable: updatable
  22926. };
  22927. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  22928. };
  22929. /**
  22930. * Creates a sphere mesh.
  22931. * Please consider using the same method from the MeshBuilder class instead.
  22932. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  22933. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  22934. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22935. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22936. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22937. */
  22938. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  22939. var options = {
  22940. segments: segments,
  22941. diameterX: diameter,
  22942. diameterY: diameter,
  22943. diameterZ: diameter,
  22944. sideOrientation: sideOrientation,
  22945. updatable: updatable
  22946. };
  22947. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  22948. };
  22949. /**
  22950. * Creates a cylinder or a cone mesh.
  22951. * Please consider using the same method from the MeshBuilder class instead.
  22952. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  22953. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  22954. * 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.
  22955. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  22956. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  22957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22958. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22960. */
  22961. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  22962. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  22963. if (scene !== undefined) {
  22964. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  22965. updatable = scene;
  22966. }
  22967. scene = subdivisions;
  22968. subdivisions = 1;
  22969. }
  22970. var options = {
  22971. height: height,
  22972. diameterTop: diameterTop,
  22973. diameterBottom: diameterBottom,
  22974. tessellation: tessellation,
  22975. subdivisions: subdivisions,
  22976. sideOrientation: sideOrientation,
  22977. updatable: updatable
  22978. };
  22979. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  22980. };
  22981. // Torus (Code from SharpDX.org)
  22982. /**
  22983. * Creates a torus mesh.
  22984. * Please consider using the same method from the MeshBuilder class instead.
  22985. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  22986. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  22987. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  22988. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  22989. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  22990. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  22991. */
  22992. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  22993. var options = {
  22994. diameter: diameter,
  22995. thickness: thickness,
  22996. tessellation: tessellation,
  22997. sideOrientation: sideOrientation,
  22998. updatable: updatable
  22999. };
  23000. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  23001. };
  23002. /**
  23003. * Creates a torus knot mesh.
  23004. * Please consider using the same method from the MeshBuilder class instead.
  23005. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  23006. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  23007. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  23008. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  23009. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23010. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23011. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23012. */
  23013. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  23014. var options = {
  23015. radius: radius,
  23016. tube: tube,
  23017. radialSegments: radialSegments,
  23018. tubularSegments: tubularSegments,
  23019. p: p,
  23020. q: q,
  23021. sideOrientation: sideOrientation,
  23022. updatable: updatable
  23023. };
  23024. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  23025. };
  23026. /**
  23027. * Creates a line mesh.
  23028. * Please consider using the same method from the MeshBuilder class instead.
  23029. * 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.
  23030. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23031. * The parameter `points` is an array successive Vector3.
  23032. * 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
  23033. * When updating an instance, remember that only point positions can change, not the number of points.
  23034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23035. */
  23036. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  23037. var options = {
  23038. points: points,
  23039. updatable: updatable,
  23040. instance: instance
  23041. };
  23042. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  23043. };
  23044. /**
  23045. * Creates a dashed line mesh.
  23046. * Please consider using the same method from the MeshBuilder class instead.
  23047. * 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.
  23048. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  23049. * The parameter `points` is an array successive Vector3.
  23050. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  23051. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  23052. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  23053. * 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
  23054. * When updating an instance, remember that only point positions can change, not the number of points.
  23055. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23056. */
  23057. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  23058. var options = {
  23059. points: points,
  23060. dashSize: dashSize,
  23061. gapSize: gapSize,
  23062. dashNb: dashNb,
  23063. updatable: updatable,
  23064. instance: instance
  23065. };
  23066. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  23067. };
  23068. /**
  23069. * Creates a polygon mesh.
  23070. * Please consider using the same method from the MeshBuilder class instead.
  23071. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  23072. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  23073. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23074. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23075. * Remember you can only change the shape positions, not their number when updating a polygon.
  23076. */
  23077. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  23078. var options = {
  23079. shape: shape,
  23080. holes: holes,
  23081. updatable: updatable,
  23082. sideOrientation: sideOrientation
  23083. };
  23084. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  23085. };
  23086. /**
  23087. * Creates an extruded polygon mesh, with depth in the Y direction.
  23088. * Please consider using the same method from the MeshBuilder class instead.
  23089. */
  23090. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  23091. var options = {
  23092. shape: shape,
  23093. holes: holes,
  23094. depth: depth,
  23095. updatable: updatable,
  23096. sideOrientation: sideOrientation
  23097. };
  23098. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  23099. };
  23100. /**
  23101. * Creates an extruded shape mesh.
  23102. * 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.
  23103. * Please consider using the same method from the MeshBuilder class instead.
  23104. *
  23105. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23106. * 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
  23107. * extruded along the Z axis.
  23108. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23109. * 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.
  23110. * The parameter `scale` (float, default 1) is the value to scale the shape.
  23111. * 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
  23112. * 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
  23113. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23114. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23115. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23116. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23117. */
  23118. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  23119. var options = {
  23120. shape: shape,
  23121. path: path,
  23122. scale: scale,
  23123. rotation: rotation,
  23124. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23125. sideOrientation: sideOrientation,
  23126. instance: instance,
  23127. updatable: updatable
  23128. };
  23129. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  23130. };
  23131. /**
  23132. * Creates an custom extruded shape mesh.
  23133. * 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.
  23134. * Please consider using the same method from the MeshBuilder class instead.
  23135. *
  23136. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  23137. * 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
  23138. * extruded along the Z axis.
  23139. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  23140. * 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
  23141. * and the distance of this point from the begining of the path :
  23142. * ```javascript
  23143. * var rotationFunction = function(i, distance) {
  23144. * // do things
  23145. * return rotationValue; }
  23146. * ```
  23147. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  23148. * 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
  23149. * and the distance of this point from the begining of the path :
  23150. * ```javascript
  23151. * var scaleFunction = function(i, distance) {
  23152. * // do things
  23153. * return scaleValue;}
  23154. * ```
  23155. * It must returns a float value that will be the scale value applied to the shape on each path point.
  23156. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  23157. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  23158. * 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
  23159. * 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
  23160. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  23161. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23162. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23163. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23164. */
  23165. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  23166. var options = {
  23167. shape: shape,
  23168. path: path,
  23169. scaleFunction: scaleFunction,
  23170. rotationFunction: rotationFunction,
  23171. ribbonCloseArray: ribbonCloseArray,
  23172. ribbonClosePath: ribbonClosePath,
  23173. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  23174. sideOrientation: sideOrientation,
  23175. instance: instance,
  23176. updatable: updatable
  23177. };
  23178. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  23179. };
  23180. /**
  23181. * Creates lathe mesh.
  23182. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  23183. * Please consider using the same method from the MeshBuilder class instead.
  23184. * 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
  23185. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  23186. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  23187. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  23188. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23189. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23190. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23191. */
  23192. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  23193. var options = {
  23194. shape: shape,
  23195. radius: radius,
  23196. tessellation: tessellation,
  23197. sideOrientation: sideOrientation,
  23198. updatable: updatable
  23199. };
  23200. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  23201. };
  23202. /**
  23203. * Creates a plane mesh.
  23204. * Please consider using the same method from the MeshBuilder class instead.
  23205. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  23206. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23207. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23208. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23209. */
  23210. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  23211. var options = {
  23212. size: size,
  23213. width: size,
  23214. height: size,
  23215. sideOrientation: sideOrientation,
  23216. updatable: updatable
  23217. };
  23218. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  23219. };
  23220. /**
  23221. * Creates a ground mesh.
  23222. * Please consider using the same method from the MeshBuilder class instead.
  23223. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  23224. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  23225. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23226. */
  23227. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  23228. var options = {
  23229. width: width,
  23230. height: height,
  23231. subdivisions: subdivisions,
  23232. updatable: updatable
  23233. };
  23234. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  23235. };
  23236. /**
  23237. * Creates a tiled ground mesh.
  23238. * Please consider using the same method from the MeshBuilder class instead.
  23239. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  23240. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  23241. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  23242. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  23243. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  23244. * numbers of subdivisions on the ground width and height of each tile.
  23245. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23246. */
  23247. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  23248. var options = {
  23249. xmin: xmin,
  23250. zmin: zmin,
  23251. xmax: xmax,
  23252. zmax: zmax,
  23253. subdivisions: subdivisions,
  23254. precision: precision,
  23255. updatable: updatable
  23256. };
  23257. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  23258. };
  23259. /**
  23260. * Creates a ground mesh from a height map.
  23261. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  23262. * Please consider using the same method from the MeshBuilder class instead.
  23263. * The parameter `url` sets the URL of the height map image resource.
  23264. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  23265. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  23266. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  23267. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  23268. * 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).
  23269. * This function is passed the newly built mesh :
  23270. * ```javascript
  23271. * function(mesh) { // do things
  23272. * return; }
  23273. * ```
  23274. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23275. */
  23276. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  23277. var options = {
  23278. width: width,
  23279. height: height,
  23280. subdivisions: subdivisions,
  23281. minHeight: minHeight,
  23282. maxHeight: maxHeight,
  23283. updatable: updatable,
  23284. onReady: onReady
  23285. };
  23286. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  23287. };
  23288. /**
  23289. * Creates a tube mesh.
  23290. * 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.
  23291. * Please consider using the same method from the MeshBuilder class instead.
  23292. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  23293. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  23294. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  23295. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  23296. * 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.
  23297. * It must return a radius value (positive float) :
  23298. * ```javascript
  23299. * var radiusFunction = function(i, distance) {
  23300. * // do things
  23301. * return radius; }
  23302. * ```
  23303. * 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
  23304. * 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
  23305. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23306. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23307. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23308. */
  23309. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  23310. var options = {
  23311. path: path,
  23312. radius: radius,
  23313. tessellation: tessellation,
  23314. radiusFunction: radiusFunction,
  23315. arc: 1,
  23316. cap: cap,
  23317. updatable: updatable,
  23318. sideOrientation: sideOrientation,
  23319. instance: instance
  23320. };
  23321. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  23322. };
  23323. /**
  23324. * Creates a polyhedron mesh.
  23325. * Please consider using the same method from the MeshBuilder class instead.
  23326. * 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
  23327. * to choose the wanted type.
  23328. * The parameter `size` (positive float, default 1) sets the polygon size.
  23329. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  23330. * 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`.
  23331. * 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
  23332. * 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)`).
  23333. * 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
  23334. * 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.
  23335. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23336. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23337. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23338. */
  23339. Mesh.CreatePolyhedron = function (name, options, scene) {
  23340. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  23341. };
  23342. /**
  23343. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  23344. * Please consider using the same method from the MeshBuilder class instead.
  23345. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  23346. * 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`).
  23347. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  23348. * 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.
  23349. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  23350. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  23351. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  23352. */
  23353. Mesh.CreateIcoSphere = function (name, options, scene) {
  23354. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  23355. };
  23356. /**
  23357. * Creates a decal mesh.
  23358. * Please consider using the same method from the MeshBuilder class instead.
  23359. * 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.
  23360. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  23361. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  23362. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  23363. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  23364. */
  23365. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  23366. var options = {
  23367. position: position,
  23368. normal: normal,
  23369. size: size,
  23370. angle: angle
  23371. };
  23372. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  23373. };
  23374. // Skeletons
  23375. /**
  23376. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23377. */
  23378. Mesh.prototype.setPositionsForCPUSkinning = function () {
  23379. var source;
  23380. if (!this._sourcePositions) {
  23381. source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23382. this._sourcePositions = new Float32Array(source);
  23383. if (!this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable()) {
  23384. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  23385. }
  23386. }
  23387. return this._sourcePositions;
  23388. };
  23389. /**
  23390. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  23391. */
  23392. Mesh.prototype.setNormalsForCPUSkinning = function () {
  23393. var source;
  23394. if (!this._sourceNormals) {
  23395. source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23396. this._sourceNormals = new Float32Array(source);
  23397. if (!this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable()) {
  23398. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  23399. }
  23400. }
  23401. return this._sourceNormals;
  23402. };
  23403. /**
  23404. * Updates the vertex buffer by applying transformation from the bones.
  23405. * Returns the Mesh.
  23406. *
  23407. * @param {skeleton} skeleton to apply
  23408. */
  23409. Mesh.prototype.applySkeleton = function (skeleton) {
  23410. if (!this.geometry) {
  23411. return this;
  23412. }
  23413. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  23414. return this;
  23415. }
  23416. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  23417. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  23418. return this;
  23419. }
  23420. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  23421. return this;
  23422. }
  23423. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  23424. return this;
  23425. }
  23426. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  23427. return this;
  23428. }
  23429. if (!this._sourcePositions) {
  23430. var submeshes = this.subMeshes.slice();
  23431. this.setPositionsForCPUSkinning();
  23432. this.subMeshes = submeshes;
  23433. }
  23434. if (!this._sourceNormals) {
  23435. this.setNormalsForCPUSkinning();
  23436. }
  23437. // positionsData checks for not being Float32Array will only pass at most once
  23438. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23439. if (!(positionsData instanceof Float32Array)) {
  23440. positionsData = new Float32Array(positionsData);
  23441. }
  23442. // normalsData checks for not being Float32Array will only pass at most once
  23443. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  23444. if (!(normalsData instanceof Float32Array)) {
  23445. normalsData = new Float32Array(normalsData);
  23446. }
  23447. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  23448. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  23449. var needExtras = this.numBoneInfluencers > 4;
  23450. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  23451. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  23452. var skeletonMatrices = skeleton.getTransformMatrices(this);
  23453. var tempVector3 = BABYLON.Vector3.Zero();
  23454. var finalMatrix = new BABYLON.Matrix();
  23455. var tempMatrix = new BABYLON.Matrix();
  23456. var matWeightIdx = 0;
  23457. var inf;
  23458. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  23459. var weight;
  23460. for (inf = 0; inf < 4; inf++) {
  23461. weight = matricesWeightsData[matWeightIdx + inf];
  23462. if (weight > 0) {
  23463. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23464. finalMatrix.addToSelf(tempMatrix);
  23465. }
  23466. else
  23467. break;
  23468. }
  23469. if (needExtras) {
  23470. for (inf = 0; inf < 4; inf++) {
  23471. weight = matricesWeightsExtraData[matWeightIdx + inf];
  23472. if (weight > 0) {
  23473. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, matricesIndicesExtraData[matWeightIdx + inf] * 16, weight, tempMatrix);
  23474. finalMatrix.addToSelf(tempMatrix);
  23475. }
  23476. else
  23477. break;
  23478. }
  23479. }
  23480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  23481. tempVector3.toArray(positionsData, index);
  23482. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  23483. tempVector3.toArray(normalsData, index);
  23484. finalMatrix.reset();
  23485. }
  23486. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  23487. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  23488. return this;
  23489. };
  23490. // Tools
  23491. /**
  23492. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  23493. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  23494. */
  23495. Mesh.MinMax = function (meshes) {
  23496. var minVector = null;
  23497. var maxVector = null;
  23498. meshes.forEach(function (mesh, index, array) {
  23499. var boundingBox = mesh.getBoundingInfo().boundingBox;
  23500. if (!minVector) {
  23501. minVector = boundingBox.minimumWorld;
  23502. maxVector = boundingBox.maximumWorld;
  23503. }
  23504. else {
  23505. minVector.MinimizeInPlace(boundingBox.minimumWorld);
  23506. maxVector.MaximizeInPlace(boundingBox.maximumWorld);
  23507. }
  23508. });
  23509. return {
  23510. min: minVector,
  23511. max: maxVector
  23512. };
  23513. };
  23514. /**
  23515. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  23516. */
  23517. Mesh.Center = function (meshesOrMinMaxVector) {
  23518. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? BABYLON.Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  23519. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  23520. };
  23521. /**
  23522. * Merge the array of meshes into a single mesh for performance reasons.
  23523. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  23524. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  23525. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  23526. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  23527. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  23528. */
  23529. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  23530. if (disposeSource === void 0) { disposeSource = true; }
  23531. var index;
  23532. if (!allow32BitsIndices) {
  23533. var totalVertices = 0;
  23534. // Counting vertices
  23535. for (index = 0; index < meshes.length; index++) {
  23536. if (meshes[index]) {
  23537. totalVertices += meshes[index].getTotalVertices();
  23538. if (totalVertices > 65536) {
  23539. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  23540. return null;
  23541. }
  23542. }
  23543. }
  23544. }
  23545. // Merge
  23546. var vertexData;
  23547. var otherVertexData;
  23548. var indiceArray = new Array();
  23549. var source;
  23550. for (index = 0; index < meshes.length; index++) {
  23551. if (meshes[index]) {
  23552. meshes[index].computeWorldMatrix(true);
  23553. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  23554. otherVertexData.transform(meshes[index].getWorldMatrix());
  23555. if (vertexData) {
  23556. vertexData.merge(otherVertexData);
  23557. }
  23558. else {
  23559. vertexData = otherVertexData;
  23560. source = meshes[index];
  23561. }
  23562. if (subdivideWithSubMeshes) {
  23563. indiceArray.push(meshes[index].getTotalIndices());
  23564. }
  23565. }
  23566. }
  23567. if (!meshSubclass) {
  23568. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  23569. }
  23570. vertexData.applyToMesh(meshSubclass);
  23571. // Setting properties
  23572. meshSubclass.material = source.material;
  23573. meshSubclass.checkCollisions = source.checkCollisions;
  23574. // Cleaning
  23575. if (disposeSource) {
  23576. for (index = 0; index < meshes.length; index++) {
  23577. if (meshes[index]) {
  23578. meshes[index].dispose();
  23579. }
  23580. }
  23581. }
  23582. // Subdivide
  23583. if (subdivideWithSubMeshes) {
  23584. //-- Suppresions du submesh global
  23585. meshSubclass.releaseSubMeshes();
  23586. index = 0;
  23587. var offset = 0;
  23588. //-- aplique la subdivision en fonction du tableau d'indices
  23589. while (index < indiceArray.length) {
  23590. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  23591. offset += indiceArray[index];
  23592. index++;
  23593. }
  23594. }
  23595. return meshSubclass;
  23596. };
  23597. // Consts
  23598. Mesh._FRONTSIDE = 0;
  23599. Mesh._BACKSIDE = 1;
  23600. Mesh._DOUBLESIDE = 2;
  23601. Mesh._DEFAULTSIDE = 0;
  23602. Mesh._NO_CAP = 0;
  23603. Mesh._CAP_START = 1;
  23604. Mesh._CAP_END = 2;
  23605. Mesh._CAP_ALL = 3;
  23606. return Mesh;
  23607. }(BABYLON.AbstractMesh));
  23608. BABYLON.Mesh = Mesh;
  23609. })(BABYLON || (BABYLON = {}));
  23610. //# sourceMappingURL=babylon.mesh.js.map
  23611. var BABYLON;
  23612. (function (BABYLON) {
  23613. var BaseSubMesh = (function () {
  23614. function BaseSubMesh() {
  23615. }
  23616. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  23617. get: function () {
  23618. return this._materialEffect;
  23619. },
  23620. enumerable: true,
  23621. configurable: true
  23622. });
  23623. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  23624. if (this._materialEffect === effect) {
  23625. if (!effect) {
  23626. this._materialDefines = undefined;
  23627. }
  23628. return;
  23629. }
  23630. this._materialDefines = defines;
  23631. this._materialEffect = effect;
  23632. };
  23633. return BaseSubMesh;
  23634. }());
  23635. BABYLON.BaseSubMesh = BaseSubMesh;
  23636. var SubMesh = (function (_super) {
  23637. __extends(SubMesh, _super);
  23638. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  23639. if (createBoundingBox === void 0) { createBoundingBox = true; }
  23640. var _this = _super.call(this) || this;
  23641. _this.materialIndex = materialIndex;
  23642. _this.verticesStart = verticesStart;
  23643. _this.verticesCount = verticesCount;
  23644. _this.indexStart = indexStart;
  23645. _this.indexCount = indexCount;
  23646. _this._renderId = 0;
  23647. _this._mesh = mesh;
  23648. _this._renderingMesh = renderingMesh || mesh;
  23649. mesh.subMeshes.push(_this);
  23650. _this._trianglePlanes = [];
  23651. _this._id = mesh.subMeshes.length - 1;
  23652. if (createBoundingBox) {
  23653. _this.refreshBoundingInfo();
  23654. mesh.computeWorldMatrix(true);
  23655. }
  23656. return _this;
  23657. }
  23658. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  23659. get: function () {
  23660. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  23661. },
  23662. enumerable: true,
  23663. configurable: true
  23664. });
  23665. /**
  23666. * Returns the submesh BoudingInfo object.
  23667. */
  23668. SubMesh.prototype.getBoundingInfo = function () {
  23669. if (this.IsGlobal) {
  23670. return this._mesh.getBoundingInfo();
  23671. }
  23672. return this._boundingInfo;
  23673. };
  23674. /**
  23675. * Sets the submesh BoundingInfo.
  23676. * Return the SubMesh.
  23677. */
  23678. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  23679. this._boundingInfo = boundingInfo;
  23680. return this;
  23681. };
  23682. /**
  23683. * Returns the mesh of the current submesh.
  23684. */
  23685. SubMesh.prototype.getMesh = function () {
  23686. return this._mesh;
  23687. };
  23688. /**
  23689. * Returns the rendering mesh of the submesh.
  23690. */
  23691. SubMesh.prototype.getRenderingMesh = function () {
  23692. return this._renderingMesh;
  23693. };
  23694. /**
  23695. * Returns the submesh material.
  23696. */
  23697. SubMesh.prototype.getMaterial = function () {
  23698. var rootMaterial = this._renderingMesh.material;
  23699. if (rootMaterial && rootMaterial.getSubMaterial) {
  23700. var multiMaterial = rootMaterial;
  23701. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  23702. if (this._currentMaterial !== effectiveMaterial) {
  23703. this._currentMaterial = effectiveMaterial;
  23704. this._materialDefines = undefined;
  23705. }
  23706. return effectiveMaterial;
  23707. }
  23708. if (!rootMaterial) {
  23709. return this._mesh.getScene().defaultMaterial;
  23710. }
  23711. return rootMaterial;
  23712. };
  23713. // Methods
  23714. /**
  23715. * Sets a new updated BoundingInfo object to the submesh.
  23716. * Returns the SubMesh.
  23717. */
  23718. SubMesh.prototype.refreshBoundingInfo = function () {
  23719. this._lastColliderWorldVertices = null;
  23720. if (this.IsGlobal) {
  23721. return;
  23722. }
  23723. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  23724. if (!data) {
  23725. this._boundingInfo = this._mesh._boundingInfo;
  23726. return;
  23727. }
  23728. var indices = this._renderingMesh.getIndices();
  23729. var extend;
  23730. //is this the only submesh?
  23731. if (this.indexStart === 0 && this.indexCount === indices.length) {
  23732. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  23733. extend = { minimum: this._renderingMesh.getBoundingInfo().minimum.clone(), maximum: this._renderingMesh.getBoundingInfo().maximum.clone() };
  23734. }
  23735. else {
  23736. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  23737. }
  23738. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  23739. return this;
  23740. };
  23741. SubMesh.prototype._checkCollision = function (collider) {
  23742. return this.getBoundingInfo()._checkCollision(collider);
  23743. };
  23744. /**
  23745. * Updates the submesh BoundingInfo.
  23746. * Returns the Submesh.
  23747. */
  23748. SubMesh.prototype.updateBoundingInfo = function (world) {
  23749. if (!this.getBoundingInfo()) {
  23750. this.refreshBoundingInfo();
  23751. }
  23752. this.getBoundingInfo().update(world);
  23753. return this;
  23754. };
  23755. /**
  23756. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  23757. * Boolean returned.
  23758. */
  23759. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  23760. return this.getBoundingInfo().isInFrustum(frustumPlanes);
  23761. };
  23762. /**
  23763. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  23764. * Boolean returned.
  23765. */
  23766. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  23767. return this.getBoundingInfo().isCompletelyInFrustum(frustumPlanes);
  23768. };
  23769. /**
  23770. * Renders the submesh.
  23771. * Returns it.
  23772. */
  23773. SubMesh.prototype.render = function (enableAlphaMode) {
  23774. this._renderingMesh.render(this, enableAlphaMode);
  23775. return this;
  23776. };
  23777. /**
  23778. * Returns a new Index Buffer.
  23779. * Type returned : WebGLBuffer.
  23780. */
  23781. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  23782. if (!this._linesIndexBuffer) {
  23783. var linesIndices = [];
  23784. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23785. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  23786. }
  23787. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  23788. this.linesIndexCount = linesIndices.length;
  23789. }
  23790. return this._linesIndexBuffer;
  23791. };
  23792. /**
  23793. * True is the passed Ray intersects the submesh bounding box.
  23794. * Boolean returned.
  23795. */
  23796. SubMesh.prototype.canIntersects = function (ray) {
  23797. return ray.intersectsBox(this.getBoundingInfo().boundingBox);
  23798. };
  23799. /**
  23800. * Returns an object IntersectionInfo.
  23801. */
  23802. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  23803. var intersectInfo = null;
  23804. // LineMesh first as it's also a Mesh...
  23805. if (this._mesh instanceof BABYLON.LinesMesh) {
  23806. var lineMesh = this._mesh;
  23807. // Line test
  23808. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  23809. var p0 = positions[indices[index]];
  23810. var p1 = positions[indices[index + 1]];
  23811. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  23812. if (length < 0) {
  23813. continue;
  23814. }
  23815. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  23816. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  23817. if (fastCheck) {
  23818. break;
  23819. }
  23820. }
  23821. }
  23822. }
  23823. else {
  23824. // Triangles test
  23825. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  23826. var p0 = positions[indices[index]];
  23827. var p1 = positions[indices[index + 1]];
  23828. var p2 = positions[indices[index + 2]];
  23829. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  23830. if (currentIntersectInfo) {
  23831. if (currentIntersectInfo.distance < 0) {
  23832. continue;
  23833. }
  23834. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  23835. intersectInfo = currentIntersectInfo;
  23836. intersectInfo.faceId = index / 3;
  23837. if (fastCheck) {
  23838. break;
  23839. }
  23840. }
  23841. }
  23842. }
  23843. }
  23844. return intersectInfo;
  23845. };
  23846. SubMesh.prototype._rebuild = function () {
  23847. if (this._linesIndexBuffer) {
  23848. this._linesIndexBuffer = null;
  23849. }
  23850. };
  23851. // Clone
  23852. /**
  23853. * Creates a new Submesh from the passed Mesh.
  23854. */
  23855. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  23856. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  23857. if (!this.IsGlobal) {
  23858. result._boundingInfo = new BABYLON.BoundingInfo(this.getBoundingInfo().minimum, this.getBoundingInfo().maximum);
  23859. }
  23860. return result;
  23861. };
  23862. // Dispose
  23863. /**
  23864. * Disposes the Submesh.
  23865. * Returns nothing.
  23866. */
  23867. SubMesh.prototype.dispose = function () {
  23868. if (this._linesIndexBuffer) {
  23869. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  23870. this._linesIndexBuffer = null;
  23871. }
  23872. // Remove from mesh
  23873. var index = this._mesh.subMeshes.indexOf(this);
  23874. this._mesh.subMeshes.splice(index, 1);
  23875. };
  23876. // Statics
  23877. /**
  23878. * Creates a new Submesh from the passed parameters :
  23879. * - materialIndex (integer) : the index of the main mesh material.
  23880. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  23881. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  23882. * - mesh (Mesh) : the main mesh to create the submesh from.
  23883. * - renderingMesh (optional Mesh) : rendering mesh.
  23884. */
  23885. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  23886. var minVertexIndex = Number.MAX_VALUE;
  23887. var maxVertexIndex = -Number.MAX_VALUE;
  23888. renderingMesh = renderingMesh || mesh;
  23889. var indices = renderingMesh.getIndices();
  23890. for (var index = startIndex; index < startIndex + indexCount; index++) {
  23891. var vertexIndex = indices[index];
  23892. if (vertexIndex < minVertexIndex)
  23893. minVertexIndex = vertexIndex;
  23894. if (vertexIndex > maxVertexIndex)
  23895. maxVertexIndex = vertexIndex;
  23896. }
  23897. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  23898. };
  23899. return SubMesh;
  23900. }(BaseSubMesh));
  23901. BABYLON.SubMesh = SubMesh;
  23902. })(BABYLON || (BABYLON = {}));
  23903. //# sourceMappingURL=babylon.subMesh.js.map
  23904. var BABYLON;
  23905. (function (BABYLON) {
  23906. var EffectFallbacks = (function () {
  23907. function EffectFallbacks() {
  23908. this._defines = {};
  23909. this._currentRank = 32;
  23910. this._maxRank = -1;
  23911. }
  23912. EffectFallbacks.prototype.unBindMesh = function () {
  23913. this._mesh = null;
  23914. };
  23915. EffectFallbacks.prototype.addFallback = function (rank, define) {
  23916. if (!this._defines[rank]) {
  23917. if (rank < this._currentRank) {
  23918. this._currentRank = rank;
  23919. }
  23920. if (rank > this._maxRank) {
  23921. this._maxRank = rank;
  23922. }
  23923. this._defines[rank] = new Array();
  23924. }
  23925. this._defines[rank].push(define);
  23926. };
  23927. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  23928. this._meshRank = rank;
  23929. this._mesh = mesh;
  23930. if (rank < this._currentRank) {
  23931. this._currentRank = rank;
  23932. }
  23933. if (rank > this._maxRank) {
  23934. this._maxRank = rank;
  23935. }
  23936. };
  23937. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  23938. get: function () {
  23939. return this._currentRank <= this._maxRank;
  23940. },
  23941. enumerable: true,
  23942. configurable: true
  23943. });
  23944. EffectFallbacks.prototype.reduce = function (currentDefines) {
  23945. // First we try to switch to CPU skinning
  23946. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0) {
  23947. this._mesh.computeBonesUsingShaders = false;
  23948. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  23949. BABYLON.Tools.Log("Falling back to CPU skinning for " + this._mesh.name);
  23950. var scene = this._mesh.getScene();
  23951. for (var index = 0; index < scene.meshes.length; index++) {
  23952. var otherMesh = scene.meshes[index];
  23953. if (otherMesh.material === this._mesh.material && otherMesh.computeBonesUsingShaders && otherMesh.numBoneInfluencers > 0) {
  23954. otherMesh.computeBonesUsingShaders = false;
  23955. }
  23956. }
  23957. }
  23958. else {
  23959. var currentFallbacks = this._defines[this._currentRank];
  23960. if (currentFallbacks) {
  23961. for (var index = 0; index < currentFallbacks.length; index++) {
  23962. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  23963. }
  23964. }
  23965. this._currentRank++;
  23966. }
  23967. return currentDefines;
  23968. };
  23969. return EffectFallbacks;
  23970. }());
  23971. BABYLON.EffectFallbacks = EffectFallbacks;
  23972. var EffectCreationOptions = (function () {
  23973. function EffectCreationOptions() {
  23974. }
  23975. return EffectCreationOptions;
  23976. }());
  23977. BABYLON.EffectCreationOptions = EffectCreationOptions;
  23978. var Effect = (function () {
  23979. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  23980. var _this = this;
  23981. this.uniqueId = 0;
  23982. this.onCompileObservable = new BABYLON.Observable();
  23983. this.onErrorObservable = new BABYLON.Observable();
  23984. this.onBindObservable = new BABYLON.Observable();
  23985. this._uniformBuffersNames = {};
  23986. this._isReady = false;
  23987. this._compilationError = "";
  23988. this.name = baseName;
  23989. if (attributesNamesOrOptions.attributes) {
  23990. var options = attributesNamesOrOptions;
  23991. this._engine = uniformsNamesOrEngine;
  23992. this._attributesNames = options.attributes;
  23993. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  23994. this._samplers = options.samplers;
  23995. this.defines = options.defines;
  23996. this.onError = options.onError;
  23997. this.onCompiled = options.onCompiled;
  23998. this._fallbacks = options.fallbacks;
  23999. this._indexParameters = options.indexParameters;
  24000. if (options.uniformBuffersNames) {
  24001. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  24002. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  24003. }
  24004. }
  24005. }
  24006. else {
  24007. this._engine = engine;
  24008. this.defines = defines;
  24009. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  24010. this._samplers = samplers;
  24011. this._attributesNames = attributesNamesOrOptions;
  24012. this.onError = onError;
  24013. this.onCompiled = onCompiled;
  24014. this._indexParameters = indexParameters;
  24015. this._fallbacks = fallbacks;
  24016. }
  24017. this.uniqueId = Effect._uniqueIdSeed++;
  24018. var vertexSource;
  24019. var fragmentSource;
  24020. if (baseName.vertexElement) {
  24021. vertexSource = document.getElementById(baseName.vertexElement);
  24022. if (!vertexSource) {
  24023. vertexSource = baseName.vertexElement;
  24024. }
  24025. }
  24026. else {
  24027. vertexSource = baseName.vertex || baseName;
  24028. }
  24029. if (baseName.fragmentElement) {
  24030. fragmentSource = document.getElementById(baseName.fragmentElement);
  24031. if (!fragmentSource) {
  24032. fragmentSource = baseName.fragmentElement;
  24033. }
  24034. }
  24035. else {
  24036. fragmentSource = baseName.fragment || baseName;
  24037. }
  24038. this._loadVertexShader(vertexSource, function (vertexCode) {
  24039. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  24040. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  24041. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  24042. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  24043. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  24044. if (baseName) {
  24045. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + baseName + "\n" + migratedVertexCode;
  24046. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + baseName + "\n" + migratedFragmentCode;
  24047. }
  24048. else {
  24049. _this._vertexSourceCode = migratedVertexCode;
  24050. _this._fragmentSourceCode = migratedFragmentCode;
  24051. }
  24052. _this._prepareEffect();
  24053. });
  24054. });
  24055. });
  24056. });
  24057. });
  24058. });
  24059. }
  24060. Object.defineProperty(Effect.prototype, "key", {
  24061. get: function () {
  24062. return this._key;
  24063. },
  24064. enumerable: true,
  24065. configurable: true
  24066. });
  24067. // Properties
  24068. Effect.prototype.isReady = function () {
  24069. return this._isReady;
  24070. };
  24071. Effect.prototype.getEngine = function () {
  24072. return this._engine;
  24073. };
  24074. Effect.prototype.getProgram = function () {
  24075. return this._program;
  24076. };
  24077. Effect.prototype.getAttributesNames = function () {
  24078. return this._attributesNames;
  24079. };
  24080. Effect.prototype.getAttributeLocation = function (index) {
  24081. return this._attributes[index];
  24082. };
  24083. Effect.prototype.getAttributeLocationByName = function (name) {
  24084. var index = this._attributesNames.indexOf(name);
  24085. return this._attributes[index];
  24086. };
  24087. Effect.prototype.getAttributesCount = function () {
  24088. return this._attributes.length;
  24089. };
  24090. Effect.prototype.getUniformIndex = function (uniformName) {
  24091. return this._uniformsNames.indexOf(uniformName);
  24092. };
  24093. Effect.prototype.getUniform = function (uniformName) {
  24094. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  24095. };
  24096. Effect.prototype.getSamplers = function () {
  24097. return this._samplers;
  24098. };
  24099. Effect.prototype.getCompilationError = function () {
  24100. return this._compilationError;
  24101. };
  24102. // Methods
  24103. Effect.prototype.executeWhenCompiled = function (func) {
  24104. if (this.isReady()) {
  24105. func(this);
  24106. return;
  24107. }
  24108. this.onCompileObservable.add(function (effect) {
  24109. func(effect);
  24110. });
  24111. };
  24112. Effect.prototype._loadVertexShader = function (vertex, callback) {
  24113. // DOM element ?
  24114. if (vertex instanceof HTMLElement) {
  24115. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  24116. callback(vertexCode);
  24117. return;
  24118. }
  24119. // Base64 encoded ?
  24120. if (vertex.substr(0, 7) === "base64:") {
  24121. var vertexBinary = window.atob(vertex.substr(7));
  24122. callback(vertexBinary);
  24123. return;
  24124. }
  24125. // Is in local store ?
  24126. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  24127. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  24128. return;
  24129. }
  24130. var vertexShaderUrl;
  24131. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  24132. vertexShaderUrl = vertex;
  24133. }
  24134. else {
  24135. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  24136. }
  24137. // Vertex shader
  24138. BABYLON.Tools.LoadFile(vertexShaderUrl + ".vertex.fx", callback);
  24139. };
  24140. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  24141. // DOM element ?
  24142. if (fragment instanceof HTMLElement) {
  24143. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  24144. callback(fragmentCode);
  24145. return;
  24146. }
  24147. // Base64 encoded ?
  24148. if (fragment.substr(0, 7) === "base64:") {
  24149. var fragmentBinary = window.atob(fragment.substr(7));
  24150. callback(fragmentBinary);
  24151. return;
  24152. }
  24153. // Is in local store ?
  24154. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  24155. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  24156. return;
  24157. }
  24158. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  24159. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  24160. return;
  24161. }
  24162. var fragmentShaderUrl;
  24163. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  24164. fragmentShaderUrl = fragment;
  24165. }
  24166. else {
  24167. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  24168. }
  24169. // Fragment shader
  24170. BABYLON.Tools.LoadFile(fragmentShaderUrl + ".fragment.fx", callback);
  24171. };
  24172. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  24173. // Rebuild shaders source code
  24174. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n" : "";
  24175. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  24176. vertexCode = prefix + vertexCode;
  24177. fragmentCode = prefix + fragmentCode;
  24178. // Number lines of shaders source code
  24179. var i = 2;
  24180. var regex = /\n/gm;
  24181. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24182. i = 2;
  24183. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  24184. // Dump shaders name and formatted source code
  24185. if (this.name.vertexElement) {
  24186. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  24187. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  24188. }
  24189. else if (this.name.vertex) {
  24190. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  24191. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  24192. }
  24193. else {
  24194. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  24195. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  24196. }
  24197. };
  24198. ;
  24199. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  24200. var preparedSourceCode = this._processPrecision(sourceCode);
  24201. if (this._engine.webGLVersion == 1) {
  24202. callback(preparedSourceCode);
  24203. return;
  24204. }
  24205. // Already converted
  24206. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  24207. callback(preparedSourceCode.replace("#version 300 es", ""));
  24208. return;
  24209. }
  24210. // Remove extensions
  24211. // #extension GL_OES_standard_derivatives : enable
  24212. // #extension GL_EXT_shader_texture_lod : enable
  24213. // #extension GL_EXT_frag_depth : enable
  24214. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth).+enable/g;
  24215. var result = preparedSourceCode.replace(regex, "");
  24216. // Migrate to GLSL v300
  24217. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  24218. result = result.replace(/attribute[ \t]/g, "in ");
  24219. result = result.replace(/[ \t]attribute/g, " in");
  24220. if (isFragment) {
  24221. result = result.replace(/texture2DLodEXT\(/g, "textureLod(");
  24222. result = result.replace(/textureCubeLodEXT\(/g, "textureLod(");
  24223. result = result.replace(/texture2D\(/g, "texture(");
  24224. result = result.replace(/textureCube\(/g, "texture(");
  24225. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  24226. result = result.replace(/gl_FragColor/g, "glFragColor");
  24227. result = result.replace(/void\s+?main\(/g, "out vec4 glFragColor;\nvoid main(");
  24228. }
  24229. callback(result);
  24230. };
  24231. Effect.prototype._processIncludes = function (sourceCode, callback) {
  24232. var _this = this;
  24233. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  24234. var match = regex.exec(sourceCode);
  24235. var returnValue = new String(sourceCode);
  24236. while (match != null) {
  24237. var includeFile = match[1];
  24238. // Uniform declaration
  24239. if (includeFile.indexOf("__decl__") !== -1) {
  24240. includeFile = includeFile.replace(/__decl__/, "");
  24241. if (this._engine.webGLVersion != 1) {
  24242. includeFile = includeFile.replace(/Vertex/, "Ubo");
  24243. includeFile = includeFile.replace(/Fragment/, "Ubo");
  24244. }
  24245. includeFile = includeFile + "Declaration";
  24246. }
  24247. if (Effect.IncludesShadersStore[includeFile]) {
  24248. // Substitution
  24249. var includeContent = Effect.IncludesShadersStore[includeFile];
  24250. if (match[2]) {
  24251. var splits = match[3].split(",");
  24252. for (var index = 0; index < splits.length; index += 2) {
  24253. var source = new RegExp(splits[index], "g");
  24254. var dest = splits[index + 1];
  24255. includeContent = includeContent.replace(source, dest);
  24256. }
  24257. }
  24258. if (match[4]) {
  24259. var indexString = match[5];
  24260. if (indexString.indexOf("..") !== -1) {
  24261. var indexSplits = indexString.split("..");
  24262. var minIndex = parseInt(indexSplits[0]);
  24263. var maxIndex = parseInt(indexSplits[1]);
  24264. var sourceIncludeContent = includeContent.slice(0);
  24265. includeContent = "";
  24266. if (isNaN(maxIndex)) {
  24267. maxIndex = this._indexParameters[indexSplits[1]];
  24268. }
  24269. for (var i = minIndex; i < maxIndex; i++) {
  24270. if (this._engine.webGLVersion === 1) {
  24271. // Ubo replacement
  24272. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24273. return p1 + "{X}";
  24274. });
  24275. }
  24276. includeContent += sourceIncludeContent.replace(/\{X\}/g, i) + "\n";
  24277. }
  24278. }
  24279. else {
  24280. if (this._engine.webGLVersion === 1) {
  24281. // Ubo replacement
  24282. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  24283. return p1 + "{X}";
  24284. });
  24285. }
  24286. includeContent = includeContent.replace(/\{X\}/g, indexString);
  24287. }
  24288. }
  24289. // Replace
  24290. returnValue = returnValue.replace(match[0], includeContent);
  24291. }
  24292. else {
  24293. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  24294. BABYLON.Tools.LoadFile(includeShaderUrl, function (fileContent) {
  24295. Effect.IncludesShadersStore[includeFile] = fileContent;
  24296. _this._processIncludes(returnValue, callback);
  24297. });
  24298. return;
  24299. }
  24300. match = regex.exec(sourceCode);
  24301. }
  24302. callback(returnValue);
  24303. };
  24304. Effect.prototype._processPrecision = function (source) {
  24305. if (source.indexOf("precision highp float") === -1) {
  24306. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24307. source = "precision mediump float;\n" + source;
  24308. }
  24309. else {
  24310. source = "precision highp float;\n" + source;
  24311. }
  24312. }
  24313. else {
  24314. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  24315. source = source.replace("precision highp float", "precision mediump float");
  24316. }
  24317. }
  24318. return source;
  24319. };
  24320. Effect.prototype._prepareEffect = function () {
  24321. var attributesNames = this._attributesNames;
  24322. var defines = this.defines;
  24323. var fallbacks = this._fallbacks;
  24324. this._valueCache = {};
  24325. try {
  24326. var engine = this._engine;
  24327. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24328. if (engine.webGLVersion > 1) {
  24329. for (var name in this._uniformBuffersNames) {
  24330. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  24331. }
  24332. }
  24333. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  24334. this._attributes = engine.getAttributes(this._program, attributesNames);
  24335. var index;
  24336. for (index = 0; index < this._samplers.length; index++) {
  24337. var sampler = this.getUniform(this._samplers[index]);
  24338. if (sampler == null) {
  24339. this._samplers.splice(index, 1);
  24340. index--;
  24341. }
  24342. }
  24343. engine.bindSamplers(this);
  24344. this._compilationError = "";
  24345. this._isReady = true;
  24346. if (this.onCompiled) {
  24347. this.onCompiled(this);
  24348. }
  24349. this.onCompileObservable.notifyObservers(this);
  24350. this.onCompileObservable.clear();
  24351. // Unbind mesh reference in fallbacks
  24352. if (this._fallbacks) {
  24353. this._fallbacks.unBindMesh();
  24354. }
  24355. }
  24356. catch (e) {
  24357. this._compilationError = e.message;
  24358. // Let's go through fallbacks then
  24359. BABYLON.Tools.Error("Unable to compile effect:");
  24360. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  24361. return " " + uniform;
  24362. }));
  24363. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  24364. return " " + attribute;
  24365. }));
  24366. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  24367. BABYLON.Tools.Error("Error: " + this._compilationError);
  24368. if (fallbacks && fallbacks.isMoreFallbacks) {
  24369. BABYLON.Tools.Error("Trying next fallback.");
  24370. this.defines = fallbacks.reduce(this.defines);
  24371. this._prepareEffect();
  24372. }
  24373. else {
  24374. if (this.onError) {
  24375. this.onError(this, this._compilationError);
  24376. }
  24377. this.onErrorObservable.notifyObservers(this);
  24378. this.onErrorObservable.clear();
  24379. // Unbind mesh reference in fallbacks
  24380. if (this._fallbacks) {
  24381. this._fallbacks.unBindMesh();
  24382. }
  24383. }
  24384. }
  24385. };
  24386. Object.defineProperty(Effect.prototype, "isSupported", {
  24387. get: function () {
  24388. return this._compilationError === "";
  24389. },
  24390. enumerable: true,
  24391. configurable: true
  24392. });
  24393. Effect.prototype._bindTexture = function (channel, texture) {
  24394. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  24395. };
  24396. Effect.prototype.setTexture = function (channel, texture) {
  24397. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  24398. };
  24399. Effect.prototype.setTextureArray = function (channel, textures) {
  24400. if (this._samplers.indexOf(channel + "Ex") === -1) {
  24401. var initialPos = this._samplers.indexOf(channel);
  24402. for (var index = 1; index < textures.length; index++) {
  24403. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  24404. }
  24405. }
  24406. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  24407. };
  24408. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  24409. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  24410. };
  24411. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  24412. var cache = this._valueCache[uniformName];
  24413. var flag = matrix.updateFlag;
  24414. if (cache !== undefined && cache === flag) {
  24415. return false;
  24416. }
  24417. this._valueCache[uniformName] = flag;
  24418. return true;
  24419. };
  24420. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  24421. var cache = this._valueCache[uniformName];
  24422. if (!cache) {
  24423. cache = [x, y];
  24424. this._valueCache[uniformName] = cache;
  24425. return true;
  24426. }
  24427. var changed = false;
  24428. if (cache[0] !== x) {
  24429. cache[0] = x;
  24430. changed = true;
  24431. }
  24432. if (cache[1] !== y) {
  24433. cache[1] = y;
  24434. changed = true;
  24435. }
  24436. return changed;
  24437. };
  24438. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  24439. var cache = this._valueCache[uniformName];
  24440. if (!cache) {
  24441. cache = [x, y, z];
  24442. this._valueCache[uniformName] = cache;
  24443. return true;
  24444. }
  24445. var changed = false;
  24446. if (cache[0] !== x) {
  24447. cache[0] = x;
  24448. changed = true;
  24449. }
  24450. if (cache[1] !== y) {
  24451. cache[1] = y;
  24452. changed = true;
  24453. }
  24454. if (cache[2] !== z) {
  24455. cache[2] = z;
  24456. changed = true;
  24457. }
  24458. return changed;
  24459. };
  24460. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  24461. var cache = this._valueCache[uniformName];
  24462. if (!cache) {
  24463. cache = [x, y, z, w];
  24464. this._valueCache[uniformName] = cache;
  24465. return true;
  24466. }
  24467. var changed = false;
  24468. if (cache[0] !== x) {
  24469. cache[0] = x;
  24470. changed = true;
  24471. }
  24472. if (cache[1] !== y) {
  24473. cache[1] = y;
  24474. changed = true;
  24475. }
  24476. if (cache[2] !== z) {
  24477. cache[2] = z;
  24478. changed = true;
  24479. }
  24480. if (cache[3] !== w) {
  24481. cache[3] = w;
  24482. changed = true;
  24483. }
  24484. return changed;
  24485. };
  24486. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  24487. if (Effect._baseCache[this._uniformBuffersNames[name]] === buffer) {
  24488. return;
  24489. }
  24490. Effect._baseCache[this._uniformBuffersNames[name]] = buffer;
  24491. this._engine.bindUniformBufferBase(buffer, this._uniformBuffersNames[name]);
  24492. };
  24493. Effect.prototype.bindUniformBlock = function (blockName, index) {
  24494. this._engine.bindUniformBlock(this._program, blockName, index);
  24495. };
  24496. Effect.prototype.setIntArray = function (uniformName, array) {
  24497. this._valueCache[uniformName] = null;
  24498. this._engine.setIntArray(this.getUniform(uniformName), array);
  24499. return this;
  24500. };
  24501. Effect.prototype.setIntArray2 = function (uniformName, array) {
  24502. this._valueCache[uniformName] = null;
  24503. this._engine.setIntArray2(this.getUniform(uniformName), array);
  24504. return this;
  24505. };
  24506. Effect.prototype.setIntArray3 = function (uniformName, array) {
  24507. this._valueCache[uniformName] = null;
  24508. this._engine.setIntArray3(this.getUniform(uniformName), array);
  24509. return this;
  24510. };
  24511. Effect.prototype.setIntArray4 = function (uniformName, array) {
  24512. this._valueCache[uniformName] = null;
  24513. this._engine.setIntArray4(this.getUniform(uniformName), array);
  24514. return this;
  24515. };
  24516. Effect.prototype.setFloatArray = function (uniformName, array) {
  24517. this._valueCache[uniformName] = null;
  24518. this._engine.setFloatArray(this.getUniform(uniformName), array);
  24519. return this;
  24520. };
  24521. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  24522. this._valueCache[uniformName] = null;
  24523. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  24524. return this;
  24525. };
  24526. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  24527. this._valueCache[uniformName] = null;
  24528. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  24529. return this;
  24530. };
  24531. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  24532. this._valueCache[uniformName] = null;
  24533. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  24534. return this;
  24535. };
  24536. Effect.prototype.setArray = function (uniformName, array) {
  24537. this._valueCache[uniformName] = null;
  24538. this._engine.setArray(this.getUniform(uniformName), array);
  24539. return this;
  24540. };
  24541. Effect.prototype.setArray2 = function (uniformName, array) {
  24542. this._valueCache[uniformName] = null;
  24543. this._engine.setArray2(this.getUniform(uniformName), array);
  24544. return this;
  24545. };
  24546. Effect.prototype.setArray3 = function (uniformName, array) {
  24547. this._valueCache[uniformName] = null;
  24548. this._engine.setArray3(this.getUniform(uniformName), array);
  24549. return this;
  24550. };
  24551. Effect.prototype.setArray4 = function (uniformName, array) {
  24552. this._valueCache[uniformName] = null;
  24553. this._engine.setArray4(this.getUniform(uniformName), array);
  24554. return this;
  24555. };
  24556. Effect.prototype.setMatrices = function (uniformName, matrices) {
  24557. if (!matrices) {
  24558. return;
  24559. }
  24560. this._valueCache[uniformName] = null;
  24561. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  24562. return this;
  24563. };
  24564. Effect.prototype.setMatrix = function (uniformName, matrix) {
  24565. if (this._cacheMatrix(uniformName, matrix)) {
  24566. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  24567. }
  24568. return this;
  24569. };
  24570. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  24571. this._valueCache[uniformName] = null;
  24572. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  24573. return this;
  24574. };
  24575. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  24576. this._valueCache[uniformName] = null;
  24577. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  24578. return this;
  24579. };
  24580. Effect.prototype.setFloat = function (uniformName, value) {
  24581. var cache = this._valueCache[uniformName];
  24582. if (cache !== undefined && cache === value)
  24583. return this;
  24584. this._valueCache[uniformName] = value;
  24585. this._engine.setFloat(this.getUniform(uniformName), value);
  24586. return this;
  24587. };
  24588. Effect.prototype.setBool = function (uniformName, bool) {
  24589. var cache = this._valueCache[uniformName];
  24590. if (cache !== undefined && cache === bool)
  24591. return this;
  24592. this._valueCache[uniformName] = bool;
  24593. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  24594. return this;
  24595. };
  24596. Effect.prototype.setVector2 = function (uniformName, vector2) {
  24597. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  24598. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  24599. }
  24600. return this;
  24601. };
  24602. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  24603. if (this._cacheFloat2(uniformName, x, y)) {
  24604. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  24605. }
  24606. return this;
  24607. };
  24608. Effect.prototype.setVector3 = function (uniformName, vector3) {
  24609. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  24610. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  24611. }
  24612. return this;
  24613. };
  24614. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  24615. if (this._cacheFloat3(uniformName, x, y, z)) {
  24616. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  24617. }
  24618. return this;
  24619. };
  24620. Effect.prototype.setVector4 = function (uniformName, vector4) {
  24621. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  24622. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  24623. }
  24624. return this;
  24625. };
  24626. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  24627. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  24628. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  24629. }
  24630. return this;
  24631. };
  24632. Effect.prototype.setColor3 = function (uniformName, color3) {
  24633. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  24634. this._engine.setColor3(this.getUniform(uniformName), color3);
  24635. }
  24636. return this;
  24637. };
  24638. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  24639. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  24640. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  24641. }
  24642. return this;
  24643. };
  24644. Effect.ResetCache = function () {
  24645. Effect._baseCache = {};
  24646. };
  24647. Effect._uniqueIdSeed = 0;
  24648. Effect._baseCache = {};
  24649. // Statics
  24650. Effect.ShadersStore = {};
  24651. Effect.IncludesShadersStore = {};
  24652. return Effect;
  24653. }());
  24654. BABYLON.Effect = Effect;
  24655. })(BABYLON || (BABYLON = {}));
  24656. //# sourceMappingURL=babylon.effect.js.map
  24657. var BABYLON;
  24658. (function (BABYLON) {
  24659. var MaterialHelper = (function () {
  24660. function MaterialHelper() {
  24661. }
  24662. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  24663. defines._needUVs = true;
  24664. defines[key] = true;
  24665. if (texture.getTextureMatrix().isIdentity(true)) {
  24666. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  24667. if (texture.coordinatesIndex === 0) {
  24668. defines["MAINUV1"] = true;
  24669. }
  24670. else {
  24671. defines["MAINUV2"] = true;
  24672. }
  24673. }
  24674. else {
  24675. defines[key + "DIRECTUV"] = 0;
  24676. }
  24677. };
  24678. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  24679. var matrix = texture.getTextureMatrix();
  24680. if (!matrix.isIdentity(true)) {
  24681. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  24682. }
  24683. };
  24684. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, defines) {
  24685. if (defines._areMiscDirty) {
  24686. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  24687. defines["POINTSIZE"] = (pointsCloud || scene.forcePointsCloud);
  24688. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  24689. defines["USERIGHTHANDEDSYSTEM"] = scene.useRightHandedSystem;
  24690. }
  24691. };
  24692. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, forceAlphaTest) {
  24693. if (forceAlphaTest === void 0) { forceAlphaTest = false; }
  24694. var changed = false;
  24695. if (defines["CLIPPLANE"] !== (scene.clipPlane !== undefined && scene.clipPlane !== null)) {
  24696. defines["CLIPPLANE"] = !defines["CLIPPLANE"];
  24697. changed = true;
  24698. }
  24699. if (defines["ALPHATEST"] !== (engine.getAlphaTesting() || forceAlphaTest)) {
  24700. defines["ALPHATEST"] = !defines["ALPHATEST"];
  24701. changed = true;
  24702. }
  24703. if (defines["INSTANCES"] !== useInstances) {
  24704. defines["INSTANCES"] = useInstances;
  24705. changed = true;
  24706. }
  24707. if (changed) {
  24708. defines.markAsUnprocessed();
  24709. }
  24710. };
  24711. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets) {
  24712. if (useMorphTargets === void 0) { useMorphTargets = false; }
  24713. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  24714. return false;
  24715. }
  24716. defines._normals = defines._needNormals;
  24717. defines._uvs = defines._needUVs;
  24718. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  24719. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  24720. defines["TANGENT"] = true;
  24721. }
  24722. if (defines._needUVs) {
  24723. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  24724. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  24725. }
  24726. else {
  24727. defines["UV1"] = false;
  24728. defines["UV2"] = false;
  24729. }
  24730. if (useVertexColor) {
  24731. defines["VERTEXCOLOR"] = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  24732. defines["VERTEXALPHA"] = mesh.hasVertexAlpha;
  24733. }
  24734. if (useBones) {
  24735. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  24736. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  24737. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  24738. }
  24739. else {
  24740. defines["NUM_BONE_INFLUENCERS"] = 0;
  24741. defines["BonesPerMesh"] = 0;
  24742. }
  24743. }
  24744. if (useMorphTargets) {
  24745. if (mesh.morphTargetManager) {
  24746. var manager = mesh.morphTargetManager;
  24747. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  24748. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  24749. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  24750. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  24751. }
  24752. else {
  24753. defines["MORPHTARGETS_TANGENT"] = false;
  24754. defines["MORPHTARGETS_NORMAL"] = false;
  24755. defines["MORPHTARGETS"] = false;
  24756. defines["NUM_MORPH_INFLUENCERS"] = 0;
  24757. }
  24758. }
  24759. return true;
  24760. };
  24761. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  24762. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24763. if (disableLighting === void 0) { disableLighting = false; }
  24764. if (!defines._areLightsDirty) {
  24765. return defines._needNormals;
  24766. }
  24767. var lightIndex = 0;
  24768. var needNormals = false;
  24769. var needRebuild = false;
  24770. var lightmapMode = false;
  24771. var shadowEnabled = false;
  24772. var specularEnabled = false;
  24773. if (scene.lightsEnabled && !disableLighting) {
  24774. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24775. var light = _a[_i];
  24776. needNormals = true;
  24777. if (defines["LIGHT" + lightIndex] === undefined) {
  24778. needRebuild = true;
  24779. }
  24780. defines["LIGHT" + lightIndex] = true;
  24781. defines["SPOTLIGHT" + lightIndex] = false;
  24782. defines["HEMILIGHT" + lightIndex] = false;
  24783. defines["POINTLIGHT" + lightIndex] = false;
  24784. defines["DIRLIGHT" + lightIndex] = false;
  24785. var type;
  24786. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  24787. type = "SPOTLIGHT" + lightIndex;
  24788. }
  24789. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  24790. type = "HEMILIGHT" + lightIndex;
  24791. }
  24792. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  24793. type = "POINTLIGHT" + lightIndex;
  24794. }
  24795. else {
  24796. type = "DIRLIGHT" + lightIndex;
  24797. }
  24798. defines[type] = true;
  24799. // Specular
  24800. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  24801. specularEnabled = true;
  24802. }
  24803. // Shadows
  24804. defines["SHADOW" + lightIndex] = false;
  24805. defines["SHADOWPCF" + lightIndex] = false;
  24806. defines["SHADOWESM" + lightIndex] = false;
  24807. defines["SHADOWCUBE" + lightIndex] = false;
  24808. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  24809. var shadowGenerator = light.getShadowGenerator();
  24810. if (shadowGenerator) {
  24811. shadowEnabled = true;
  24812. shadowGenerator.prepareDefines(defines, lightIndex);
  24813. }
  24814. }
  24815. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  24816. lightmapMode = true;
  24817. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  24818. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  24819. }
  24820. else {
  24821. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  24822. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  24823. }
  24824. lightIndex++;
  24825. if (lightIndex === maxSimultaneousLights)
  24826. break;
  24827. }
  24828. }
  24829. defines["SPECULARTERM"] = specularEnabled;
  24830. defines["SHADOWS"] = shadowEnabled;
  24831. // Resetting all other lights if any
  24832. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  24833. if (defines["LIGHT" + index] !== undefined) {
  24834. defines["LIGHT" + index] = false;
  24835. defines["HEMILIGHT" + lightIndex] = false;
  24836. defines["POINTLIGHT" + lightIndex] = false;
  24837. defines["DIRLIGHT" + lightIndex] = false;
  24838. defines["SPOTLIGHT" + lightIndex] = false;
  24839. defines["SHADOW" + lightIndex] = false;
  24840. }
  24841. }
  24842. var caps = scene.getEngine().getCaps();
  24843. if (defines["SHADOWFLOAT"] === undefined) {
  24844. needRebuild = true;
  24845. }
  24846. defines["SHADOWFLOAT"] = shadowEnabled &&
  24847. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  24848. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  24849. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  24850. if (needRebuild) {
  24851. defines.rebuild();
  24852. }
  24853. return needNormals;
  24854. };
  24855. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  24856. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24857. var uniformsList, uniformBuffersList, samplersList, defines;
  24858. if (uniformsListOrOptions.uniformsNames) {
  24859. var options = uniformsListOrOptions;
  24860. uniformsList = options.uniformsNames;
  24861. uniformBuffersList = options.uniformBuffersNames;
  24862. samplersList = options.samplers;
  24863. defines = options.defines;
  24864. maxSimultaneousLights = options.maxSimultaneousLights;
  24865. }
  24866. else {
  24867. uniformsList = uniformsListOrOptions;
  24868. }
  24869. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24870. if (!defines["LIGHT" + lightIndex]) {
  24871. break;
  24872. }
  24873. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  24874. if (uniformBuffersList) {
  24875. uniformBuffersList.push("Light" + lightIndex);
  24876. }
  24877. samplersList.push("shadowSampler" + lightIndex);
  24878. }
  24879. if (defines["NUM_MORPH_INFLUENCERS"]) {
  24880. uniformsList.push("morphTargetInfluences");
  24881. }
  24882. };
  24883. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights) {
  24884. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24885. if (!defines["SHADOWS"]) {
  24886. return;
  24887. }
  24888. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  24889. if (!defines["LIGHT" + lightIndex]) {
  24890. break;
  24891. }
  24892. if (lightIndex > 0) {
  24893. fallbacks.addFallback(lightIndex, "LIGHT" + lightIndex);
  24894. }
  24895. if (defines["SHADOW" + lightIndex]) {
  24896. fallbacks.addFallback(0, "SHADOW" + lightIndex);
  24897. }
  24898. if (defines["SHADOWPCF" + lightIndex]) {
  24899. fallbacks.addFallback(0, "SHADOWPCF" + lightIndex);
  24900. }
  24901. if (defines["SHADOWESM" + lightIndex]) {
  24902. fallbacks.addFallback(0, "SHADOWESM" + lightIndex);
  24903. }
  24904. }
  24905. };
  24906. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  24907. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  24908. if (influencers > 0) {
  24909. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  24910. var manager = mesh.morphTargetManager;
  24911. var normal = manager.supportsNormals && defines["NORMAL"];
  24912. var tangent = manager.supportsTangents && defines["TANGENT"];
  24913. for (var index = 0; index < influencers; index++) {
  24914. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  24915. if (normal) {
  24916. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  24917. }
  24918. if (tangent) {
  24919. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  24920. }
  24921. if (attribs.length > maxAttributesCount) {
  24922. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  24923. }
  24924. }
  24925. }
  24926. };
  24927. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  24928. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  24929. fallbacks.addCPUSkinningFallback(0, mesh);
  24930. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  24931. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  24932. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  24933. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  24934. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  24935. }
  24936. }
  24937. };
  24938. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  24939. if (defines["INSTANCES"]) {
  24940. attribs.push("world0");
  24941. attribs.push("world1");
  24942. attribs.push("world2");
  24943. attribs.push("world3");
  24944. }
  24945. };
  24946. // Bindings
  24947. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  24948. if (light.shadowEnabled && mesh.receiveShadows) {
  24949. var shadowGenerator = light.getShadowGenerator();
  24950. if (shadowGenerator) {
  24951. shadowGenerator.bindShadowLight(lightIndex, effect);
  24952. }
  24953. }
  24954. };
  24955. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  24956. light.transferToEffect(effect, lightIndex + "");
  24957. };
  24958. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  24959. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  24960. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  24961. var lightIndex = 0;
  24962. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  24963. var light = _a[_i];
  24964. var scaledIntensity = light.getScaledIntensity();
  24965. light._uniformBuffer.bindToEffect(effect, "Light" + lightIndex);
  24966. MaterialHelper.BindLightProperties(light, effect, lightIndex);
  24967. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  24968. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, lightIndex + "");
  24969. if (defines["SPECULARTERM"]) {
  24970. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  24971. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], lightIndex + "");
  24972. }
  24973. // Shadows
  24974. if (scene.shadowsEnabled) {
  24975. this.BindLightShadow(light, scene, mesh, lightIndex + "", effect);
  24976. }
  24977. light._uniformBuffer.update();
  24978. lightIndex++;
  24979. if (lightIndex === maxSimultaneousLights)
  24980. break;
  24981. }
  24982. };
  24983. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  24984. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  24985. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  24986. effect.setColor3("vFogColor", scene.fogColor);
  24987. }
  24988. };
  24989. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  24990. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  24991. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  24992. if (matrices) {
  24993. effect.setMatrices("mBones", matrices);
  24994. }
  24995. }
  24996. };
  24997. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  24998. if (!abstractMesh || !abstractMesh.morphTargetManager) {
  24999. return;
  25000. }
  25001. effect.setFloatArray("morphTargetInfluences", abstractMesh.morphTargetManager.influences);
  25002. };
  25003. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  25004. if (defines["LOGARITHMICDEPTH"]) {
  25005. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  25006. }
  25007. };
  25008. MaterialHelper.BindClipPlane = function (effect, scene) {
  25009. if (scene.clipPlane) {
  25010. var clipPlane = scene.clipPlane;
  25011. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  25012. }
  25013. };
  25014. return MaterialHelper;
  25015. }());
  25016. BABYLON.MaterialHelper = MaterialHelper;
  25017. })(BABYLON || (BABYLON = {}));
  25018. //# sourceMappingURL=babylon.materialHelper.js.map
  25019. var BABYLON;
  25020. (function (BABYLON) {
  25021. var MaterialDefines = (function () {
  25022. function MaterialDefines() {
  25023. this._isDirty = true;
  25024. this._areLightsDirty = true;
  25025. this._areAttributesDirty = true;
  25026. this._areTexturesDirty = true;
  25027. this._areFresnelDirty = true;
  25028. this._areMiscDirty = true;
  25029. this._areImageProcessingDirty = true;
  25030. this._normals = false;
  25031. this._uvs = false;
  25032. this._needNormals = false;
  25033. this._needUVs = false;
  25034. }
  25035. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  25036. get: function () {
  25037. return this._isDirty;
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. MaterialDefines.prototype.markAsProcessed = function () {
  25043. this._isDirty = false;
  25044. this._areAttributesDirty = false;
  25045. this._areTexturesDirty = false;
  25046. this._areFresnelDirty = false;
  25047. this._areLightsDirty = false;
  25048. this._areMiscDirty = false;
  25049. this._areImageProcessingDirty = false;
  25050. };
  25051. MaterialDefines.prototype.markAsUnprocessed = function () {
  25052. this._isDirty = true;
  25053. };
  25054. MaterialDefines.prototype.markAllAsDirty = function () {
  25055. this._areTexturesDirty = true;
  25056. this._areAttributesDirty = true;
  25057. this._areLightsDirty = true;
  25058. this._areFresnelDirty = true;
  25059. this._areMiscDirty = true;
  25060. this._areImageProcessingDirty = true;
  25061. this._isDirty = true;
  25062. };
  25063. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  25064. this._areImageProcessingDirty = true;
  25065. this._isDirty = true;
  25066. };
  25067. MaterialDefines.prototype.markAsLightDirty = function () {
  25068. this._areLightsDirty = true;
  25069. this._isDirty = true;
  25070. };
  25071. MaterialDefines.prototype.markAsAttributesDirty = function () {
  25072. this._areAttributesDirty = true;
  25073. this._isDirty = true;
  25074. };
  25075. MaterialDefines.prototype.markAsTexturesDirty = function () {
  25076. this._areTexturesDirty = true;
  25077. this._isDirty = true;
  25078. };
  25079. MaterialDefines.prototype.markAsFresnelDirty = function () {
  25080. this._areFresnelDirty = true;
  25081. this._isDirty = true;
  25082. };
  25083. MaterialDefines.prototype.markAsMiscDirty = function () {
  25084. this._areMiscDirty = true;
  25085. this._isDirty = true;
  25086. };
  25087. MaterialDefines.prototype.rebuild = function () {
  25088. if (this._keys) {
  25089. delete this._keys;
  25090. }
  25091. this._keys = [];
  25092. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  25093. var key = _a[_i];
  25094. if (key[0] === "_") {
  25095. continue;
  25096. }
  25097. this._keys.push(key);
  25098. }
  25099. };
  25100. MaterialDefines.prototype.isEqual = function (other) {
  25101. if (this._keys.length !== other._keys.length) {
  25102. return false;
  25103. }
  25104. for (var index = 0; index < this._keys.length; index++) {
  25105. var prop = this._keys[index];
  25106. if (this[prop] !== other[prop]) {
  25107. return false;
  25108. }
  25109. }
  25110. return true;
  25111. };
  25112. MaterialDefines.prototype.cloneTo = function (other) {
  25113. if (this._keys.length !== other._keys.length) {
  25114. other._keys = this._keys.slice(0);
  25115. }
  25116. for (var index = 0; index < this._keys.length; index++) {
  25117. var prop = this._keys[index];
  25118. other[prop] = this[prop];
  25119. }
  25120. };
  25121. MaterialDefines.prototype.reset = function () {
  25122. for (var index = 0; index < this._keys.length; index++) {
  25123. var prop = this._keys[index];
  25124. if (typeof (this[prop]) === "number") {
  25125. this[prop] = 0;
  25126. }
  25127. else {
  25128. this[prop] = false;
  25129. }
  25130. }
  25131. };
  25132. MaterialDefines.prototype.toString = function () {
  25133. var result = "";
  25134. for (var index = 0; index < this._keys.length; index++) {
  25135. var prop = this._keys[index];
  25136. var value = this[prop];
  25137. if (typeof (value) === "number") {
  25138. result += "#define " + prop + " " + this[prop] + "\n";
  25139. }
  25140. else if (value) {
  25141. result += "#define " + prop + "\n";
  25142. }
  25143. }
  25144. return result;
  25145. };
  25146. return MaterialDefines;
  25147. }());
  25148. BABYLON.MaterialDefines = MaterialDefines;
  25149. var Material = (function () {
  25150. function Material(name, scene, doNotAdd) {
  25151. this.checkReadyOnEveryCall = false;
  25152. this.checkReadyOnlyOnce = false;
  25153. this.state = "";
  25154. this.alpha = 1.0;
  25155. this._backFaceCulling = true;
  25156. this.doNotSerialize = false;
  25157. this.storeEffectOnSubMeshes = false;
  25158. /**
  25159. * An event triggered when the material is disposed.
  25160. * @type {BABYLON.Observable}
  25161. */
  25162. this.onDisposeObservable = new BABYLON.Observable();
  25163. /**
  25164. * An event triggered when the material is bound.
  25165. * @type {BABYLON.Observable}
  25166. */
  25167. this.onBindObservable = new BABYLON.Observable();
  25168. /**
  25169. * An event triggered when the material is unbound.
  25170. * @type {BABYLON.Observable}
  25171. */
  25172. this.onUnBindObservable = new BABYLON.Observable();
  25173. this.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  25174. this.disableDepthWrite = false;
  25175. this._fogEnabled = true;
  25176. this.pointSize = 1.0;
  25177. this.zOffset = 0;
  25178. this._wasPreviouslyReady = false;
  25179. this._fillMode = Material.TriangleFillMode;
  25180. this.name = name;
  25181. this.id = name || BABYLON.Tools.RandomId();
  25182. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  25183. if (this._scene.useRightHandedSystem) {
  25184. this.sideOrientation = Material.ClockWiseSideOrientation;
  25185. }
  25186. else {
  25187. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  25188. }
  25189. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  25190. this._useUBO = this.getScene().getEngine().webGLVersion > 1;
  25191. if (!doNotAdd) {
  25192. this._scene.materials.push(this);
  25193. }
  25194. }
  25195. Object.defineProperty(Material, "TriangleFillMode", {
  25196. get: function () {
  25197. return Material._TriangleFillMode;
  25198. },
  25199. enumerable: true,
  25200. configurable: true
  25201. });
  25202. Object.defineProperty(Material, "WireFrameFillMode", {
  25203. get: function () {
  25204. return Material._WireFrameFillMode;
  25205. },
  25206. enumerable: true,
  25207. configurable: true
  25208. });
  25209. Object.defineProperty(Material, "PointFillMode", {
  25210. get: function () {
  25211. return Material._PointFillMode;
  25212. },
  25213. enumerable: true,
  25214. configurable: true
  25215. });
  25216. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  25217. get: function () {
  25218. return Material._ClockWiseSideOrientation;
  25219. },
  25220. enumerable: true,
  25221. configurable: true
  25222. });
  25223. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  25224. get: function () {
  25225. return Material._CounterClockWiseSideOrientation;
  25226. },
  25227. enumerable: true,
  25228. configurable: true
  25229. });
  25230. Object.defineProperty(Material, "TextureDirtyFlag", {
  25231. get: function () {
  25232. return Material._TextureDirtyFlag;
  25233. },
  25234. enumerable: true,
  25235. configurable: true
  25236. });
  25237. Object.defineProperty(Material, "LightDirtyFlag", {
  25238. get: function () {
  25239. return Material._LightDirtyFlag;
  25240. },
  25241. enumerable: true,
  25242. configurable: true
  25243. });
  25244. Object.defineProperty(Material, "FresnelDirtyFlag", {
  25245. get: function () {
  25246. return Material._FresnelDirtyFlag;
  25247. },
  25248. enumerable: true,
  25249. configurable: true
  25250. });
  25251. Object.defineProperty(Material, "AttributesDirtyFlag", {
  25252. get: function () {
  25253. return Material._AttributesDirtyFlag;
  25254. },
  25255. enumerable: true,
  25256. configurable: true
  25257. });
  25258. Object.defineProperty(Material, "MiscDirtyFlag", {
  25259. get: function () {
  25260. return Material._MiscDirtyFlag;
  25261. },
  25262. enumerable: true,
  25263. configurable: true
  25264. });
  25265. Object.defineProperty(Material.prototype, "backFaceCulling", {
  25266. get: function () {
  25267. return this._backFaceCulling;
  25268. },
  25269. set: function (value) {
  25270. if (this._backFaceCulling === value) {
  25271. return;
  25272. }
  25273. this._backFaceCulling = value;
  25274. this.markAsDirty(Material.TextureDirtyFlag);
  25275. },
  25276. enumerable: true,
  25277. configurable: true
  25278. });
  25279. Object.defineProperty(Material.prototype, "onDispose", {
  25280. set: function (callback) {
  25281. if (this._onDisposeObserver) {
  25282. this.onDisposeObservable.remove(this._onDisposeObserver);
  25283. }
  25284. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  25285. },
  25286. enumerable: true,
  25287. configurable: true
  25288. });
  25289. Object.defineProperty(Material.prototype, "onBind", {
  25290. set: function (callback) {
  25291. if (this._onBindObserver) {
  25292. this.onBindObservable.remove(this._onBindObserver);
  25293. }
  25294. this._onBindObserver = this.onBindObservable.add(callback);
  25295. },
  25296. enumerable: true,
  25297. configurable: true
  25298. });
  25299. Object.defineProperty(Material.prototype, "fogEnabled", {
  25300. get: function () {
  25301. return this._fogEnabled;
  25302. },
  25303. set: function (value) {
  25304. if (this._fogEnabled === value) {
  25305. return;
  25306. }
  25307. this._fogEnabled = value;
  25308. this.markAsDirty(Material.MiscDirtyFlag);
  25309. },
  25310. enumerable: true,
  25311. configurable: true
  25312. });
  25313. Object.defineProperty(Material.prototype, "wireframe", {
  25314. get: function () {
  25315. return this._fillMode === Material.WireFrameFillMode;
  25316. },
  25317. set: function (value) {
  25318. this._fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  25319. },
  25320. enumerable: true,
  25321. configurable: true
  25322. });
  25323. Object.defineProperty(Material.prototype, "pointsCloud", {
  25324. get: function () {
  25325. return this._fillMode === Material.PointFillMode;
  25326. },
  25327. set: function (value) {
  25328. this._fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  25329. },
  25330. enumerable: true,
  25331. configurable: true
  25332. });
  25333. Object.defineProperty(Material.prototype, "fillMode", {
  25334. get: function () {
  25335. return this._fillMode;
  25336. },
  25337. set: function (value) {
  25338. if (this._fillMode === value) {
  25339. return;
  25340. }
  25341. this._fillMode = value;
  25342. this.markAsDirty(Material.MiscDirtyFlag);
  25343. },
  25344. enumerable: true,
  25345. configurable: true
  25346. });
  25347. /**
  25348. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  25349. * subclasses should override adding information pertainent to themselves
  25350. */
  25351. Material.prototype.toString = function (fullDetails) {
  25352. var ret = "Name: " + this.name;
  25353. if (fullDetails) {
  25354. }
  25355. return ret;
  25356. };
  25357. /**
  25358. * Child classes can use it to update shaders
  25359. */
  25360. Material.prototype.getClassName = function () {
  25361. return "Material";
  25362. };
  25363. Object.defineProperty(Material.prototype, "isFrozen", {
  25364. get: function () {
  25365. return this.checkReadyOnlyOnce;
  25366. },
  25367. enumerable: true,
  25368. configurable: true
  25369. });
  25370. Material.prototype.freeze = function () {
  25371. this.checkReadyOnlyOnce = true;
  25372. };
  25373. Material.prototype.unfreeze = function () {
  25374. this.checkReadyOnlyOnce = false;
  25375. };
  25376. Material.prototype.isReady = function (mesh, useInstances) {
  25377. return true;
  25378. };
  25379. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  25380. return false;
  25381. };
  25382. Material.prototype.getEffect = function () {
  25383. return this._effect;
  25384. };
  25385. Material.prototype.getScene = function () {
  25386. return this._scene;
  25387. };
  25388. Material.prototype.needAlphaBlending = function () {
  25389. return (this.alpha < 1.0);
  25390. };
  25391. Material.prototype.needAlphaTesting = function () {
  25392. return false;
  25393. };
  25394. Material.prototype.getAlphaTestTexture = function () {
  25395. return null;
  25396. };
  25397. Material.prototype.markDirty = function () {
  25398. this._wasPreviouslyReady = false;
  25399. };
  25400. Material.prototype._preBind = function (effect) {
  25401. var engine = this._scene.getEngine();
  25402. var reverse = this.sideOrientation === Material.ClockWiseSideOrientation;
  25403. engine.enableEffect(effect ? effect : this._effect);
  25404. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  25405. };
  25406. Material.prototype.bind = function (world, mesh) {
  25407. };
  25408. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  25409. };
  25410. Material.prototype.bindOnlyWorldMatrix = function (world) {
  25411. };
  25412. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  25413. sceneUbo.bindToEffect(effect, "Scene");
  25414. };
  25415. Material.prototype.bindView = function (effect) {
  25416. if (!this._useUBO) {
  25417. effect.setMatrix("view", this.getScene().getViewMatrix());
  25418. }
  25419. else {
  25420. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25421. }
  25422. };
  25423. Material.prototype.bindViewProjection = function (effect) {
  25424. if (!this._useUBO) {
  25425. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  25426. }
  25427. else {
  25428. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  25429. }
  25430. };
  25431. Material.prototype._afterBind = function (mesh) {
  25432. this._scene._cachedMaterial = this;
  25433. if (mesh) {
  25434. this._scene._cachedVisibility = mesh.visibility;
  25435. }
  25436. else {
  25437. this._scene._cachedVisibility = 1;
  25438. }
  25439. this.onBindObservable.notifyObservers(mesh);
  25440. if (this.disableDepthWrite) {
  25441. var engine = this._scene.getEngine();
  25442. this._cachedDepthWriteState = engine.getDepthWrite();
  25443. engine.setDepthWrite(false);
  25444. }
  25445. };
  25446. Material.prototype.unbind = function () {
  25447. this.onUnBindObservable.notifyObservers(this);
  25448. if (this.disableDepthWrite) {
  25449. var engine = this._scene.getEngine();
  25450. engine.setDepthWrite(this._cachedDepthWriteState);
  25451. }
  25452. };
  25453. Material.prototype.getActiveTextures = function () {
  25454. return [];
  25455. };
  25456. Material.prototype.hasTexture = function (texture) {
  25457. return false;
  25458. };
  25459. Material.prototype.clone = function (name) {
  25460. return null;
  25461. };
  25462. Material.prototype.getBindedMeshes = function () {
  25463. var result = new Array();
  25464. for (var index = 0; index < this._scene.meshes.length; index++) {
  25465. var mesh = this._scene.meshes[index];
  25466. if (mesh.material === this) {
  25467. result.push(mesh);
  25468. }
  25469. }
  25470. return result;
  25471. };
  25472. /**
  25473. * Force shader compilation including textures ready check
  25474. */
  25475. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  25476. var _this = this;
  25477. var subMesh = new BABYLON.BaseSubMesh();
  25478. var scene = this.getScene();
  25479. var engine = scene.getEngine();
  25480. var checkReady = function () {
  25481. if (!_this._scene || !_this._scene.getEngine()) {
  25482. return;
  25483. }
  25484. if (subMesh._materialDefines) {
  25485. subMesh._materialDefines._renderId = -1;
  25486. }
  25487. var alphaTestState = engine.getAlphaTesting();
  25488. var clipPlaneState = scene.clipPlane;
  25489. engine.setAlphaTesting(options ? options.alphaTest : _this.needAlphaTesting());
  25490. if (options && options.clipPlane) {
  25491. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  25492. }
  25493. if (_this.storeEffectOnSubMeshes) {
  25494. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  25495. if (onCompiled) {
  25496. onCompiled(_this);
  25497. }
  25498. }
  25499. else {
  25500. setTimeout(checkReady, 16);
  25501. }
  25502. }
  25503. else {
  25504. if (_this.isReady(mesh)) {
  25505. if (onCompiled) {
  25506. onCompiled(_this);
  25507. }
  25508. }
  25509. else {
  25510. setTimeout(checkReady, 16);
  25511. }
  25512. }
  25513. engine.setAlphaTesting(alphaTestState);
  25514. if (options && options.clipPlane) {
  25515. scene.clipPlane = clipPlaneState;
  25516. }
  25517. };
  25518. checkReady();
  25519. };
  25520. Material.prototype.markAsDirty = function (flag) {
  25521. if (flag & Material.TextureDirtyFlag) {
  25522. this._markAllSubMeshesAsTexturesDirty();
  25523. }
  25524. if (flag & Material.LightDirtyFlag) {
  25525. this._markAllSubMeshesAsLightsDirty();
  25526. }
  25527. if (flag & Material.FresnelDirtyFlag) {
  25528. this._markAllSubMeshesAsFresnelDirty();
  25529. }
  25530. if (flag & Material.AttributesDirtyFlag) {
  25531. this._markAllSubMeshesAsAttributesDirty();
  25532. }
  25533. if (flag & Material.MiscDirtyFlag) {
  25534. this._markAllSubMeshesAsMiscDirty();
  25535. }
  25536. this.getScene().resetCachedMaterial();
  25537. };
  25538. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  25539. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  25540. var mesh = _a[_i];
  25541. if (!mesh.subMeshes) {
  25542. continue;
  25543. }
  25544. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25545. var subMesh = _c[_b];
  25546. if (subMesh.getMaterial() !== this) {
  25547. continue;
  25548. }
  25549. if (!subMesh._materialDefines) {
  25550. continue;
  25551. }
  25552. func(subMesh._materialDefines);
  25553. }
  25554. }
  25555. };
  25556. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  25557. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  25558. };
  25559. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  25560. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  25561. };
  25562. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  25563. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  25564. };
  25565. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  25566. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  25567. };
  25568. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  25569. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  25570. };
  25571. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  25572. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  25573. };
  25574. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  25575. // Animations
  25576. this.getScene().stopAnimation(this);
  25577. // Remove from scene
  25578. var index = this._scene.materials.indexOf(this);
  25579. if (index >= 0) {
  25580. this._scene.materials.splice(index, 1);
  25581. }
  25582. // Remove from meshes
  25583. for (index = 0; index < this._scene.meshes.length; index++) {
  25584. var mesh = this._scene.meshes[index];
  25585. if (mesh.material === this) {
  25586. mesh.material = null;
  25587. if (mesh.geometry) {
  25588. var geometry = mesh.geometry;
  25589. if (this.storeEffectOnSubMeshes) {
  25590. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  25591. var subMesh = _a[_i];
  25592. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  25593. }
  25594. }
  25595. else {
  25596. geometry._releaseVertexArrayObject(this._effect);
  25597. }
  25598. }
  25599. }
  25600. }
  25601. this._uniformBuffer.dispose();
  25602. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  25603. if (forceDisposeEffect && this._effect) {
  25604. if (this.storeEffectOnSubMeshes) {
  25605. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25606. var subMesh = _c[_b];
  25607. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  25608. }
  25609. }
  25610. else {
  25611. this._scene.getEngine()._releaseEffect(this._effect);
  25612. }
  25613. this._effect = null;
  25614. }
  25615. // Callback
  25616. this.onDisposeObservable.notifyObservers(this);
  25617. this.onDisposeObservable.clear();
  25618. this.onBindObservable.clear();
  25619. this.onUnBindObservable.clear();
  25620. };
  25621. Material.prototype.serialize = function () {
  25622. return BABYLON.SerializationHelper.Serialize(this);
  25623. };
  25624. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  25625. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  25626. multiMaterial.id = parsedMultiMaterial.id;
  25627. if (BABYLON.Tags) {
  25628. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  25629. }
  25630. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  25631. var subMatId = parsedMultiMaterial.materials[matIndex];
  25632. if (subMatId) {
  25633. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  25634. }
  25635. else {
  25636. multiMaterial.subMaterials.push(null);
  25637. }
  25638. }
  25639. return multiMaterial;
  25640. };
  25641. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  25642. if (!parsedMaterial.customType) {
  25643. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  25644. }
  25645. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  25646. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  25647. if (!BABYLON.LegacyPBRMaterial) {
  25648. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  25649. return;
  25650. }
  25651. }
  25652. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  25653. return materialType.Parse(parsedMaterial, scene, rootUrl);
  25654. ;
  25655. };
  25656. Material._TriangleFillMode = 0;
  25657. Material._WireFrameFillMode = 1;
  25658. Material._PointFillMode = 2;
  25659. Material._ClockWiseSideOrientation = 0;
  25660. Material._CounterClockWiseSideOrientation = 1;
  25661. Material._TextureDirtyFlag = 1;
  25662. Material._LightDirtyFlag = 2;
  25663. Material._FresnelDirtyFlag = 4;
  25664. Material._AttributesDirtyFlag = 8;
  25665. Material._MiscDirtyFlag = 16;
  25666. __decorate([
  25667. BABYLON.serialize()
  25668. ], Material.prototype, "id", void 0);
  25669. __decorate([
  25670. BABYLON.serialize()
  25671. ], Material.prototype, "name", void 0);
  25672. __decorate([
  25673. BABYLON.serialize()
  25674. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  25675. __decorate([
  25676. BABYLON.serialize()
  25677. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  25678. __decorate([
  25679. BABYLON.serialize()
  25680. ], Material.prototype, "state", void 0);
  25681. __decorate([
  25682. BABYLON.serialize()
  25683. ], Material.prototype, "alpha", void 0);
  25684. __decorate([
  25685. BABYLON.serialize("backFaceCulling")
  25686. ], Material.prototype, "_backFaceCulling", void 0);
  25687. __decorate([
  25688. BABYLON.serialize()
  25689. ], Material.prototype, "sideOrientation", void 0);
  25690. __decorate([
  25691. BABYLON.serialize()
  25692. ], Material.prototype, "alphaMode", void 0);
  25693. __decorate([
  25694. BABYLON.serialize()
  25695. ], Material.prototype, "disableDepthWrite", void 0);
  25696. __decorate([
  25697. BABYLON.serialize("fogEnabled")
  25698. ], Material.prototype, "_fogEnabled", void 0);
  25699. __decorate([
  25700. BABYLON.serialize()
  25701. ], Material.prototype, "pointSize", void 0);
  25702. __decorate([
  25703. BABYLON.serialize()
  25704. ], Material.prototype, "zOffset", void 0);
  25705. __decorate([
  25706. BABYLON.serialize()
  25707. ], Material.prototype, "wireframe", null);
  25708. __decorate([
  25709. BABYLON.serialize()
  25710. ], Material.prototype, "pointsCloud", null);
  25711. __decorate([
  25712. BABYLON.serialize()
  25713. ], Material.prototype, "fillMode", null);
  25714. return Material;
  25715. }());
  25716. BABYLON.Material = Material;
  25717. })(BABYLON || (BABYLON = {}));
  25718. //# sourceMappingURL=babylon.material.js.map
  25719. var BABYLON;
  25720. (function (BABYLON) {
  25721. var UniformBuffer = (function () {
  25722. /**
  25723. * Uniform buffer objects.
  25724. *
  25725. * Handles blocks of uniform on the GPU.
  25726. *
  25727. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  25728. *
  25729. * For more information, please refer to :
  25730. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  25731. */
  25732. function UniformBuffer(engine, data, dynamic) {
  25733. this._engine = engine;
  25734. this._noUBO = engine.webGLVersion === 1;
  25735. this._dynamic = dynamic;
  25736. this._data = data || [];
  25737. this._uniformLocations = {};
  25738. this._uniformSizes = {};
  25739. this._uniformLocationPointer = 0;
  25740. this._needSync = false;
  25741. if (this._noUBO) {
  25742. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  25743. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  25744. this.updateFloat = this._updateFloatForEffect;
  25745. this.updateFloat2 = this._updateFloat2ForEffect;
  25746. this.updateFloat3 = this._updateFloat3ForEffect;
  25747. this.updateFloat4 = this._updateFloat4ForEffect;
  25748. this.updateMatrix = this._updateMatrixForEffect;
  25749. this.updateVector3 = this._updateVector3ForEffect;
  25750. this.updateVector4 = this._updateVector4ForEffect;
  25751. this.updateColor3 = this._updateColor3ForEffect;
  25752. this.updateColor4 = this._updateColor4ForEffect;
  25753. }
  25754. else {
  25755. this._engine._uniformBuffers.push(this);
  25756. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  25757. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  25758. this.updateFloat = this._updateFloatForUniform;
  25759. this.updateFloat2 = this._updateFloat2ForUniform;
  25760. this.updateFloat3 = this._updateFloat3ForUniform;
  25761. this.updateFloat4 = this._updateFloat4ForUniform;
  25762. this.updateMatrix = this._updateMatrixForUniform;
  25763. this.updateVector3 = this._updateVector3ForUniform;
  25764. this.updateVector4 = this._updateVector4ForUniform;
  25765. this.updateColor3 = this._updateColor3ForUniform;
  25766. this.updateColor4 = this._updateColor4ForUniform;
  25767. }
  25768. }
  25769. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  25770. // Properties
  25771. /**
  25772. * Indicates if the buffer is using the WebGL2 UBO implementation,
  25773. * or just falling back on setUniformXXX calls.
  25774. */
  25775. get: function () {
  25776. return !this._noUBO;
  25777. },
  25778. enumerable: true,
  25779. configurable: true
  25780. });
  25781. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  25782. /**
  25783. * Indicates if the WebGL underlying uniform buffer is in sync
  25784. * with the javascript cache data.
  25785. */
  25786. get: function () {
  25787. return !this._needSync;
  25788. },
  25789. enumerable: true,
  25790. configurable: true
  25791. });
  25792. /**
  25793. * Indicates if the WebGL underlying uniform buffer is dynamic.
  25794. * Also, a dynamic UniformBuffer will disable cache verification and always
  25795. * update the underlying WebGL uniform buffer to the GPU.
  25796. */
  25797. UniformBuffer.prototype.isDynamic = function () {
  25798. return this._dynamic;
  25799. };
  25800. /**
  25801. * The data cache on JS side.
  25802. */
  25803. UniformBuffer.prototype.getData = function () {
  25804. return this._bufferData;
  25805. };
  25806. /**
  25807. * The underlying WebGL Uniform buffer.
  25808. */
  25809. UniformBuffer.prototype.getBuffer = function () {
  25810. return this._buffer;
  25811. };
  25812. /**
  25813. * std140 layout specifies how to align data within an UBO structure.
  25814. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  25815. * for specs.
  25816. */
  25817. UniformBuffer.prototype._fillAlignment = function (size) {
  25818. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  25819. // and 4x4 matrices
  25820. // TODO : change if other types are used
  25821. var alignment;
  25822. if (size <= 2) {
  25823. alignment = size;
  25824. }
  25825. else {
  25826. alignment = 4;
  25827. }
  25828. if ((this._uniformLocationPointer % alignment) !== 0) {
  25829. var oldPointer = this._uniformLocationPointer;
  25830. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  25831. var diff = this._uniformLocationPointer - oldPointer;
  25832. for (var i = 0; i < diff; i++) {
  25833. this._data.push(0);
  25834. }
  25835. }
  25836. };
  25837. /**
  25838. * Adds an uniform in the buffer.
  25839. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  25840. * for the layout to be correct !
  25841. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25842. * @param {number|number[]} size Data size, or data directly.
  25843. */
  25844. UniformBuffer.prototype.addUniform = function (name, size) {
  25845. if (this._noUBO) {
  25846. return;
  25847. }
  25848. if (this._uniformLocations[name] !== undefined) {
  25849. // Already existing uniform
  25850. return;
  25851. }
  25852. // This function must be called in the order of the shader layout !
  25853. // size can be the size of the uniform, or data directly
  25854. var data;
  25855. if (size instanceof Array) {
  25856. data = size;
  25857. size = data.length;
  25858. }
  25859. else {
  25860. size = size;
  25861. data = [];
  25862. // Fill with zeros
  25863. for (var i = 0; i < size; i++) {
  25864. data.push(0);
  25865. }
  25866. }
  25867. this._fillAlignment(size);
  25868. this._uniformSizes[name] = size;
  25869. this._uniformLocations[name] = this._uniformLocationPointer;
  25870. this._uniformLocationPointer += size;
  25871. for (var i = 0; i < size; i++) {
  25872. this._data.push(data[i]);
  25873. }
  25874. this._needSync = true;
  25875. };
  25876. /**
  25877. * Wrapper for addUniform.
  25878. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25879. * @param {Matrix} mat A 4x4 matrix.
  25880. */
  25881. UniformBuffer.prototype.addMatrix = function (name, mat) {
  25882. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  25883. };
  25884. /**
  25885. * Wrapper for addUniform.
  25886. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25887. * @param {number} x
  25888. * @param {number} y
  25889. */
  25890. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  25891. var temp = [x, y];
  25892. this.addUniform(name, temp);
  25893. };
  25894. /**
  25895. * Wrapper for addUniform.
  25896. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25897. * @param {number} x
  25898. * @param {number} y
  25899. * @param {number} z
  25900. */
  25901. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  25902. var temp = [x, y, z];
  25903. this.addUniform(name, temp);
  25904. };
  25905. /**
  25906. * Wrapper for addUniform.
  25907. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25908. * @param {Color3} color
  25909. */
  25910. UniformBuffer.prototype.addColor3 = function (name, color) {
  25911. var temp = [];
  25912. color.toArray(temp);
  25913. this.addUniform(name, temp);
  25914. };
  25915. /**
  25916. * Wrapper for addUniform.
  25917. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25918. * @param {Color3} color
  25919. * @param {number} alpha
  25920. */
  25921. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  25922. var temp = [];
  25923. color.toArray(temp);
  25924. temp.push(alpha);
  25925. this.addUniform(name, temp);
  25926. };
  25927. /**
  25928. * Wrapper for addUniform.
  25929. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25930. * @param {Vector3} vector
  25931. */
  25932. UniformBuffer.prototype.addVector3 = function (name, vector) {
  25933. var temp = [];
  25934. vector.toArray(temp);
  25935. this.addUniform(name, temp);
  25936. };
  25937. /**
  25938. * Wrapper for addUniform.
  25939. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25940. */
  25941. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  25942. this.addUniform(name, 12);
  25943. };
  25944. /**
  25945. * Wrapper for addUniform.
  25946. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  25947. */
  25948. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  25949. this.addUniform(name, 8);
  25950. };
  25951. /**
  25952. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  25953. */
  25954. UniformBuffer.prototype.create = function () {
  25955. if (this._noUBO) {
  25956. return;
  25957. }
  25958. if (this._buffer) {
  25959. return; // nothing to do
  25960. }
  25961. // See spec, alignment must be filled as a vec4
  25962. this._fillAlignment(4);
  25963. this._bufferData = new Float32Array(this._data);
  25964. this._rebuild();
  25965. this._needSync = true;
  25966. };
  25967. UniformBuffer.prototype._rebuild = function () {
  25968. if (this._noUBO) {
  25969. return;
  25970. }
  25971. if (this._dynamic) {
  25972. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  25973. }
  25974. else {
  25975. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  25976. }
  25977. };
  25978. /**
  25979. * Updates the WebGL Uniform Buffer on the GPU.
  25980. * If the `dynamic` flag is set to true, no cache comparison is done.
  25981. * Otherwise, the buffer will be updated only if the cache differs.
  25982. */
  25983. UniformBuffer.prototype.update = function () {
  25984. if (!this._buffer) {
  25985. this.create();
  25986. return;
  25987. }
  25988. if (!this._dynamic && !this._needSync) {
  25989. return;
  25990. }
  25991. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  25992. this._needSync = false;
  25993. };
  25994. /**
  25995. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  25996. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  25997. * @param {number[]|Float32Array} data Flattened data
  25998. * @param {number} size Size of the data.
  25999. */
  26000. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  26001. var location = this._uniformLocations[uniformName];
  26002. if (location === undefined) {
  26003. if (this._buffer) {
  26004. // Cannot add an uniform if the buffer is already created
  26005. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  26006. return;
  26007. }
  26008. this.addUniform(uniformName, size);
  26009. location = this._uniformLocations[uniformName];
  26010. }
  26011. if (!this._buffer) {
  26012. this.create();
  26013. }
  26014. if (!this._dynamic) {
  26015. // Cache for static uniform buffers
  26016. var changed = false;
  26017. for (var i = 0; i < size; i++) {
  26018. if (this._bufferData[location + i] !== data[i]) {
  26019. changed = true;
  26020. this._bufferData[location + i] = data[i];
  26021. }
  26022. }
  26023. this._needSync = this._needSync || changed;
  26024. }
  26025. else {
  26026. // No cache for dynamic
  26027. for (var i = 0; i < size; i++) {
  26028. this._bufferData[location + i] = data[i];
  26029. }
  26030. }
  26031. };
  26032. // Update methods
  26033. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  26034. // To match std140, matrix must be realigned
  26035. for (var i = 0; i < 3; i++) {
  26036. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  26037. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  26038. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  26039. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26040. }
  26041. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  26042. };
  26043. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  26044. this._currentEffect.setMatrix3x3(name, matrix);
  26045. };
  26046. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  26047. this._currentEffect.setMatrix2x2(name, matrix);
  26048. };
  26049. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  26050. // To match std140, matrix must be realigned
  26051. for (var i = 0; i < 2; i++) {
  26052. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  26053. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  26054. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  26055. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  26056. }
  26057. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  26058. };
  26059. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  26060. this._currentEffect.setFloat(name, x);
  26061. };
  26062. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  26063. UniformBuffer._tempBuffer[0] = x;
  26064. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  26065. };
  26066. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  26067. if (suffix === void 0) { suffix = ""; }
  26068. this._currentEffect.setFloat2(name + suffix, x, y);
  26069. };
  26070. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  26071. if (suffix === void 0) { suffix = ""; }
  26072. UniformBuffer._tempBuffer[0] = x;
  26073. UniformBuffer._tempBuffer[1] = y;
  26074. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  26075. };
  26076. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  26077. if (suffix === void 0) { suffix = ""; }
  26078. this._currentEffect.setFloat3(name + suffix, x, y, z);
  26079. };
  26080. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  26081. if (suffix === void 0) { suffix = ""; }
  26082. UniformBuffer._tempBuffer[0] = x;
  26083. UniformBuffer._tempBuffer[1] = y;
  26084. UniformBuffer._tempBuffer[2] = z;
  26085. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26086. };
  26087. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  26088. if (suffix === void 0) { suffix = ""; }
  26089. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  26090. };
  26091. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  26092. if (suffix === void 0) { suffix = ""; }
  26093. UniformBuffer._tempBuffer[0] = x;
  26094. UniformBuffer._tempBuffer[1] = y;
  26095. UniformBuffer._tempBuffer[2] = z;
  26096. UniformBuffer._tempBuffer[3] = w;
  26097. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26098. };
  26099. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  26100. this._currentEffect.setMatrix(name, mat);
  26101. };
  26102. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  26103. this.updateUniform(name, mat.toArray(), 16);
  26104. };
  26105. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  26106. this._currentEffect.setVector3(name, vector);
  26107. };
  26108. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  26109. vector.toArray(UniformBuffer._tempBuffer);
  26110. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26111. };
  26112. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  26113. this._currentEffect.setVector4(name, vector);
  26114. };
  26115. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  26116. vector.toArray(UniformBuffer._tempBuffer);
  26117. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26118. };
  26119. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  26120. if (suffix === void 0) { suffix = ""; }
  26121. this._currentEffect.setColor3(name + suffix, color);
  26122. };
  26123. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  26124. if (suffix === void 0) { suffix = ""; }
  26125. color.toArray(UniformBuffer._tempBuffer);
  26126. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  26127. };
  26128. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  26129. if (suffix === void 0) { suffix = ""; }
  26130. this._currentEffect.setColor4(name + suffix, color, alpha);
  26131. };
  26132. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  26133. if (suffix === void 0) { suffix = ""; }
  26134. color.toArray(UniformBuffer._tempBuffer);
  26135. UniformBuffer._tempBuffer[3] = alpha;
  26136. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  26137. };
  26138. /**
  26139. * Sets a sampler uniform on the effect.
  26140. * @param {string} name Name of the sampler.
  26141. * @param {Texture} texture
  26142. */
  26143. UniformBuffer.prototype.setTexture = function (name, texture) {
  26144. this._currentEffect.setTexture(name, texture);
  26145. };
  26146. /**
  26147. * Directly updates the value of the uniform in the cache AND on the GPU.
  26148. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  26149. * @param {number[]|Float32Array} data Flattened data
  26150. */
  26151. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  26152. this.updateUniform(uniformName, data, data.length);
  26153. this.update();
  26154. };
  26155. /**
  26156. * Binds this uniform buffer to an effect.
  26157. * @param {Effect} effect
  26158. * @param {string} name Name of the uniform block in the shader.
  26159. */
  26160. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  26161. this._currentEffect = effect;
  26162. if (this._noUBO) {
  26163. return;
  26164. }
  26165. effect.bindUniformBuffer(this._buffer, name);
  26166. };
  26167. /**
  26168. * Disposes the uniform buffer.
  26169. */
  26170. UniformBuffer.prototype.dispose = function () {
  26171. if (this._noUBO) {
  26172. return;
  26173. }
  26174. var index = this._engine._uniformBuffers.indexOf(this);
  26175. if (index !== -1) {
  26176. this._engine._uniformBuffers.splice(index, 1);
  26177. }
  26178. if (!this._buffer) {
  26179. return;
  26180. }
  26181. if (this._engine._releaseBuffer(this._buffer)) {
  26182. this._buffer = null;
  26183. }
  26184. };
  26185. // Pool for avoiding memory leaks
  26186. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  26187. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  26188. return UniformBuffer;
  26189. }());
  26190. BABYLON.UniformBuffer = UniformBuffer;
  26191. })(BABYLON || (BABYLON = {}));
  26192. //# sourceMappingURL=babylon.uniformBuffer.js.map
  26193. var BABYLON;
  26194. (function (BABYLON) {
  26195. var PushMaterial = (function (_super) {
  26196. __extends(PushMaterial, _super);
  26197. function PushMaterial(name, scene) {
  26198. var _this = _super.call(this, name, scene) || this;
  26199. _this.storeEffectOnSubMeshes = true;
  26200. return _this;
  26201. }
  26202. PushMaterial.prototype.getEffect = function () {
  26203. return this._activeEffect;
  26204. };
  26205. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  26206. if (!mesh) {
  26207. return false;
  26208. }
  26209. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  26210. return true;
  26211. }
  26212. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  26213. };
  26214. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  26215. this._activeEffect.setMatrix("world", world);
  26216. };
  26217. PushMaterial.prototype.bind = function (world, mesh) {
  26218. if (!mesh) {
  26219. return;
  26220. }
  26221. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  26222. };
  26223. PushMaterial.prototype._afterBind = function (mesh, effect) {
  26224. _super.prototype._afterBind.call(this, mesh);
  26225. this.getScene()._cachedEffect = effect;
  26226. };
  26227. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  26228. if (visibility === void 0) { visibility = 1; }
  26229. return scene.isCachedMaterialInvalid(this, effect, visibility);
  26230. };
  26231. return PushMaterial;
  26232. }(BABYLON.Material));
  26233. BABYLON.PushMaterial = PushMaterial;
  26234. })(BABYLON || (BABYLON = {}));
  26235. //# sourceMappingURL=babylon.pushMaterial.js.map
  26236. var BABYLON;
  26237. (function (BABYLON) {
  26238. var VertexData = (function () {
  26239. function VertexData() {
  26240. }
  26241. VertexData.prototype.set = function (data, kind) {
  26242. switch (kind) {
  26243. case BABYLON.VertexBuffer.PositionKind:
  26244. this.positions = data;
  26245. break;
  26246. case BABYLON.VertexBuffer.NormalKind:
  26247. this.normals = data;
  26248. break;
  26249. case BABYLON.VertexBuffer.TangentKind:
  26250. this.tangents = data;
  26251. break;
  26252. case BABYLON.VertexBuffer.UVKind:
  26253. this.uvs = data;
  26254. break;
  26255. case BABYLON.VertexBuffer.UV2Kind:
  26256. this.uvs2 = data;
  26257. break;
  26258. case BABYLON.VertexBuffer.UV3Kind:
  26259. this.uvs3 = data;
  26260. break;
  26261. case BABYLON.VertexBuffer.UV4Kind:
  26262. this.uvs4 = data;
  26263. break;
  26264. case BABYLON.VertexBuffer.UV5Kind:
  26265. this.uvs5 = data;
  26266. break;
  26267. case BABYLON.VertexBuffer.UV6Kind:
  26268. this.uvs6 = data;
  26269. break;
  26270. case BABYLON.VertexBuffer.ColorKind:
  26271. this.colors = data;
  26272. break;
  26273. case BABYLON.VertexBuffer.MatricesIndicesKind:
  26274. this.matricesIndices = data;
  26275. break;
  26276. case BABYLON.VertexBuffer.MatricesWeightsKind:
  26277. this.matricesWeights = data;
  26278. break;
  26279. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  26280. this.matricesIndicesExtra = data;
  26281. break;
  26282. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  26283. this.matricesWeightsExtra = data;
  26284. break;
  26285. }
  26286. };
  26287. /**
  26288. * Associates the vertexData to the passed Mesh.
  26289. * Sets it as updatable or not (default `false`).
  26290. * Returns the VertexData.
  26291. */
  26292. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  26293. this._applyTo(mesh, updatable);
  26294. return this;
  26295. };
  26296. /**
  26297. * Associates the vertexData to the passed Geometry.
  26298. * Sets it as updatable or not (default `false`).
  26299. * Returns the VertexData.
  26300. */
  26301. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  26302. this._applyTo(geometry, updatable);
  26303. return this;
  26304. };
  26305. /**
  26306. * Updates the associated mesh.
  26307. * Returns the VertexData.
  26308. */
  26309. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  26310. this._update(mesh);
  26311. return this;
  26312. };
  26313. /**
  26314. * Updates the associated geometry.
  26315. * Returns the VertexData.
  26316. */
  26317. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  26318. this._update(geometry);
  26319. return this;
  26320. };
  26321. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  26322. if (this.positions) {
  26323. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  26324. }
  26325. if (this.normals) {
  26326. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  26327. }
  26328. if (this.tangents) {
  26329. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  26330. }
  26331. if (this.uvs) {
  26332. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  26333. }
  26334. if (this.uvs2) {
  26335. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  26336. }
  26337. if (this.uvs3) {
  26338. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  26339. }
  26340. if (this.uvs4) {
  26341. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  26342. }
  26343. if (this.uvs5) {
  26344. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  26345. }
  26346. if (this.uvs6) {
  26347. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  26348. }
  26349. if (this.colors) {
  26350. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  26351. }
  26352. if (this.matricesIndices) {
  26353. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  26354. }
  26355. if (this.matricesWeights) {
  26356. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  26357. }
  26358. if (this.matricesIndicesExtra) {
  26359. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  26360. }
  26361. if (this.matricesWeightsExtra) {
  26362. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  26363. }
  26364. if (this.indices) {
  26365. meshOrGeometry.setIndices(this.indices);
  26366. }
  26367. return this;
  26368. };
  26369. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  26370. if (this.positions) {
  26371. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  26372. }
  26373. if (this.normals) {
  26374. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  26375. }
  26376. if (this.tangents) {
  26377. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  26378. }
  26379. if (this.uvs) {
  26380. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  26381. }
  26382. if (this.uvs2) {
  26383. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  26384. }
  26385. if (this.uvs3) {
  26386. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  26387. }
  26388. if (this.uvs4) {
  26389. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  26390. }
  26391. if (this.uvs5) {
  26392. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  26393. }
  26394. if (this.uvs6) {
  26395. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  26396. }
  26397. if (this.colors) {
  26398. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  26399. }
  26400. if (this.matricesIndices) {
  26401. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  26402. }
  26403. if (this.matricesWeights) {
  26404. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  26405. }
  26406. if (this.matricesIndicesExtra) {
  26407. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  26408. }
  26409. if (this.matricesWeightsExtra) {
  26410. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  26411. }
  26412. if (this.indices) {
  26413. meshOrGeometry.setIndices(this.indices);
  26414. }
  26415. return this;
  26416. };
  26417. /**
  26418. * Transforms each position and each normal of the vertexData according to the passed Matrix.
  26419. * Returns the VertexData.
  26420. */
  26421. VertexData.prototype.transform = function (matrix) {
  26422. var transformed = BABYLON.Vector3.Zero();
  26423. var index;
  26424. if (this.positions) {
  26425. var position = BABYLON.Vector3.Zero();
  26426. for (index = 0; index < this.positions.length; index += 3) {
  26427. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  26428. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  26429. this.positions[index] = transformed.x;
  26430. this.positions[index + 1] = transformed.y;
  26431. this.positions[index + 2] = transformed.z;
  26432. }
  26433. }
  26434. if (this.normals) {
  26435. var normal = BABYLON.Vector3.Zero();
  26436. for (index = 0; index < this.normals.length; index += 3) {
  26437. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  26438. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  26439. this.normals[index] = transformed.x;
  26440. this.normals[index + 1] = transformed.y;
  26441. this.normals[index + 2] = transformed.z;
  26442. }
  26443. }
  26444. if (this.tangents) {
  26445. var tangent = BABYLON.Vector4.Zero();
  26446. var tangentTransformed = BABYLON.Vector4.Zero();
  26447. for (index = 0; index < this.tangents.length; index += 4) {
  26448. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  26449. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  26450. this.tangents[index] = tangentTransformed.x;
  26451. this.tangents[index + 1] = tangentTransformed.y;
  26452. this.tangents[index + 2] = tangentTransformed.z;
  26453. this.tangents[index + 3] = tangentTransformed.w;
  26454. }
  26455. }
  26456. return this;
  26457. };
  26458. /**
  26459. * Merges the passed VertexData into the current one.
  26460. * Returns the modified VertexData.
  26461. */
  26462. VertexData.prototype.merge = function (other) {
  26463. if (other.indices) {
  26464. if (!this.indices) {
  26465. this.indices = [];
  26466. }
  26467. var offset = this.positions ? this.positions.length / 3 : 0;
  26468. for (var index = 0; index < other.indices.length; index++) {
  26469. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  26470. this.indices.push(other.indices[index] + offset);
  26471. }
  26472. }
  26473. this.positions = this._mergeElement(this.positions, other.positions);
  26474. this.normals = this._mergeElement(this.normals, other.normals);
  26475. this.tangents = this._mergeElement(this.tangents, other.tangents);
  26476. this.uvs = this._mergeElement(this.uvs, other.uvs);
  26477. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  26478. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  26479. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  26480. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  26481. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  26482. this.colors = this._mergeElement(this.colors, other.colors);
  26483. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  26484. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  26485. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  26486. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  26487. return this;
  26488. };
  26489. VertexData.prototype._mergeElement = function (source, other) {
  26490. if (!other)
  26491. return source;
  26492. if (!source)
  26493. return other;
  26494. var len = other.length + source.length;
  26495. var isSrcTypedArray = source instanceof Float32Array;
  26496. var isOthTypedArray = other instanceof Float32Array;
  26497. // use non-loop method when the source is Float32Array
  26498. if (isSrcTypedArray) {
  26499. var ret32 = new Float32Array(len);
  26500. ret32.set(source);
  26501. ret32.set(other, source.length);
  26502. return ret32;
  26503. // source is number[], when other is also use concat
  26504. }
  26505. else if (!isOthTypedArray) {
  26506. return source.concat(other);
  26507. // source is a number[], but other is a Float32Array, loop required
  26508. }
  26509. else {
  26510. var ret = source.slice(0); // copy source to a separate array
  26511. for (var i = 0, len = other.length; i < len; i++) {
  26512. ret.push(other[i]);
  26513. }
  26514. return ret;
  26515. }
  26516. };
  26517. /**
  26518. * Serializes the VertexData.
  26519. * Returns a serialized object.
  26520. */
  26521. VertexData.prototype.serialize = function () {
  26522. var serializationObject = this.serialize();
  26523. if (this.positions) {
  26524. serializationObject.positions = this.positions;
  26525. }
  26526. if (this.normals) {
  26527. serializationObject.normals = this.normals;
  26528. }
  26529. if (this.tangents) {
  26530. serializationObject.tangents = this.tangents;
  26531. }
  26532. if (this.uvs) {
  26533. serializationObject.uvs = this.uvs;
  26534. }
  26535. if (this.uvs2) {
  26536. serializationObject.uvs2 = this.uvs2;
  26537. }
  26538. if (this.uvs3) {
  26539. serializationObject.uvs3 = this.uvs3;
  26540. }
  26541. if (this.uvs4) {
  26542. serializationObject.uvs4 = this.uvs4;
  26543. }
  26544. if (this.uvs5) {
  26545. serializationObject.uvs5 = this.uvs5;
  26546. }
  26547. if (this.uvs6) {
  26548. serializationObject.uvs6 = this.uvs6;
  26549. }
  26550. if (this.colors) {
  26551. serializationObject.colors = this.colors;
  26552. }
  26553. if (this.matricesIndices) {
  26554. serializationObject.matricesIndices = this.matricesIndices;
  26555. serializationObject.matricesIndices._isExpanded = true;
  26556. }
  26557. if (this.matricesWeights) {
  26558. serializationObject.matricesWeights = this.matricesWeights;
  26559. }
  26560. if (this.matricesIndicesExtra) {
  26561. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  26562. serializationObject.matricesIndicesExtra._isExpanded = true;
  26563. }
  26564. if (this.matricesWeightsExtra) {
  26565. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  26566. }
  26567. serializationObject.indices = this.indices;
  26568. return serializationObject;
  26569. };
  26570. // Statics
  26571. /**
  26572. * Returns the object VertexData associated to the passed mesh.
  26573. */
  26574. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  26575. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  26576. };
  26577. /**
  26578. * Returns the object VertexData associated to the passed geometry.
  26579. */
  26580. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  26581. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  26582. };
  26583. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  26584. var result = new VertexData();
  26585. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  26586. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  26587. }
  26588. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  26589. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  26590. }
  26591. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  26592. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  26593. }
  26594. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  26595. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  26596. }
  26597. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  26598. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  26599. }
  26600. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  26601. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  26602. }
  26603. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  26604. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  26605. }
  26606. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  26607. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  26608. }
  26609. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  26610. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  26611. }
  26612. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  26613. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  26614. }
  26615. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  26616. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  26617. }
  26618. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  26619. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  26620. }
  26621. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  26622. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  26623. }
  26624. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  26625. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  26626. }
  26627. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  26628. return result;
  26629. };
  26630. /**
  26631. * Creates the vertexData of the Ribbon.
  26632. */
  26633. VertexData.CreateRibbon = function (options) {
  26634. var pathArray = options.pathArray;
  26635. var closeArray = options.closeArray || false;
  26636. var closePath = options.closePath || false;
  26637. var invertUV = options.invertUV || false;
  26638. var defaultOffset = Math.floor(pathArray[0].length / 2);
  26639. var offset = options.offset || defaultOffset;
  26640. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  26641. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26642. var customUV = options.uvs;
  26643. var customColors = options.colors;
  26644. var positions = [];
  26645. var indices = [];
  26646. var normals = [];
  26647. var uvs = [];
  26648. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  26649. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  26650. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  26651. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  26652. var minlg; // minimal length among all paths from pathArray
  26653. var lg = []; // array of path lengths : nb of vertex per path
  26654. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  26655. var p; // path iterator
  26656. var i; // point iterator
  26657. var j; // point iterator
  26658. // if single path in pathArray
  26659. if (pathArray.length < 2) {
  26660. var ar1 = [];
  26661. var ar2 = [];
  26662. for (i = 0; i < pathArray[0].length - offset; i++) {
  26663. ar1.push(pathArray[0][i]);
  26664. ar2.push(pathArray[0][i + offset]);
  26665. }
  26666. pathArray = [ar1, ar2];
  26667. }
  26668. // positions and horizontal distances (u)
  26669. var idc = 0;
  26670. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  26671. var path;
  26672. var l;
  26673. minlg = pathArray[0].length;
  26674. var vectlg;
  26675. var dist;
  26676. for (p = 0; p < pathArray.length; p++) {
  26677. uTotalDistance[p] = 0;
  26678. us[p] = [0];
  26679. path = pathArray[p];
  26680. l = path.length;
  26681. minlg = (minlg < l) ? minlg : l;
  26682. j = 0;
  26683. while (j < l) {
  26684. positions.push(path[j].x, path[j].y, path[j].z);
  26685. if (j > 0) {
  26686. vectlg = path[j].subtract(path[j - 1]).length();
  26687. dist = vectlg + uTotalDistance[p];
  26688. us[p].push(dist);
  26689. uTotalDistance[p] = dist;
  26690. }
  26691. j++;
  26692. }
  26693. if (closePath) {
  26694. j--;
  26695. positions.push(path[0].x, path[0].y, path[0].z);
  26696. vectlg = path[j].subtract(path[0]).length();
  26697. dist = vectlg + uTotalDistance[p];
  26698. us[p].push(dist);
  26699. uTotalDistance[p] = dist;
  26700. }
  26701. lg[p] = l + closePathCorr;
  26702. idx[p] = idc;
  26703. idc += (l + closePathCorr);
  26704. }
  26705. // vertical distances (v)
  26706. var path1;
  26707. var path2;
  26708. var vertex1;
  26709. var vertex2;
  26710. for (i = 0; i < minlg + closePathCorr; i++) {
  26711. vTotalDistance[i] = 0;
  26712. vs[i] = [0];
  26713. for (p = 0; p < pathArray.length - 1; p++) {
  26714. path1 = pathArray[p];
  26715. path2 = pathArray[p + 1];
  26716. if (i === minlg) {
  26717. vertex1 = path1[0];
  26718. vertex2 = path2[0];
  26719. }
  26720. else {
  26721. vertex1 = path1[i];
  26722. vertex2 = path2[i];
  26723. }
  26724. vectlg = vertex2.subtract(vertex1).length();
  26725. dist = vectlg + vTotalDistance[i];
  26726. vs[i].push(dist);
  26727. vTotalDistance[i] = dist;
  26728. }
  26729. if (closeArray) {
  26730. path1 = pathArray[p];
  26731. path2 = pathArray[0];
  26732. if (i === minlg) {
  26733. vertex2 = path2[0];
  26734. }
  26735. vectlg = vertex2.subtract(vertex1).length();
  26736. dist = vectlg + vTotalDistance[i];
  26737. vTotalDistance[i] = dist;
  26738. }
  26739. }
  26740. // uvs
  26741. var u;
  26742. var v;
  26743. if (customUV) {
  26744. for (p = 0; p < customUV.length; p++) {
  26745. uvs.push(customUV[p].x, customUV[p].y);
  26746. }
  26747. }
  26748. else {
  26749. for (p = 0; p < pathArray.length; p++) {
  26750. for (i = 0; i < minlg + closePathCorr; i++) {
  26751. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  26752. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  26753. if (invertUV) {
  26754. uvs.push(v, u);
  26755. }
  26756. else {
  26757. uvs.push(u, v);
  26758. }
  26759. }
  26760. }
  26761. }
  26762. // indices
  26763. p = 0; // path index
  26764. var pi = 0; // positions array index
  26765. var l1 = lg[p] - 1; // path1 length
  26766. var l2 = lg[p + 1] - 1; // path2 length
  26767. var min = (l1 < l2) ? l1 : l2; // current path stop index
  26768. var shft = idx[1] - idx[0]; // shift
  26769. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  26770. while (pi <= min && p < path1nb) {
  26771. // 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
  26772. indices.push(pi, pi + shft, pi + 1);
  26773. indices.push(pi + shft + 1, pi + 1, pi + shft);
  26774. pi += 1;
  26775. if (pi === min) {
  26776. p++;
  26777. if (p === lg.length - 1) {
  26778. shft = idx[0] - idx[p];
  26779. l1 = lg[p] - 1;
  26780. l2 = lg[0] - 1;
  26781. }
  26782. else {
  26783. shft = idx[p + 1] - idx[p];
  26784. l1 = lg[p] - 1;
  26785. l2 = lg[p + 1] - 1;
  26786. }
  26787. pi = idx[p];
  26788. min = (l1 < l2) ? l1 + pi : l2 + pi;
  26789. }
  26790. }
  26791. // normals
  26792. VertexData.ComputeNormals(positions, indices, normals);
  26793. if (closePath) {
  26794. var indexFirst = 0;
  26795. var indexLast = 0;
  26796. for (p = 0; p < pathArray.length; p++) {
  26797. indexFirst = idx[p] * 3;
  26798. if (p + 1 < pathArray.length) {
  26799. indexLast = (idx[p + 1] - 1) * 3;
  26800. }
  26801. else {
  26802. indexLast = normals.length - 3;
  26803. }
  26804. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  26805. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  26806. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  26807. normals[indexLast] = normals[indexFirst];
  26808. normals[indexLast + 1] = normals[indexFirst + 1];
  26809. normals[indexLast + 2] = normals[indexFirst + 2];
  26810. }
  26811. }
  26812. // sides
  26813. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26814. // Colors
  26815. if (customColors) {
  26816. var colors = new Float32Array(customColors.length * 4);
  26817. for (var c = 0; c < customColors.length; c++) {
  26818. colors[c * 4] = customColors[c].r;
  26819. colors[c * 4 + 1] = customColors[c].g;
  26820. colors[c * 4 + 2] = customColors[c].b;
  26821. colors[c * 4 + 3] = customColors[c].a;
  26822. }
  26823. }
  26824. // Result
  26825. var vertexData = new VertexData();
  26826. var positions32 = new Float32Array(positions);
  26827. var normals32 = new Float32Array(normals);
  26828. var uvs32 = new Float32Array(uvs);
  26829. vertexData.indices = indices;
  26830. vertexData.positions = positions32;
  26831. vertexData.normals = normals32;
  26832. vertexData.uvs = uvs32;
  26833. if (customColors) {
  26834. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  26835. }
  26836. if (closePath) {
  26837. vertexData._idx = idx;
  26838. }
  26839. return vertexData;
  26840. };
  26841. /**
  26842. * Creates the VertexData of the Box.
  26843. */
  26844. VertexData.CreateBox = function (options) {
  26845. var normalsSource = [
  26846. new BABYLON.Vector3(0, 0, 1),
  26847. new BABYLON.Vector3(0, 0, -1),
  26848. new BABYLON.Vector3(1, 0, 0),
  26849. new BABYLON.Vector3(-1, 0, 0),
  26850. new BABYLON.Vector3(0, 1, 0),
  26851. new BABYLON.Vector3(0, -1, 0)
  26852. ];
  26853. var indices = [];
  26854. var positions = [];
  26855. var normals = [];
  26856. var uvs = [];
  26857. var width = options.width || options.size || 1;
  26858. var height = options.height || options.size || 1;
  26859. var depth = options.depth || options.size || 1;
  26860. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26861. var faceUV = options.faceUV || new Array(6);
  26862. var faceColors = options.faceColors;
  26863. var colors = [];
  26864. // default face colors and UV if undefined
  26865. for (var f = 0; f < 6; f++) {
  26866. if (faceUV[f] === undefined) {
  26867. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  26868. }
  26869. if (faceColors && faceColors[f] === undefined) {
  26870. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  26871. }
  26872. }
  26873. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  26874. // Create each face in turn.
  26875. for (var index = 0; index < normalsSource.length; index++) {
  26876. var normal = normalsSource[index];
  26877. // Get two vectors perpendicular to the face normal and to each other.
  26878. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  26879. var side2 = BABYLON.Vector3.Cross(normal, side1);
  26880. // Six indices (two triangles) per face.
  26881. var verticesLength = positions.length / 3;
  26882. indices.push(verticesLength);
  26883. indices.push(verticesLength + 1);
  26884. indices.push(verticesLength + 2);
  26885. indices.push(verticesLength);
  26886. indices.push(verticesLength + 2);
  26887. indices.push(verticesLength + 3);
  26888. // Four vertices per face.
  26889. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  26890. positions.push(vertex.x, vertex.y, vertex.z);
  26891. normals.push(normal.x, normal.y, normal.z);
  26892. uvs.push(faceUV[index].z, faceUV[index].w);
  26893. if (faceColors) {
  26894. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26895. }
  26896. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  26897. positions.push(vertex.x, vertex.y, vertex.z);
  26898. normals.push(normal.x, normal.y, normal.z);
  26899. uvs.push(faceUV[index].x, faceUV[index].w);
  26900. if (faceColors) {
  26901. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26902. }
  26903. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  26904. positions.push(vertex.x, vertex.y, vertex.z);
  26905. normals.push(normal.x, normal.y, normal.z);
  26906. uvs.push(faceUV[index].x, faceUV[index].y);
  26907. if (faceColors) {
  26908. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26909. }
  26910. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  26911. positions.push(vertex.x, vertex.y, vertex.z);
  26912. normals.push(normal.x, normal.y, normal.z);
  26913. uvs.push(faceUV[index].z, faceUV[index].y);
  26914. if (faceColors) {
  26915. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  26916. }
  26917. }
  26918. // sides
  26919. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26920. // Result
  26921. var vertexData = new VertexData();
  26922. vertexData.indices = indices;
  26923. vertexData.positions = positions;
  26924. vertexData.normals = normals;
  26925. vertexData.uvs = uvs;
  26926. if (faceColors) {
  26927. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  26928. vertexData.colors = totalColors;
  26929. }
  26930. return vertexData;
  26931. };
  26932. /**
  26933. * Creates the VertexData of the Sphere.
  26934. */
  26935. VertexData.CreateSphere = function (options) {
  26936. var segments = options.segments || 32;
  26937. var diameterX = options.diameterX || options.diameter || 1;
  26938. var diameterY = options.diameterY || options.diameter || 1;
  26939. var diameterZ = options.diameterZ || options.diameter || 1;
  26940. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  26941. var slice = (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  26942. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  26943. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  26944. var totalZRotationSteps = 2 + segments;
  26945. var totalYRotationSteps = 2 * totalZRotationSteps;
  26946. var indices = [];
  26947. var positions = [];
  26948. var normals = [];
  26949. var uvs = [];
  26950. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  26951. var normalizedZ = zRotationStep / totalZRotationSteps;
  26952. var angleZ = normalizedZ * Math.PI * slice;
  26953. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  26954. var normalizedY = yRotationStep / totalYRotationSteps;
  26955. var angleY = normalizedY * Math.PI * 2 * arc;
  26956. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  26957. var rotationY = BABYLON.Matrix.RotationY(angleY);
  26958. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  26959. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  26960. var vertex = complete.multiply(radius);
  26961. var normal = complete.divide(radius).normalize();
  26962. positions.push(vertex.x, vertex.y, vertex.z);
  26963. normals.push(normal.x, normal.y, normal.z);
  26964. uvs.push(normalizedY, normalizedZ);
  26965. }
  26966. if (zRotationStep > 0) {
  26967. var verticesCount = positions.length / 3;
  26968. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  26969. indices.push((firstIndex));
  26970. indices.push((firstIndex + 1));
  26971. indices.push(firstIndex + totalYRotationSteps + 1);
  26972. indices.push((firstIndex + totalYRotationSteps + 1));
  26973. indices.push((firstIndex + 1));
  26974. indices.push((firstIndex + totalYRotationSteps + 2));
  26975. }
  26976. }
  26977. }
  26978. // Sides
  26979. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  26980. // Result
  26981. var vertexData = new VertexData();
  26982. vertexData.indices = indices;
  26983. vertexData.positions = positions;
  26984. vertexData.normals = normals;
  26985. vertexData.uvs = uvs;
  26986. return vertexData;
  26987. };
  26988. /**
  26989. * Creates the VertexData of the Cylinder or Cone.
  26990. */
  26991. VertexData.CreateCylinder = function (options) {
  26992. var height = options.height || 2;
  26993. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  26994. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  26995. var tessellation = options.tessellation || 24;
  26996. var subdivisions = options.subdivisions || 1;
  26997. var hasRings = options.hasRings;
  26998. var enclose = options.enclose;
  26999. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27000. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27001. var faceUV = options.faceUV || new Array(3);
  27002. var faceColors = options.faceColors;
  27003. // default face colors and UV if undefined
  27004. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  27005. var ringNb = (hasRings) ? subdivisions : 1;
  27006. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  27007. var f;
  27008. for (f = 0; f < surfaceNb; f++) {
  27009. if (faceColors && faceColors[f] === undefined) {
  27010. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27011. }
  27012. }
  27013. for (f = 0; f < surfaceNb; f++) {
  27014. if (faceUV && faceUV[f] === undefined) {
  27015. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27016. }
  27017. }
  27018. var indices = [];
  27019. var positions = [];
  27020. var normals = [];
  27021. var uvs = [];
  27022. var colors = [];
  27023. var angle_step = Math.PI * 2 * arc / tessellation;
  27024. var angle;
  27025. var h;
  27026. var radius;
  27027. var tan = (diameterBottom - diameterTop) / 2 / height;
  27028. var ringVertex = BABYLON.Vector3.Zero();
  27029. var ringNormal = BABYLON.Vector3.Zero();
  27030. var ringFirstVertex = BABYLON.Vector3.Zero();
  27031. var ringFirstNormal = BABYLON.Vector3.Zero();
  27032. var quadNormal = BABYLON.Vector3.Zero();
  27033. var Y = BABYLON.Axis.Y;
  27034. // positions, normals, uvs
  27035. var i;
  27036. var j;
  27037. var r;
  27038. var ringIdx = 1;
  27039. var s = 1; // surface index
  27040. var cs = 0;
  27041. var v = 0;
  27042. for (i = 0; i <= subdivisions; i++) {
  27043. h = i / subdivisions;
  27044. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  27045. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  27046. for (r = 0; r < ringIdx; r++) {
  27047. if (hasRings) {
  27048. s += r;
  27049. }
  27050. if (enclose) {
  27051. s += 2 * r;
  27052. }
  27053. for (j = 0; j <= tessellation; j++) {
  27054. angle = j * angle_step;
  27055. // position
  27056. ringVertex.x = Math.cos(-angle) * radius;
  27057. ringVertex.y = -height / 2 + h * height;
  27058. ringVertex.z = Math.sin(-angle) * radius;
  27059. // normal
  27060. if (diameterTop === 0 && i === subdivisions) {
  27061. // if no top cap, reuse former normals
  27062. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  27063. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  27064. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  27065. }
  27066. else {
  27067. ringNormal.x = ringVertex.x;
  27068. ringNormal.z = ringVertex.z;
  27069. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  27070. ringNormal.normalize();
  27071. }
  27072. // keep first ring vertex values for enclose
  27073. if (j === 0) {
  27074. ringFirstVertex.copyFrom(ringVertex);
  27075. ringFirstNormal.copyFrom(ringNormal);
  27076. }
  27077. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27078. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  27079. if (hasRings) {
  27080. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  27081. }
  27082. else {
  27083. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  27084. }
  27085. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  27086. if (faceColors) {
  27087. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  27088. }
  27089. }
  27090. // if enclose, add four vertices and their dedicated normals
  27091. if (arc !== 1 && enclose) {
  27092. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  27093. positions.push(0, ringVertex.y, 0);
  27094. positions.push(0, ringVertex.y, 0);
  27095. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  27096. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  27097. quadNormal.normalize();
  27098. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27099. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  27100. quadNormal.normalize();
  27101. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  27102. if (hasRings) {
  27103. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  27104. }
  27105. else {
  27106. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  27107. }
  27108. uvs.push(faceUV[s + 1].x, v);
  27109. uvs.push(faceUV[s + 1].z, v);
  27110. if (hasRings) {
  27111. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  27112. }
  27113. else {
  27114. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  27115. }
  27116. uvs.push(faceUV[s + 2].x, v);
  27117. uvs.push(faceUV[s + 2].z, v);
  27118. if (faceColors) {
  27119. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27120. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  27121. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27122. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  27123. }
  27124. }
  27125. if (cs !== s) {
  27126. cs = s;
  27127. }
  27128. }
  27129. }
  27130. // indices
  27131. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  27132. var s;
  27133. i = 0;
  27134. for (s = 0; s < subdivisions; s++) {
  27135. for (j = 0; j < tessellation; j++) {
  27136. var i0 = i * (e + 1) + j;
  27137. var i1 = (i + 1) * (e + 1) + j;
  27138. var i2 = i * (e + 1) + (j + 1);
  27139. var i3 = (i + 1) * (e + 1) + (j + 1);
  27140. indices.push(i0, i1, i2);
  27141. indices.push(i3, i2, i1);
  27142. }
  27143. if (arc !== 1 && enclose) {
  27144. indices.push(i0 + 2, i1 + 2, i2 + 2);
  27145. indices.push(i3 + 2, i2 + 2, i1 + 2);
  27146. indices.push(i0 + 4, i1 + 4, i2 + 4);
  27147. indices.push(i3 + 4, i2 + 4, i1 + 4);
  27148. }
  27149. i = (hasRings) ? (i + 2) : (i + 1);
  27150. }
  27151. // Caps
  27152. var createCylinderCap = function (isTop) {
  27153. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  27154. if (radius === 0) {
  27155. return;
  27156. }
  27157. // Cap positions, normals & uvs
  27158. var angle;
  27159. var circleVector;
  27160. var i;
  27161. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  27162. var c;
  27163. if (faceColors) {
  27164. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  27165. }
  27166. // cap center
  27167. var vbase = positions.length / 3;
  27168. var offset = isTop ? height / 2 : -height / 2;
  27169. var center = new BABYLON.Vector3(0, offset, 0);
  27170. positions.push(center.x, center.y, center.z);
  27171. normals.push(0, isTop ? 1 : -1, 0);
  27172. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  27173. if (faceColors) {
  27174. colors.push(c.r, c.g, c.b, c.a);
  27175. }
  27176. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  27177. for (i = 0; i <= tessellation; i++) {
  27178. angle = Math.PI * 2 * i * arc / tessellation;
  27179. var cos = Math.cos(-angle);
  27180. var sin = Math.sin(-angle);
  27181. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  27182. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  27183. positions.push(circleVector.x, circleVector.y, circleVector.z);
  27184. normals.push(0, isTop ? 1 : -1, 0);
  27185. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  27186. if (faceColors) {
  27187. colors.push(c.r, c.g, c.b, c.a);
  27188. }
  27189. }
  27190. // Cap indices
  27191. for (i = 0; i < tessellation; i++) {
  27192. if (!isTop) {
  27193. indices.push(vbase);
  27194. indices.push(vbase + (i + 1));
  27195. indices.push(vbase + (i + 2));
  27196. }
  27197. else {
  27198. indices.push(vbase);
  27199. indices.push(vbase + (i + 2));
  27200. indices.push(vbase + (i + 1));
  27201. }
  27202. }
  27203. };
  27204. // add caps to geometry
  27205. createCylinderCap(false);
  27206. createCylinderCap(true);
  27207. // Sides
  27208. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27209. var vertexData = new VertexData();
  27210. vertexData.indices = indices;
  27211. vertexData.positions = positions;
  27212. vertexData.normals = normals;
  27213. vertexData.uvs = uvs;
  27214. if (faceColors) {
  27215. vertexData.colors = colors;
  27216. }
  27217. return vertexData;
  27218. };
  27219. /**
  27220. * Creates the VertexData of the Torus.
  27221. */
  27222. VertexData.CreateTorus = function (options) {
  27223. var indices = [];
  27224. var positions = [];
  27225. var normals = [];
  27226. var uvs = [];
  27227. var diameter = options.diameter || 1;
  27228. var thickness = options.thickness || 0.5;
  27229. var tessellation = options.tessellation || 16;
  27230. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27231. var stride = tessellation + 1;
  27232. for (var i = 0; i <= tessellation; i++) {
  27233. var u = i / tessellation;
  27234. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  27235. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  27236. for (var j = 0; j <= tessellation; j++) {
  27237. var v = 1 - j / tessellation;
  27238. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  27239. var dx = Math.cos(innerAngle);
  27240. var dy = Math.sin(innerAngle);
  27241. // Create a vertex.
  27242. var normal = new BABYLON.Vector3(dx, dy, 0);
  27243. var position = normal.scale(thickness / 2);
  27244. var textureCoordinate = new BABYLON.Vector2(u, v);
  27245. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  27246. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  27247. positions.push(position.x, position.y, position.z);
  27248. normals.push(normal.x, normal.y, normal.z);
  27249. uvs.push(textureCoordinate.x, textureCoordinate.y);
  27250. // And create indices for two triangles.
  27251. var nextI = (i + 1) % stride;
  27252. var nextJ = (j + 1) % stride;
  27253. indices.push(i * stride + j);
  27254. indices.push(i * stride + nextJ);
  27255. indices.push(nextI * stride + j);
  27256. indices.push(i * stride + nextJ);
  27257. indices.push(nextI * stride + nextJ);
  27258. indices.push(nextI * stride + j);
  27259. }
  27260. }
  27261. // Sides
  27262. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27263. // Result
  27264. var vertexData = new VertexData();
  27265. vertexData.indices = indices;
  27266. vertexData.positions = positions;
  27267. vertexData.normals = normals;
  27268. vertexData.uvs = uvs;
  27269. return vertexData;
  27270. };
  27271. /**
  27272. * Creates the VertexData of the LineSystem.
  27273. */
  27274. VertexData.CreateLineSystem = function (options) {
  27275. var indices = [];
  27276. var positions = [];
  27277. var lines = options.lines;
  27278. var idx = 0;
  27279. for (var l = 0; l < lines.length; l++) {
  27280. var points = lines[l];
  27281. for (var index = 0; index < points.length; index++) {
  27282. positions.push(points[index].x, points[index].y, points[index].z);
  27283. if (index > 0) {
  27284. indices.push(idx - 1);
  27285. indices.push(idx);
  27286. }
  27287. idx++;
  27288. }
  27289. }
  27290. var vertexData = new VertexData();
  27291. vertexData.indices = indices;
  27292. vertexData.positions = positions;
  27293. return vertexData;
  27294. };
  27295. /**
  27296. * Create the VertexData of the DashedLines.
  27297. */
  27298. VertexData.CreateDashedLines = function (options) {
  27299. var dashSize = options.dashSize || 3;
  27300. var gapSize = options.gapSize || 1;
  27301. var dashNb = options.dashNb || 200;
  27302. var points = options.points;
  27303. var positions = new Array();
  27304. var indices = new Array();
  27305. var curvect = BABYLON.Vector3.Zero();
  27306. var lg = 0;
  27307. var nb = 0;
  27308. var shft = 0;
  27309. var dashshft = 0;
  27310. var curshft = 0;
  27311. var idx = 0;
  27312. var i = 0;
  27313. for (i = 0; i < points.length - 1; i++) {
  27314. points[i + 1].subtractToRef(points[i], curvect);
  27315. lg += curvect.length();
  27316. }
  27317. shft = lg / dashNb;
  27318. dashshft = dashSize * shft / (dashSize + gapSize);
  27319. for (i = 0; i < points.length - 1; i++) {
  27320. points[i + 1].subtractToRef(points[i], curvect);
  27321. nb = Math.floor(curvect.length() / shft);
  27322. curvect.normalize();
  27323. for (var j = 0; j < nb; j++) {
  27324. curshft = shft * j;
  27325. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  27326. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  27327. indices.push(idx, idx + 1);
  27328. idx += 2;
  27329. }
  27330. }
  27331. // Result
  27332. var vertexData = new VertexData();
  27333. vertexData.positions = positions;
  27334. vertexData.indices = indices;
  27335. return vertexData;
  27336. };
  27337. /**
  27338. * Creates the VertexData of the Ground.
  27339. */
  27340. VertexData.CreateGround = function (options) {
  27341. var indices = [];
  27342. var positions = [];
  27343. var normals = [];
  27344. var uvs = [];
  27345. var row, col;
  27346. var width = options.width || 1;
  27347. var height = options.height || 1;
  27348. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  27349. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  27350. for (row = 0; row <= subdivisionsY; row++) {
  27351. for (col = 0; col <= subdivisionsX; col++) {
  27352. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  27353. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27354. positions.push(position.x, position.y, position.z);
  27355. normals.push(normal.x, normal.y, normal.z);
  27356. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  27357. }
  27358. }
  27359. for (row = 0; row < subdivisionsY; row++) {
  27360. for (col = 0; col < subdivisionsX; col++) {
  27361. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27362. indices.push(col + 1 + row * (subdivisionsX + 1));
  27363. indices.push(col + row * (subdivisionsX + 1));
  27364. indices.push(col + (row + 1) * (subdivisionsX + 1));
  27365. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  27366. indices.push(col + row * (subdivisionsX + 1));
  27367. }
  27368. }
  27369. // Result
  27370. var vertexData = new VertexData();
  27371. vertexData.indices = indices;
  27372. vertexData.positions = positions;
  27373. vertexData.normals = normals;
  27374. vertexData.uvs = uvs;
  27375. return vertexData;
  27376. };
  27377. /**
  27378. * Creates the VertexData of the TiledGround.
  27379. */
  27380. VertexData.CreateTiledGround = function (options) {
  27381. var xmin = options.xmin || -1.0;
  27382. var zmin = options.zmin || -1.0;
  27383. var xmax = options.xmax || 1.0;
  27384. var zmax = options.zmax || 1.0;
  27385. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  27386. var precision = options.precision || { w: 1, h: 1 };
  27387. var indices = [];
  27388. var positions = [];
  27389. var normals = [];
  27390. var uvs = [];
  27391. var row, col, tileRow, tileCol;
  27392. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  27393. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  27394. precision.w = (precision.w < 1) ? 1 : precision.w;
  27395. precision.h = (precision.h < 1) ? 1 : precision.h;
  27396. var tileSize = {
  27397. 'w': (xmax - xmin) / subdivisions.w,
  27398. 'h': (zmax - zmin) / subdivisions.h
  27399. };
  27400. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  27401. // Indices
  27402. var base = positions.length / 3;
  27403. var rowLength = precision.w + 1;
  27404. for (row = 0; row < precision.h; row++) {
  27405. for (col = 0; col < precision.w; col++) {
  27406. var square = [
  27407. base + col + row * rowLength,
  27408. base + (col + 1) + row * rowLength,
  27409. base + (col + 1) + (row + 1) * rowLength,
  27410. base + col + (row + 1) * rowLength
  27411. ];
  27412. indices.push(square[1]);
  27413. indices.push(square[2]);
  27414. indices.push(square[3]);
  27415. indices.push(square[0]);
  27416. indices.push(square[1]);
  27417. indices.push(square[3]);
  27418. }
  27419. }
  27420. // Position, normals and uvs
  27421. var position = BABYLON.Vector3.Zero();
  27422. var normal = new BABYLON.Vector3(0, 1.0, 0);
  27423. for (row = 0; row <= precision.h; row++) {
  27424. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  27425. for (col = 0; col <= precision.w; col++) {
  27426. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  27427. position.y = 0;
  27428. positions.push(position.x, position.y, position.z);
  27429. normals.push(normal.x, normal.y, normal.z);
  27430. uvs.push(col / precision.w, row / precision.h);
  27431. }
  27432. }
  27433. }
  27434. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  27435. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  27436. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  27437. }
  27438. }
  27439. // Result
  27440. var vertexData = new VertexData();
  27441. vertexData.indices = indices;
  27442. vertexData.positions = positions;
  27443. vertexData.normals = normals;
  27444. vertexData.uvs = uvs;
  27445. return vertexData;
  27446. };
  27447. /**
  27448. * Creates the VertexData of the Ground designed from a heightmap.
  27449. */
  27450. VertexData.CreateGroundFromHeightMap = function (options) {
  27451. var indices = [];
  27452. var positions = [];
  27453. var normals = [];
  27454. var uvs = [];
  27455. var row, col;
  27456. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  27457. // Vertices
  27458. for (row = 0; row <= options.subdivisions; row++) {
  27459. for (col = 0; col <= options.subdivisions; col++) {
  27460. 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));
  27461. // Compute height
  27462. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  27463. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  27464. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  27465. var r = options.buffer[pos] / 255.0;
  27466. var g = options.buffer[pos + 1] / 255.0;
  27467. var b = options.buffer[pos + 2] / 255.0;
  27468. var gradient = r * filter.r + g * filter.g + b * filter.b;
  27469. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  27470. // Add vertex
  27471. positions.push(position.x, position.y, position.z);
  27472. normals.push(0, 0, 0);
  27473. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  27474. }
  27475. }
  27476. // Indices
  27477. for (row = 0; row < options.subdivisions; row++) {
  27478. for (col = 0; col < options.subdivisions; col++) {
  27479. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27480. indices.push(col + 1 + row * (options.subdivisions + 1));
  27481. indices.push(col + row * (options.subdivisions + 1));
  27482. indices.push(col + (row + 1) * (options.subdivisions + 1));
  27483. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  27484. indices.push(col + row * (options.subdivisions + 1));
  27485. }
  27486. }
  27487. // Normals
  27488. VertexData.ComputeNormals(positions, indices, normals);
  27489. // Result
  27490. var vertexData = new VertexData();
  27491. vertexData.indices = indices;
  27492. vertexData.positions = positions;
  27493. vertexData.normals = normals;
  27494. vertexData.uvs = uvs;
  27495. return vertexData;
  27496. };
  27497. /**
  27498. * Creates the VertexData of the Plane.
  27499. */
  27500. VertexData.CreatePlane = function (options) {
  27501. var indices = [];
  27502. var positions = [];
  27503. var normals = [];
  27504. var uvs = [];
  27505. var width = options.width || options.size || 1;
  27506. var height = options.height || options.size || 1;
  27507. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27508. // Vertices
  27509. var halfWidth = width / 2.0;
  27510. var halfHeight = height / 2.0;
  27511. positions.push(-halfWidth, -halfHeight, 0);
  27512. normals.push(0, 0, -1.0);
  27513. uvs.push(0.0, 0.0);
  27514. positions.push(halfWidth, -halfHeight, 0);
  27515. normals.push(0, 0, -1.0);
  27516. uvs.push(1.0, 0.0);
  27517. positions.push(halfWidth, halfHeight, 0);
  27518. normals.push(0, 0, -1.0);
  27519. uvs.push(1.0, 1.0);
  27520. positions.push(-halfWidth, halfHeight, 0);
  27521. normals.push(0, 0, -1.0);
  27522. uvs.push(0.0, 1.0);
  27523. // Indices
  27524. indices.push(0);
  27525. indices.push(1);
  27526. indices.push(2);
  27527. indices.push(0);
  27528. indices.push(2);
  27529. indices.push(3);
  27530. // Sides
  27531. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27532. // Result
  27533. var vertexData = new VertexData();
  27534. vertexData.indices = indices;
  27535. vertexData.positions = positions;
  27536. vertexData.normals = normals;
  27537. vertexData.uvs = uvs;
  27538. return vertexData;
  27539. };
  27540. /**
  27541. * Creates the VertexData of the Disc or regular Polygon.
  27542. */
  27543. VertexData.CreateDisc = function (options) {
  27544. var positions = [];
  27545. var indices = [];
  27546. var normals = [];
  27547. var uvs = [];
  27548. var radius = options.radius || 0.5;
  27549. var tessellation = options.tessellation || 64;
  27550. var arc = (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  27551. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27552. // positions and uvs
  27553. positions.push(0, 0, 0); // disc center first
  27554. uvs.push(0.5, 0.5);
  27555. var theta = Math.PI * 2 * arc;
  27556. var step = theta / tessellation;
  27557. for (var a = 0; a < theta; a += step) {
  27558. var x = Math.cos(a);
  27559. var y = Math.sin(a);
  27560. var u = (x + 1) / 2;
  27561. var v = (1 - y) / 2;
  27562. positions.push(radius * x, radius * y, 0);
  27563. uvs.push(u, v);
  27564. }
  27565. if (arc === 1) {
  27566. positions.push(positions[3], positions[4], positions[5]); // close the circle
  27567. uvs.push(uvs[2], uvs[3]);
  27568. }
  27569. //indices
  27570. var vertexNb = positions.length / 3;
  27571. for (var i = 1; i < vertexNb - 1; i++) {
  27572. indices.push(i + 1, 0, i);
  27573. }
  27574. // result
  27575. VertexData.ComputeNormals(positions, indices, normals);
  27576. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27577. var vertexData = new VertexData();
  27578. vertexData.indices = indices;
  27579. vertexData.positions = positions;
  27580. vertexData.normals = normals;
  27581. vertexData.uvs = uvs;
  27582. return vertexData;
  27583. };
  27584. /**
  27585. * Re-creates the VertexData of the Polygon for sideOrientation.
  27586. */
  27587. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  27588. var faceUV = fUV || new Array(3);
  27589. var faceColors = fColors;
  27590. var colors = [];
  27591. // default face colors and UV if undefined
  27592. for (var f = 0; f < 3; f++) {
  27593. if (faceUV[f] === undefined) {
  27594. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27595. }
  27596. if (faceColors && faceColors[f] === undefined) {
  27597. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27598. }
  27599. }
  27600. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  27601. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  27602. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  27603. var indices = polygon.getIndices();
  27604. // set face colours and textures
  27605. var idx = 0;
  27606. var face = 0;
  27607. for (var index = 0; index < normals.length; index += 3) {
  27608. //Edge Face no. 1
  27609. if (Math.abs(normals[index + 1]) < 0.001) {
  27610. face = 1;
  27611. }
  27612. //Top Face no. 0
  27613. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  27614. face = 0;
  27615. }
  27616. //Bottom Face no. 2
  27617. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  27618. face = 2;
  27619. }
  27620. idx = index / 3;
  27621. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  27622. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  27623. if (faceColors) {
  27624. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  27625. }
  27626. }
  27627. // sides
  27628. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  27629. // Result
  27630. var vertexData = new VertexData();
  27631. vertexData.indices = indices;
  27632. vertexData.positions = positions;
  27633. vertexData.normals = normals;
  27634. vertexData.uvs = uvs;
  27635. if (faceColors) {
  27636. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  27637. vertexData.colors = totalColors;
  27638. }
  27639. return vertexData;
  27640. };
  27641. /**
  27642. * Creates the VertexData of the IcoSphere.
  27643. */
  27644. VertexData.CreateIcoSphere = function (options) {
  27645. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27646. var radius = options.radius || 1;
  27647. var flat = (options.flat === undefined) ? true : options.flat;
  27648. var subdivisions = options.subdivisions || 4;
  27649. var radiusX = options.radiusX || radius;
  27650. var radiusY = options.radiusY || radius;
  27651. var radiusZ = options.radiusZ || radius;
  27652. var t = (1 + Math.sqrt(5)) / 2;
  27653. // 12 vertex x,y,z
  27654. var ico_vertices = [
  27655. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  27656. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  27657. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  27658. ];
  27659. // index of 3 vertex makes a face of icopshere
  27660. var ico_indices = [
  27661. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  27662. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  27663. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  27664. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  27665. ];
  27666. // vertex for uv have aliased position, not for UV
  27667. var vertices_unalias_id = [
  27668. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  27669. // vertex alias
  27670. 0,
  27671. 2,
  27672. 3,
  27673. 3,
  27674. 3,
  27675. 4,
  27676. 7,
  27677. 8,
  27678. 9,
  27679. 9,
  27680. 10,
  27681. 11 // 23: B + 12
  27682. ];
  27683. // uv as integer step (not pixels !)
  27684. var ico_vertexuv = [
  27685. 5, 1, 3, 1, 6, 4, 0, 0,
  27686. 5, 3, 4, 2, 2, 2, 4, 0,
  27687. 2, 0, 1, 1, 6, 0, 6, 2,
  27688. // vertex alias (for same vertex on different faces)
  27689. 0, 4,
  27690. 3, 3,
  27691. 4, 4,
  27692. 3, 1,
  27693. 4, 2,
  27694. 4, 4,
  27695. 0, 2,
  27696. 1, 1,
  27697. 2, 2,
  27698. 3, 3,
  27699. 1, 3,
  27700. 2, 4 // 23: B + 12
  27701. ];
  27702. // Vertices[0, 1, ...9, A, B] : position on UV plane
  27703. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  27704. // First island of uv mapping
  27705. // v = 4h 3+ 2
  27706. // v = 3h 9+ 4
  27707. // v = 2h 9+ 5 B
  27708. // v = 1h 9 1 0
  27709. // v = 0h 3 8 7 A
  27710. // u = 0 1 2 3 4 5 6 *a
  27711. // Second island of uv mapping
  27712. // v = 4h 0+ B+ 4+
  27713. // v = 3h A+ 2+
  27714. // v = 2h 7+ 6 3+
  27715. // v = 1h 8+ 3+
  27716. // v = 0h
  27717. // u = 0 1 2 3 4 5 6 *a
  27718. // Face layout on texture UV mapping
  27719. // ============
  27720. // \ 4 /\ 16 / ======
  27721. // \ / \ / /\ 11 /
  27722. // \/ 7 \/ / \ /
  27723. // ======= / 10 \/
  27724. // /\ 17 /\ =======
  27725. // / \ / \ \ 15 /\
  27726. // / 8 \/ 12 \ \ / \
  27727. // ============ \/ 6 \
  27728. // \ 18 /\ ============
  27729. // \ / \ \ 5 /\ 0 /
  27730. // \/ 13 \ \ / \ /
  27731. // ======= \/ 1 \/
  27732. // =============
  27733. // /\ 19 /\ 2 /\
  27734. // / \ / \ / \
  27735. // / 14 \/ 9 \/ 3 \
  27736. // ===================
  27737. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  27738. var ustep = 138 / 1024;
  27739. var vstep = 239 / 1024;
  27740. var uoffset = 60 / 1024;
  27741. var voffset = 26 / 1024;
  27742. // Second island should have margin, not to touch the first island
  27743. // avoid any borderline artefact in pixel rounding
  27744. var island_u_offset = -40 / 1024;
  27745. var island_v_offset = +20 / 1024;
  27746. // face is either island 0 or 1 :
  27747. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  27748. var island = [
  27749. 0, 0, 0, 0, 1,
  27750. 0, 0, 1, 1, 0,
  27751. 0, 0, 1, 1, 0,
  27752. 0, 1, 1, 1, 0 // 15 - 19
  27753. ];
  27754. var indices = [];
  27755. var positions = [];
  27756. var normals = [];
  27757. var uvs = [];
  27758. var current_indice = 0;
  27759. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  27760. var face_vertex_pos = new Array(3);
  27761. var face_vertex_uv = new Array(3);
  27762. var v012;
  27763. for (v012 = 0; v012 < 3; v012++) {
  27764. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  27765. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  27766. }
  27767. // create all with normals
  27768. for (var face = 0; face < 20; face++) {
  27769. // 3 vertex per face
  27770. for (v012 = 0; v012 < 3; v012++) {
  27771. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  27772. var v_id = ico_indices[3 * face + v012];
  27773. // vertex have 3D position (x,y,z)
  27774. 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]);
  27775. // Normalize to get normal, then scale to radius
  27776. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  27777. // uv Coordinates from vertex ID
  27778. 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);
  27779. }
  27780. // Subdivide the face (interpolate pos, norm, uv)
  27781. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  27782. // - norm is linear interpolation of vertex corner normal
  27783. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  27784. // - uv is linear interpolation
  27785. //
  27786. // Topology is as below for sub-divide by 2
  27787. // vertex shown as v0,v1,v2
  27788. // interp index is i1 to progress in range [v0,v1[
  27789. // interp index is i2 to progress in range [v0,v2[
  27790. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  27791. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27792. //
  27793. //
  27794. // i2 v2
  27795. // ^ ^
  27796. // / / \
  27797. // / / \
  27798. // / / \
  27799. // / / (0,1) \
  27800. // / #---------\
  27801. // / / \ (0,0)'/ \
  27802. // / / \ / \
  27803. // / / \ / \
  27804. // / / (0,0) \ / (1,0) \
  27805. // / #---------#---------\
  27806. // v0 v1
  27807. //
  27808. // --------------------> i1
  27809. //
  27810. // interp of (i1,i2):
  27811. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  27812. // along i1 : lerp(x0,x1, i1/(S-i2))
  27813. //
  27814. // centroid of triangle is needed to get help normal computation
  27815. // (c1,c2) are used for centroid location
  27816. var interp_vertex = function (i1, i2, c1, c2) {
  27817. // vertex is interpolated from
  27818. // - face_vertex_pos[0..2]
  27819. // - face_vertex_uv[0..2]
  27820. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  27821. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  27822. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  27823. pos_interp.normalize();
  27824. var vertex_normal;
  27825. if (flat) {
  27826. // in flat mode, recalculate normal as face centroid normal
  27827. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  27828. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  27829. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  27830. }
  27831. else {
  27832. // in smooth mode, recalculate normal from each single vertex position
  27833. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  27834. }
  27835. // Vertex normal need correction due to X,Y,Z radius scaling
  27836. vertex_normal.x /= radiusX;
  27837. vertex_normal.y /= radiusY;
  27838. vertex_normal.z /= radiusZ;
  27839. vertex_normal.normalize();
  27840. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  27841. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  27842. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  27843. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  27844. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  27845. uvs.push(uv_interp.x, uv_interp.y);
  27846. // push each vertex has member of a face
  27847. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  27848. indices.push(current_indice);
  27849. current_indice++;
  27850. };
  27851. for (var i2 = 0; i2 < subdivisions; i2++) {
  27852. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  27853. // face : (i1,i2) for /\ :
  27854. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  27855. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27856. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27857. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  27858. if (i1 + i2 + 1 < subdivisions) {
  27859. // face : (i1,i2)' for \/ :
  27860. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  27861. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27862. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27863. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  27864. }
  27865. }
  27866. }
  27867. }
  27868. // Sides
  27869. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27870. // Result
  27871. var vertexData = new VertexData();
  27872. vertexData.indices = indices;
  27873. vertexData.positions = positions;
  27874. vertexData.normals = normals;
  27875. vertexData.uvs = uvs;
  27876. return vertexData;
  27877. };
  27878. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  27879. /**
  27880. * Creates the VertexData of the Polyhedron.
  27881. */
  27882. VertexData.CreatePolyhedron = function (options) {
  27883. // provided polyhedron types :
  27884. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  27885. // 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)
  27886. var polyhedra = [];
  27887. 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]] };
  27888. 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]] };
  27889. polyhedra[2] = {
  27890. 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]],
  27891. 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]]
  27892. };
  27893. polyhedra[3] = {
  27894. 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]],
  27895. 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]]
  27896. };
  27897. polyhedra[4] = {
  27898. 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]],
  27899. 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]]
  27900. };
  27901. 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]] };
  27902. 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]] };
  27903. 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]] };
  27904. 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]] };
  27905. 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]] };
  27906. 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]] };
  27907. 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]] };
  27908. 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]] };
  27909. 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]] };
  27910. polyhedra[14] = {
  27911. 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]],
  27912. 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]]
  27913. };
  27914. var type = (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  27915. var size = options.size;
  27916. var sizeX = options.sizeX || size || 1;
  27917. var sizeY = options.sizeY || size || 1;
  27918. var sizeZ = options.sizeZ || size || 1;
  27919. var data = options.custom || polyhedra[type];
  27920. var nbfaces = data.face.length;
  27921. var faceUV = options.faceUV || new Array(nbfaces);
  27922. var faceColors = options.faceColors;
  27923. var flat = (options.flat === undefined) ? true : options.flat;
  27924. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  27925. var positions = [];
  27926. var indices = [];
  27927. var normals = [];
  27928. var uvs = [];
  27929. var colors = [];
  27930. var index = 0;
  27931. var faceIdx = 0; // face cursor in the array "indexes"
  27932. var indexes = [];
  27933. var i = 0;
  27934. var f = 0;
  27935. var u, v, ang, x, y, tmp;
  27936. // default face colors and UV if undefined
  27937. if (flat) {
  27938. for (f = 0; f < nbfaces; f++) {
  27939. if (faceColors && faceColors[f] === undefined) {
  27940. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  27941. }
  27942. if (faceUV && faceUV[f] === undefined) {
  27943. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  27944. }
  27945. }
  27946. }
  27947. if (!flat) {
  27948. for (i = 0; i < data.vertex.length; i++) {
  27949. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  27950. uvs.push(0, 0);
  27951. }
  27952. for (f = 0; f < nbfaces; f++) {
  27953. for (i = 0; i < data.face[f].length - 2; i++) {
  27954. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  27955. }
  27956. }
  27957. }
  27958. else {
  27959. for (f = 0; f < nbfaces; f++) {
  27960. var fl = data.face[f].length; // number of vertices of the current face
  27961. ang = 2 * Math.PI / fl;
  27962. x = 0.5 * Math.tan(ang / 2);
  27963. y = 0.5;
  27964. // positions, uvs, colors
  27965. for (i = 0; i < fl; i++) {
  27966. // positions
  27967. 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);
  27968. indexes.push(index);
  27969. index++;
  27970. // uvs
  27971. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  27972. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  27973. uvs.push(u, v);
  27974. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  27975. y = x * Math.sin(ang) + y * Math.cos(ang);
  27976. x = tmp;
  27977. // colors
  27978. if (faceColors) {
  27979. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  27980. }
  27981. }
  27982. // indices from indexes
  27983. for (i = 0; i < fl - 2; i++) {
  27984. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  27985. }
  27986. faceIdx += fl;
  27987. }
  27988. }
  27989. VertexData.ComputeNormals(positions, indices, normals);
  27990. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  27991. var vertexData = new VertexData();
  27992. vertexData.positions = positions;
  27993. vertexData.indices = indices;
  27994. vertexData.normals = normals;
  27995. vertexData.uvs = uvs;
  27996. if (faceColors && flat) {
  27997. vertexData.colors = colors;
  27998. }
  27999. return vertexData;
  28000. };
  28001. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  28002. /**
  28003. * Creates the VertexData of the Torus Knot.
  28004. */
  28005. VertexData.CreateTorusKnot = function (options) {
  28006. var indices = [];
  28007. var positions = [];
  28008. var normals = [];
  28009. var uvs = [];
  28010. var radius = options.radius || 2;
  28011. var tube = options.tube || 0.5;
  28012. var radialSegments = options.radialSegments || 32;
  28013. var tubularSegments = options.tubularSegments || 32;
  28014. var p = options.p || 2;
  28015. var q = options.q || 3;
  28016. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28017. // Helper
  28018. var getPos = function (angle) {
  28019. var cu = Math.cos(angle);
  28020. var su = Math.sin(angle);
  28021. var quOverP = q / p * angle;
  28022. var cs = Math.cos(quOverP);
  28023. var tx = radius * (2 + cs) * 0.5 * cu;
  28024. var ty = radius * (2 + cs) * su * 0.5;
  28025. var tz = radius * Math.sin(quOverP) * 0.5;
  28026. return new BABYLON.Vector3(tx, ty, tz);
  28027. };
  28028. // Vertices
  28029. var i;
  28030. var j;
  28031. for (i = 0; i <= radialSegments; i++) {
  28032. var modI = i % radialSegments;
  28033. var u = modI / radialSegments * 2 * p * Math.PI;
  28034. var p1 = getPos(u);
  28035. var p2 = getPos(u + 0.01);
  28036. var tang = p2.subtract(p1);
  28037. var n = p2.add(p1);
  28038. var bitan = BABYLON.Vector3.Cross(tang, n);
  28039. n = BABYLON.Vector3.Cross(bitan, tang);
  28040. bitan.normalize();
  28041. n.normalize();
  28042. for (j = 0; j < tubularSegments; j++) {
  28043. var modJ = j % tubularSegments;
  28044. var v = modJ / tubularSegments * 2 * Math.PI;
  28045. var cx = -tube * Math.cos(v);
  28046. var cy = tube * Math.sin(v);
  28047. positions.push(p1.x + cx * n.x + cy * bitan.x);
  28048. positions.push(p1.y + cx * n.y + cy * bitan.y);
  28049. positions.push(p1.z + cx * n.z + cy * bitan.z);
  28050. uvs.push(i / radialSegments);
  28051. uvs.push(j / tubularSegments);
  28052. }
  28053. }
  28054. for (i = 0; i < radialSegments; i++) {
  28055. for (j = 0; j < tubularSegments; j++) {
  28056. var jNext = (j + 1) % tubularSegments;
  28057. var a = i * tubularSegments + j;
  28058. var b = (i + 1) * tubularSegments + j;
  28059. var c = (i + 1) * tubularSegments + jNext;
  28060. var d = i * tubularSegments + jNext;
  28061. indices.push(d);
  28062. indices.push(b);
  28063. indices.push(a);
  28064. indices.push(d);
  28065. indices.push(c);
  28066. indices.push(b);
  28067. }
  28068. }
  28069. // Normals
  28070. VertexData.ComputeNormals(positions, indices, normals);
  28071. // Sides
  28072. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  28073. // Result
  28074. var vertexData = new VertexData();
  28075. vertexData.indices = indices;
  28076. vertexData.positions = positions;
  28077. vertexData.normals = normals;
  28078. vertexData.uvs = uvs;
  28079. return vertexData;
  28080. };
  28081. // Tools
  28082. /**
  28083. * @param {any} - positions (number[] or Float32Array)
  28084. * @param {any} - indices (number[] or Uint16Array)
  28085. * @param {any} - normals (number[] or Float32Array)
  28086. * options (optional) :
  28087. * facetPositions : optional array of facet positions (vector3)
  28088. * facetNormals : optional array of facet normals (vector3)
  28089. * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  28090. * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  28091. * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  28092. * bbSize : optional bounding box size data, required for facetPartitioning computation
  28093. * bInfo : optional bounding info, required for facetPartitioning computation
  28094. */
  28095. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  28096. // temporary scalar variables
  28097. var index = 0; // facet index
  28098. var p1p2x = 0.0; // p1p2 vector x coordinate
  28099. var p1p2y = 0.0; // p1p2 vector y coordinate
  28100. var p1p2z = 0.0; // p1p2 vector z coordinate
  28101. var p3p2x = 0.0; // p3p2 vector x coordinate
  28102. var p3p2y = 0.0; // p3p2 vector y coordinate
  28103. var p3p2z = 0.0; // p3p2 vector z coordinate
  28104. var faceNormalx = 0.0; // facet normal x coordinate
  28105. var faceNormaly = 0.0; // facet normal y coordinate
  28106. var faceNormalz = 0.0; // facet normal z coordinate
  28107. var length = 0.0; // facet normal length before normalization
  28108. var v1x = 0; // vector1 x index in the positions array
  28109. var v1y = 0; // vector1 y index in the positions array
  28110. var v1z = 0; // vector1 z index in the positions array
  28111. var v2x = 0; // vector2 x index in the positions array
  28112. var v2y = 0; // vector2 y index in the positions array
  28113. var v2z = 0; // vector2 z index in the positions array
  28114. var v3x = 0; // vector3 x index in the positions array
  28115. var v3y = 0; // vector3 y index in the positions array
  28116. var v3z = 0; // vector3 z index in the positions array
  28117. var computeFacetNormals = false;
  28118. var computeFacetPositions = false;
  28119. var computeFacetPartitioning = false;
  28120. var faceNormalSign = 1;
  28121. if (options) {
  28122. computeFacetNormals = (options.facetNormals) ? true : false;
  28123. computeFacetPositions = (options.facetPositions) ? true : false;
  28124. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  28125. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  28126. }
  28127. // facetPartitioning reinit if needed
  28128. if (computeFacetPartitioning) {
  28129. var ox = 0; // X partitioning index for facet position
  28130. var oy = 0; // Y partinioning index for facet position
  28131. var oz = 0; // Z partinioning index for facet position
  28132. var b1x = 0; // X partitioning index for facet v1 vertex
  28133. var b1y = 0; // Y partitioning index for facet v1 vertex
  28134. var b1z = 0; // z partitioning index for facet v1 vertex
  28135. var b2x = 0; // X partitioning index for facet v2 vertex
  28136. var b2y = 0; // Y partitioning index for facet v2 vertex
  28137. var b2z = 0; // Z partitioning index for facet v2 vertex
  28138. var b3x = 0; // X partitioning index for facet v3 vertex
  28139. var b3y = 0; // Y partitioning index for facet v3 vertex
  28140. var b3z = 0; // Z partitioning index for facet v3 vertex
  28141. var block_idx_o = 0; // facet barycenter block index
  28142. var block_idx_v1 = 0; // v1 vertex block index
  28143. var block_idx_v2 = 0; // v2 vertex block index
  28144. var block_idx_v3 = 0; // v3 vertex block index
  28145. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  28146. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  28147. var xSubRatio = options.subDiv.X * options.ratio / options.bbSize.x;
  28148. var ySubRatio = options.subDiv.Y * options.ratio / options.bbSize.y;
  28149. var zSubRatio = options.subDiv.Z * options.ratio / options.bbSize.z;
  28150. var subSq = options.subDiv.max * options.subDiv.max;
  28151. options.facetPartitioning.length = 0;
  28152. }
  28153. // reset the normals
  28154. for (index = 0; index < positions.length; index++) {
  28155. normals[index] = 0.0;
  28156. }
  28157. // Loop : 1 indice triplet = 1 facet
  28158. var nbFaces = indices.length / 3;
  28159. for (index = 0; index < nbFaces; index++) {
  28160. // get the indexes of the coordinates of each vertex of the facet
  28161. v1x = indices[index * 3] * 3;
  28162. v1y = v1x + 1;
  28163. v1z = v1x + 2;
  28164. v2x = indices[index * 3 + 1] * 3;
  28165. v2y = v2x + 1;
  28166. v2z = v2x + 2;
  28167. v3x = indices[index * 3 + 2] * 3;
  28168. v3y = v3x + 1;
  28169. v3z = v3x + 2;
  28170. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  28171. p1p2y = positions[v1y] - positions[v2y];
  28172. p1p2z = positions[v1z] - positions[v2z];
  28173. p3p2x = positions[v3x] - positions[v2x];
  28174. p3p2y = positions[v3y] - positions[v2y];
  28175. p3p2z = positions[v3z] - positions[v2z];
  28176. // compute the face normal with the cross product
  28177. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  28178. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  28179. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  28180. // normalize this normal and store it in the array facetData
  28181. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28182. length = (length === 0) ? 1.0 : length;
  28183. faceNormalx /= length;
  28184. faceNormaly /= length;
  28185. faceNormalz /= length;
  28186. if (computeFacetNormals) {
  28187. options.facetNormals[index].x = faceNormalx;
  28188. options.facetNormals[index].y = faceNormaly;
  28189. options.facetNormals[index].z = faceNormalz;
  28190. }
  28191. if (computeFacetPositions) {
  28192. // compute and the facet barycenter coordinates in the array facetPositions
  28193. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  28194. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  28195. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  28196. }
  28197. if (computeFacetPartitioning) {
  28198. // store the facet indexes in arrays in the main facetPartitioning array :
  28199. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  28200. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28201. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28202. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28203. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28204. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28205. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28206. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28207. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28208. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28209. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * options.ratio) * xSubRatio);
  28210. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * options.ratio) * ySubRatio);
  28211. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * options.ratio) * zSubRatio);
  28212. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  28213. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  28214. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  28215. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  28216. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  28217. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  28218. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  28219. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  28220. // push each facet index in each block containing the vertex
  28221. options.facetPartitioning[block_idx_v1].push(index);
  28222. if (block_idx_v2 != block_idx_v1) {
  28223. options.facetPartitioning[block_idx_v2].push(index);
  28224. }
  28225. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  28226. options.facetPartitioning[block_idx_v3].push(index);
  28227. }
  28228. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  28229. options.facetPartitioning[block_idx_o].push(index);
  28230. }
  28231. }
  28232. // compute the normals anyway
  28233. normals[v1x] += faceNormalx; // accumulate all the normals per face
  28234. normals[v1y] += faceNormaly;
  28235. normals[v1z] += faceNormalz;
  28236. normals[v2x] += faceNormalx;
  28237. normals[v2y] += faceNormaly;
  28238. normals[v2z] += faceNormalz;
  28239. normals[v3x] += faceNormalx;
  28240. normals[v3y] += faceNormaly;
  28241. normals[v3z] += faceNormalz;
  28242. }
  28243. // last normalization of each normal
  28244. for (index = 0; index < normals.length / 3; index++) {
  28245. faceNormalx = normals[index * 3];
  28246. faceNormaly = normals[index * 3 + 1];
  28247. faceNormalz = normals[index * 3 + 2];
  28248. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  28249. length = (length === 0) ? 1.0 : length;
  28250. faceNormalx /= length;
  28251. faceNormaly /= length;
  28252. faceNormalz /= length;
  28253. normals[index * 3] = faceNormalx;
  28254. normals[index * 3 + 1] = faceNormaly;
  28255. normals[index * 3 + 2] = faceNormalz;
  28256. }
  28257. };
  28258. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  28259. var li = indices.length;
  28260. var ln = normals.length;
  28261. var i;
  28262. var n;
  28263. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  28264. switch (sideOrientation) {
  28265. case BABYLON.Mesh.FRONTSIDE:
  28266. // nothing changed
  28267. break;
  28268. case BABYLON.Mesh.BACKSIDE:
  28269. var tmp;
  28270. // indices
  28271. for (i = 0; i < li; i += 3) {
  28272. tmp = indices[i];
  28273. indices[i] = indices[i + 2];
  28274. indices[i + 2] = tmp;
  28275. }
  28276. // normals
  28277. for (n = 0; n < ln; n++) {
  28278. normals[n] = -normals[n];
  28279. }
  28280. break;
  28281. case BABYLON.Mesh.DOUBLESIDE:
  28282. // positions
  28283. var lp = positions.length;
  28284. var l = lp / 3;
  28285. for (var p = 0; p < lp; p++) {
  28286. positions[lp + p] = positions[p];
  28287. }
  28288. // indices
  28289. for (i = 0; i < li; i += 3) {
  28290. indices[i + li] = indices[i + 2] + l;
  28291. indices[i + 1 + li] = indices[i + 1] + l;
  28292. indices[i + 2 + li] = indices[i] + l;
  28293. }
  28294. // normals
  28295. for (n = 0; n < ln; n++) {
  28296. normals[ln + n] = -normals[n];
  28297. }
  28298. // uvs
  28299. var lu = uvs.length;
  28300. var u = 0;
  28301. for (u = 0; u < lu; u++) {
  28302. uvs[u + lu] = uvs[u];
  28303. }
  28304. var frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28305. var backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  28306. u = 0;
  28307. for (i = 0; i < lu / 2; i++) {
  28308. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  28309. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  28310. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  28311. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  28312. u += 2;
  28313. }
  28314. break;
  28315. }
  28316. };
  28317. /**
  28318. * Creates a new VertexData from the imported parameters.
  28319. */
  28320. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  28321. var vertexData = new VertexData();
  28322. // positions
  28323. var positions = parsedVertexData.positions;
  28324. if (positions) {
  28325. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  28326. }
  28327. // normals
  28328. var normals = parsedVertexData.normals;
  28329. if (normals) {
  28330. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  28331. }
  28332. // tangents
  28333. var tangents = parsedVertexData.tangents;
  28334. if (tangents) {
  28335. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  28336. }
  28337. // uvs
  28338. var uvs = parsedVertexData.uvs;
  28339. if (uvs) {
  28340. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  28341. }
  28342. // uv2s
  28343. var uv2s = parsedVertexData.uv2s;
  28344. if (uv2s) {
  28345. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  28346. }
  28347. // uv3s
  28348. var uv3s = parsedVertexData.uv3s;
  28349. if (uv3s) {
  28350. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  28351. }
  28352. // uv4s
  28353. var uv4s = parsedVertexData.uv4s;
  28354. if (uv4s) {
  28355. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  28356. }
  28357. // uv5s
  28358. var uv5s = parsedVertexData.uv5s;
  28359. if (uv5s) {
  28360. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  28361. }
  28362. // uv6s
  28363. var uv6s = parsedVertexData.uv6s;
  28364. if (uv6s) {
  28365. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  28366. }
  28367. // colors
  28368. var colors = parsedVertexData.colors;
  28369. if (colors) {
  28370. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  28371. }
  28372. // matricesIndices
  28373. var matricesIndices = parsedVertexData.matricesIndices;
  28374. if (matricesIndices) {
  28375. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  28376. }
  28377. // matricesWeights
  28378. var matricesWeights = parsedVertexData.matricesWeights;
  28379. if (matricesWeights) {
  28380. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  28381. }
  28382. // indices
  28383. var indices = parsedVertexData.indices;
  28384. if (indices) {
  28385. vertexData.indices = indices;
  28386. }
  28387. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  28388. };
  28389. return VertexData;
  28390. }());
  28391. BABYLON.VertexData = VertexData;
  28392. })(BABYLON || (BABYLON = {}));
  28393. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  28394. var BABYLON;
  28395. (function (BABYLON) {
  28396. var Geometry = (function () {
  28397. function Geometry(id, scene, vertexData, updatable, mesh) {
  28398. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28399. this._totalVertices = 0;
  28400. this._isDisposed = false;
  28401. this.id = id;
  28402. this._engine = scene.getEngine();
  28403. this._meshes = [];
  28404. this._scene = scene;
  28405. //Init vertex buffer cache
  28406. this._vertexBuffers = {};
  28407. this._indices = [];
  28408. this._updatable = updatable;
  28409. // vertexData
  28410. if (vertexData) {
  28411. this.setAllVerticesData(vertexData, updatable);
  28412. }
  28413. else {
  28414. this._totalVertices = 0;
  28415. this._indices = [];
  28416. }
  28417. if (this._engine.getCaps().vertexArrayObject) {
  28418. this._vertexArrayObjects = {};
  28419. }
  28420. // applyToMesh
  28421. if (mesh) {
  28422. if (mesh.getClassName() === "LinesMesh") {
  28423. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  28424. this.updateExtend();
  28425. }
  28426. this.applyToMesh(mesh);
  28427. mesh.computeWorldMatrix(true);
  28428. }
  28429. }
  28430. Object.defineProperty(Geometry.prototype, "boundingBias", {
  28431. /**
  28432. * 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
  28433. * @returns The Bias Vector
  28434. */
  28435. get: function () {
  28436. return this._boundingBias;
  28437. },
  28438. set: function (value) {
  28439. if (this._boundingBias && this._boundingBias.equals(value)) {
  28440. return;
  28441. }
  28442. this._boundingBias = value.clone();
  28443. this.updateBoundingInfo(true, null);
  28444. },
  28445. enumerable: true,
  28446. configurable: true
  28447. });
  28448. Object.defineProperty(Geometry.prototype, "extend", {
  28449. get: function () {
  28450. return this._extend;
  28451. },
  28452. enumerable: true,
  28453. configurable: true
  28454. });
  28455. Geometry.prototype.getScene = function () {
  28456. return this._scene;
  28457. };
  28458. Geometry.prototype.getEngine = function () {
  28459. return this._engine;
  28460. };
  28461. Geometry.prototype.isReady = function () {
  28462. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  28463. };
  28464. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  28465. get: function () {
  28466. for (var index = 0; index < this._meshes.length; index++) {
  28467. if (!this._meshes[index].doNotSerialize) {
  28468. return false;
  28469. }
  28470. }
  28471. return true;
  28472. },
  28473. enumerable: true,
  28474. configurable: true
  28475. });
  28476. Geometry.prototype._rebuild = function () {
  28477. if (this._vertexArrayObjects) {
  28478. this._vertexArrayObjects = {};
  28479. }
  28480. // Index buffer
  28481. if (this._meshes.length !== 0 && this._indices) {
  28482. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28483. }
  28484. // Vertex buffers
  28485. for (var key in this._vertexBuffers) {
  28486. var vertexBuffer = this._vertexBuffers[key];
  28487. vertexBuffer._rebuild();
  28488. }
  28489. };
  28490. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  28491. vertexData.applyToGeometry(this, updatable);
  28492. this.notifyUpdate();
  28493. };
  28494. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  28495. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  28496. this.setVerticesBuffer(buffer);
  28497. };
  28498. Geometry.prototype.removeVerticesData = function (kind) {
  28499. if (this._vertexBuffers[kind]) {
  28500. this._vertexBuffers[kind].dispose();
  28501. delete this._vertexBuffers[kind];
  28502. }
  28503. };
  28504. Geometry.prototype.setVerticesBuffer = function (buffer) {
  28505. var kind = buffer.getKind();
  28506. if (this._vertexBuffers[kind]) {
  28507. this._vertexBuffers[kind].dispose();
  28508. }
  28509. this._vertexBuffers[kind] = buffer;
  28510. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28511. var data = buffer.getData();
  28512. var stride = buffer.getStrideSize();
  28513. this._totalVertices = data.length / stride;
  28514. this.updateExtend(data, stride);
  28515. this._resetPointsArrayCache();
  28516. var meshes = this._meshes;
  28517. var numOfMeshes = meshes.length;
  28518. for (var index = 0; index < numOfMeshes; index++) {
  28519. var mesh = meshes[index];
  28520. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28521. mesh._createGlobalSubMesh(false);
  28522. mesh.computeWorldMatrix(true);
  28523. }
  28524. }
  28525. this.notifyUpdate(kind);
  28526. if (this._vertexArrayObjects) {
  28527. this._disposeVertexArrayObjects();
  28528. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  28529. }
  28530. };
  28531. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset) {
  28532. var vertexBuffer = this.getVertexBuffer(kind);
  28533. if (!vertexBuffer) {
  28534. return;
  28535. }
  28536. vertexBuffer.updateDirectly(data, offset);
  28537. this.notifyUpdate(kind);
  28538. };
  28539. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  28540. var vertexBuffer = this.getVertexBuffer(kind);
  28541. if (!vertexBuffer) {
  28542. return;
  28543. }
  28544. vertexBuffer.update(data);
  28545. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28546. var stride = vertexBuffer.getStrideSize();
  28547. this._totalVertices = data.length / stride;
  28548. this.updateBoundingInfo(updateExtends, data);
  28549. }
  28550. this.notifyUpdate(kind);
  28551. };
  28552. Geometry.prototype.updateBoundingInfo = function (updateExtends, data) {
  28553. if (updateExtends) {
  28554. this.updateExtend(data);
  28555. }
  28556. var meshes = this._meshes;
  28557. var numOfMeshes = meshes.length;
  28558. this._resetPointsArrayCache();
  28559. for (var index = 0; index < numOfMeshes; index++) {
  28560. var mesh = meshes[index];
  28561. if (updateExtends) {
  28562. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28563. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  28564. var subMesh = mesh.subMeshes[subIndex];
  28565. subMesh.refreshBoundingInfo();
  28566. }
  28567. }
  28568. }
  28569. };
  28570. Geometry.prototype._bind = function (effect, indexToBind) {
  28571. if (indexToBind === void 0) { indexToBind = undefined; }
  28572. if (indexToBind === undefined) {
  28573. indexToBind = this._indexBuffer;
  28574. }
  28575. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  28576. this._engine.bindBuffers(this.getVertexBuffers(), indexToBind, effect);
  28577. return;
  28578. }
  28579. // Using VAO
  28580. if (!this._vertexArrayObjects[effect.key]) {
  28581. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(this.getVertexBuffers(), indexToBind, effect);
  28582. }
  28583. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  28584. };
  28585. Geometry.prototype.getTotalVertices = function () {
  28586. if (!this.isReady()) {
  28587. return 0;
  28588. }
  28589. return this._totalVertices;
  28590. };
  28591. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  28592. var vertexBuffer = this.getVertexBuffer(kind);
  28593. if (!vertexBuffer) {
  28594. return null;
  28595. }
  28596. var orig = vertexBuffer.getData();
  28597. if (!forceCopy && (!copyWhenShared || this._meshes.length === 1)) {
  28598. return orig;
  28599. }
  28600. else {
  28601. var len = orig.length;
  28602. var copy = [];
  28603. for (var i = 0; i < len; i++) {
  28604. copy.push(orig[i]);
  28605. }
  28606. return copy;
  28607. }
  28608. };
  28609. Geometry.prototype.getVertexBuffer = function (kind) {
  28610. if (!this.isReady()) {
  28611. return null;
  28612. }
  28613. return this._vertexBuffers[kind];
  28614. };
  28615. Geometry.prototype.getVertexBuffers = function () {
  28616. if (!this.isReady()) {
  28617. return null;
  28618. }
  28619. return this._vertexBuffers;
  28620. };
  28621. Geometry.prototype.isVerticesDataPresent = function (kind) {
  28622. if (!this._vertexBuffers) {
  28623. if (this._delayInfo) {
  28624. return this._delayInfo.indexOf(kind) !== -1;
  28625. }
  28626. return false;
  28627. }
  28628. return this._vertexBuffers[kind] !== undefined;
  28629. };
  28630. Geometry.prototype.getVerticesDataKinds = function () {
  28631. var result = [];
  28632. var kind;
  28633. if (!this._vertexBuffers && this._delayInfo) {
  28634. for (kind in this._delayInfo) {
  28635. result.push(kind);
  28636. }
  28637. }
  28638. else {
  28639. for (kind in this._vertexBuffers) {
  28640. result.push(kind);
  28641. }
  28642. }
  28643. return result;
  28644. };
  28645. Geometry.prototype.setIndices = function (indices, totalVertices) {
  28646. if (this._indexBuffer) {
  28647. this._engine._releaseBuffer(this._indexBuffer);
  28648. }
  28649. this._disposeVertexArrayObjects();
  28650. this._indices = indices;
  28651. if (this._meshes.length !== 0 && this._indices) {
  28652. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28653. }
  28654. if (totalVertices !== undefined) {
  28655. this._totalVertices = totalVertices;
  28656. }
  28657. var meshes = this._meshes;
  28658. var numOfMeshes = meshes.length;
  28659. for (var index = 0; index < numOfMeshes; index++) {
  28660. meshes[index]._createGlobalSubMesh(true);
  28661. }
  28662. this.notifyUpdate();
  28663. };
  28664. Geometry.prototype.getTotalIndices = function () {
  28665. if (!this.isReady()) {
  28666. return 0;
  28667. }
  28668. return this._indices.length;
  28669. };
  28670. Geometry.prototype.getIndices = function (copyWhenShared) {
  28671. if (!this.isReady()) {
  28672. return null;
  28673. }
  28674. var orig = this._indices;
  28675. if (!copyWhenShared || this._meshes.length === 1) {
  28676. return orig;
  28677. }
  28678. else {
  28679. var len = orig.length;
  28680. var copy = [];
  28681. for (var i = 0; i < len; i++) {
  28682. copy.push(orig[i]);
  28683. }
  28684. return copy;
  28685. }
  28686. };
  28687. Geometry.prototype.getIndexBuffer = function () {
  28688. if (!this.isReady()) {
  28689. return null;
  28690. }
  28691. return this._indexBuffer;
  28692. };
  28693. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  28694. if (!effect || !this._vertexArrayObjects) {
  28695. return;
  28696. }
  28697. if (this._vertexArrayObjects[effect.key]) {
  28698. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  28699. delete this._vertexArrayObjects[effect.key];
  28700. }
  28701. };
  28702. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  28703. var meshes = this._meshes;
  28704. var index = meshes.indexOf(mesh);
  28705. if (index === -1) {
  28706. return;
  28707. }
  28708. meshes.splice(index, 1);
  28709. mesh._geometry = null;
  28710. if (meshes.length === 0 && shouldDispose) {
  28711. this.dispose();
  28712. }
  28713. };
  28714. Geometry.prototype.applyToMesh = function (mesh) {
  28715. if (mesh._geometry === this) {
  28716. return;
  28717. }
  28718. var previousGeometry = mesh._geometry;
  28719. if (previousGeometry) {
  28720. previousGeometry.releaseForMesh(mesh);
  28721. }
  28722. var meshes = this._meshes;
  28723. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  28724. mesh._geometry = this;
  28725. this._scene.pushGeometry(this);
  28726. meshes.push(mesh);
  28727. if (this.isReady()) {
  28728. this._applyToMesh(mesh);
  28729. }
  28730. else {
  28731. mesh._boundingInfo = this._boundingInfo;
  28732. }
  28733. };
  28734. Geometry.prototype.updateExtend = function (data, stride) {
  28735. if (data === void 0) { data = null; }
  28736. if (!data) {
  28737. data = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind].getData();
  28738. }
  28739. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, stride);
  28740. };
  28741. Geometry.prototype._applyToMesh = function (mesh) {
  28742. var numOfMeshes = this._meshes.length;
  28743. // vertexBuffers
  28744. for (var kind in this._vertexBuffers) {
  28745. if (numOfMeshes === 1) {
  28746. this._vertexBuffers[kind].create();
  28747. }
  28748. var buffer = this._vertexBuffers[kind].getBuffer();
  28749. if (buffer)
  28750. buffer.references = numOfMeshes;
  28751. if (kind === BABYLON.VertexBuffer.PositionKind) {
  28752. if (!this._extend) {
  28753. this.updateExtend(this._vertexBuffers[kind].getData());
  28754. }
  28755. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28756. mesh._createGlobalSubMesh(false);
  28757. //bounding info was just created again, world matrix should be applied again.
  28758. mesh._updateBoundingInfo();
  28759. }
  28760. }
  28761. // indexBuffer
  28762. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  28763. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  28764. }
  28765. if (this._indexBuffer) {
  28766. this._indexBuffer.references = numOfMeshes;
  28767. }
  28768. };
  28769. Geometry.prototype.notifyUpdate = function (kind) {
  28770. if (this.onGeometryUpdated) {
  28771. this.onGeometryUpdated(this, kind);
  28772. }
  28773. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  28774. var mesh = _a[_i];
  28775. mesh._markSubMeshesAsAttributesDirty();
  28776. }
  28777. };
  28778. Geometry.prototype.load = function (scene, onLoaded) {
  28779. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  28780. return;
  28781. }
  28782. if (this.isReady()) {
  28783. if (onLoaded) {
  28784. onLoaded();
  28785. }
  28786. return;
  28787. }
  28788. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  28789. this._queueLoad(scene, onLoaded);
  28790. };
  28791. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  28792. var _this = this;
  28793. scene._addPendingData(this);
  28794. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  28795. _this._delayLoadingFunction(JSON.parse(data), _this);
  28796. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  28797. _this._delayInfo = [];
  28798. scene._removePendingData(_this);
  28799. var meshes = _this._meshes;
  28800. var numOfMeshes = meshes.length;
  28801. for (var index = 0; index < numOfMeshes; index++) {
  28802. _this._applyToMesh(meshes[index]);
  28803. }
  28804. if (onLoaded) {
  28805. onLoaded();
  28806. }
  28807. }, function () { }, scene.database);
  28808. };
  28809. /**
  28810. * Invert the geometry to move from a right handed system to a left handed one.
  28811. */
  28812. Geometry.prototype.toLeftHanded = function () {
  28813. // Flip faces
  28814. var tIndices = this.getIndices(false);
  28815. if (tIndices != null && tIndices.length > 0) {
  28816. for (var i = 0; i < tIndices.length; i += 3) {
  28817. var tTemp = tIndices[i + 0];
  28818. tIndices[i + 0] = tIndices[i + 2];
  28819. tIndices[i + 2] = tTemp;
  28820. }
  28821. this.setIndices(tIndices);
  28822. }
  28823. // Negate position.z
  28824. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  28825. if (tPositions != null && tPositions.length > 0) {
  28826. for (var i = 0; i < tPositions.length; i += 3) {
  28827. tPositions[i + 2] = -tPositions[i + 2];
  28828. }
  28829. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  28830. }
  28831. // Negate normal.z
  28832. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  28833. if (tNormals != null && tNormals.length > 0) {
  28834. for (var i = 0; i < tNormals.length; i += 3) {
  28835. tNormals[i + 2] = -tNormals[i + 2];
  28836. }
  28837. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  28838. }
  28839. };
  28840. // Cache
  28841. Geometry.prototype._resetPointsArrayCache = function () {
  28842. this._positions = null;
  28843. };
  28844. Geometry.prototype._generatePointsArray = function () {
  28845. if (this._positions)
  28846. return true;
  28847. this._positions = [];
  28848. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  28849. if (!data) {
  28850. return false;
  28851. }
  28852. for (var index = 0; index < data.length; index += 3) {
  28853. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  28854. }
  28855. return true;
  28856. };
  28857. Geometry.prototype.isDisposed = function () {
  28858. return this._isDisposed;
  28859. };
  28860. Geometry.prototype._disposeVertexArrayObjects = function () {
  28861. if (this._vertexArrayObjects) {
  28862. for (var kind in this._vertexArrayObjects) {
  28863. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  28864. }
  28865. this._vertexArrayObjects = {};
  28866. }
  28867. };
  28868. Geometry.prototype.dispose = function () {
  28869. var meshes = this._meshes;
  28870. var numOfMeshes = meshes.length;
  28871. var index;
  28872. for (index = 0; index < numOfMeshes; index++) {
  28873. this.releaseForMesh(meshes[index]);
  28874. }
  28875. this._meshes = [];
  28876. this._disposeVertexArrayObjects();
  28877. for (var kind in this._vertexBuffers) {
  28878. this._vertexBuffers[kind].dispose();
  28879. }
  28880. this._vertexBuffers = {};
  28881. this._totalVertices = 0;
  28882. if (this._indexBuffer) {
  28883. this._engine._releaseBuffer(this._indexBuffer);
  28884. }
  28885. this._indexBuffer = null;
  28886. this._indices = [];
  28887. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  28888. this.delayLoadingFile = null;
  28889. this._delayLoadingFunction = null;
  28890. this._delayInfo = [];
  28891. this._boundingInfo = null;
  28892. this._scene.removeGeometry(this);
  28893. this._isDisposed = true;
  28894. };
  28895. Geometry.prototype.copy = function (id) {
  28896. var vertexData = new BABYLON.VertexData();
  28897. vertexData.indices = [];
  28898. var indices = this.getIndices();
  28899. for (var index = 0; index < indices.length; index++) {
  28900. vertexData.indices.push(indices[index]);
  28901. }
  28902. var updatable = false;
  28903. var stopChecking = false;
  28904. var kind;
  28905. for (kind in this._vertexBuffers) {
  28906. // using slice() to make a copy of the array and not just reference it
  28907. var data = this.getVerticesData(kind);
  28908. if (data instanceof Float32Array) {
  28909. vertexData.set(new Float32Array(data), kind);
  28910. }
  28911. else {
  28912. vertexData.set(data.slice(0), kind);
  28913. }
  28914. if (!stopChecking) {
  28915. updatable = this.getVertexBuffer(kind).isUpdatable();
  28916. stopChecking = !updatable;
  28917. }
  28918. }
  28919. var geometry = new Geometry(id, this._scene, vertexData, updatable, null);
  28920. geometry.delayLoadState = this.delayLoadState;
  28921. geometry.delayLoadingFile = this.delayLoadingFile;
  28922. geometry._delayLoadingFunction = this._delayLoadingFunction;
  28923. for (kind in this._delayInfo) {
  28924. geometry._delayInfo = geometry._delayInfo || [];
  28925. geometry._delayInfo.push(kind);
  28926. }
  28927. // Bounding info
  28928. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  28929. return geometry;
  28930. };
  28931. Geometry.prototype.serialize = function () {
  28932. var serializationObject = {};
  28933. serializationObject.id = this.id;
  28934. serializationObject.updatable = this._updatable;
  28935. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  28936. serializationObject.tags = BABYLON.Tags.GetTags(this);
  28937. }
  28938. return serializationObject;
  28939. };
  28940. Geometry.prototype.toNumberArray = function (origin) {
  28941. if (Array.isArray(origin)) {
  28942. return origin;
  28943. }
  28944. else {
  28945. return Array.prototype.slice.call(origin);
  28946. }
  28947. };
  28948. Geometry.prototype.serializeVerticeData = function () {
  28949. var serializationObject = this.serialize();
  28950. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  28951. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  28952. if (this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable) {
  28953. serializationObject.positions._updatable = true;
  28954. }
  28955. }
  28956. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  28957. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  28958. if (this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable) {
  28959. serializationObject.normals._updatable = true;
  28960. }
  28961. }
  28962. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  28963. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  28964. if (this.getVertexBuffer(BABYLON.VertexBuffer.UVKind).isUpdatable) {
  28965. serializationObject.uvs._updatable = true;
  28966. }
  28967. }
  28968. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  28969. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  28970. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV2Kind).isUpdatable) {
  28971. serializationObject.uv2s._updatable = true;
  28972. }
  28973. }
  28974. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  28975. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  28976. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV3Kind).isUpdatable) {
  28977. serializationObject.uv3s._updatable = true;
  28978. }
  28979. }
  28980. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  28981. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  28982. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV4Kind).isUpdatable) {
  28983. serializationObject.uv4s._updatable = true;
  28984. }
  28985. }
  28986. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  28987. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  28988. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV5Kind).isUpdatable) {
  28989. serializationObject.uv5s._updatable = true;
  28990. }
  28991. }
  28992. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  28993. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  28994. if (this.getVertexBuffer(BABYLON.VertexBuffer.UV6Kind).isUpdatable) {
  28995. serializationObject.uv6s._updatable = true;
  28996. }
  28997. }
  28998. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  28999. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  29000. if (this.getVertexBuffer(BABYLON.VertexBuffer.ColorKind).isUpdatable) {
  29001. serializationObject.colors._updatable = true;
  29002. }
  29003. }
  29004. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  29005. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  29006. serializationObject.matricesIndices._isExpanded = true;
  29007. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesIndicesKind).isUpdatable) {
  29008. serializationObject.matricesIndices._updatable = true;
  29009. }
  29010. }
  29011. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  29012. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  29013. if (this.getVertexBuffer(BABYLON.VertexBuffer.MatricesWeightsKind).isUpdatable) {
  29014. serializationObject.matricesWeights._updatable = true;
  29015. }
  29016. }
  29017. serializationObject.indices = this.toNumberArray(this.getIndices());
  29018. return serializationObject;
  29019. };
  29020. // Statics
  29021. Geometry.ExtractFromMesh = function (mesh, id) {
  29022. var geometry = mesh._geometry;
  29023. if (!geometry) {
  29024. return null;
  29025. }
  29026. return geometry.copy(id);
  29027. };
  29028. /**
  29029. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  29030. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  29031. * Be aware Math.random() could cause collisions, but:
  29032. * "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"
  29033. */
  29034. Geometry.RandomId = function () {
  29035. return BABYLON.Tools.RandomId();
  29036. };
  29037. Geometry.ImportGeometry = function (parsedGeometry, mesh) {
  29038. var scene = mesh.getScene();
  29039. // Geometry
  29040. var geometryId = parsedGeometry.geometryId;
  29041. if (geometryId) {
  29042. var geometry = scene.getGeometryByID(geometryId);
  29043. if (geometry) {
  29044. geometry.applyToMesh(mesh);
  29045. }
  29046. }
  29047. else if (parsedGeometry instanceof ArrayBuffer) {
  29048. var binaryInfo = mesh._binaryInfo;
  29049. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  29050. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  29051. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  29052. }
  29053. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  29054. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  29055. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  29056. }
  29057. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  29058. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  29059. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  29060. }
  29061. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  29062. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  29063. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  29064. }
  29065. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  29066. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  29067. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  29068. }
  29069. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  29070. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  29071. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  29072. }
  29073. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  29074. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  29075. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  29076. }
  29077. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  29078. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  29079. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  29080. }
  29081. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  29082. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  29083. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  29084. }
  29085. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  29086. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  29087. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  29088. }
  29089. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  29090. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  29091. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  29092. }
  29093. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  29094. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  29095. mesh.setIndices(indicesData);
  29096. }
  29097. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  29098. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  29099. mesh.subMeshes = [];
  29100. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  29101. var materialIndex = subMeshesData[(i * 5) + 0];
  29102. var verticesStart = subMeshesData[(i * 5) + 1];
  29103. var verticesCount = subMeshesData[(i * 5) + 2];
  29104. var indexStart = subMeshesData[(i * 5) + 3];
  29105. var indexCount = subMeshesData[(i * 5) + 4];
  29106. var subMesh = new BABYLON.SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  29107. }
  29108. }
  29109. }
  29110. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  29111. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  29112. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  29113. if (parsedGeometry.uvs) {
  29114. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  29115. }
  29116. if (parsedGeometry.uvs2) {
  29117. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  29118. }
  29119. if (parsedGeometry.uvs3) {
  29120. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  29121. }
  29122. if (parsedGeometry.uvs4) {
  29123. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  29124. }
  29125. if (parsedGeometry.uvs5) {
  29126. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  29127. }
  29128. if (parsedGeometry.uvs6) {
  29129. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  29130. }
  29131. if (parsedGeometry.colors) {
  29132. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  29133. }
  29134. if (parsedGeometry.matricesIndices) {
  29135. if (!parsedGeometry.matricesIndices._isExpanded) {
  29136. var floatIndices = [];
  29137. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  29138. var matricesIndex = parsedGeometry.matricesIndices[i];
  29139. floatIndices.push(matricesIndex & 0x000000FF);
  29140. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29141. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29142. floatIndices.push(matricesIndex >> 24);
  29143. }
  29144. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  29145. }
  29146. else {
  29147. delete parsedGeometry.matricesIndices._isExpanded;
  29148. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  29149. }
  29150. }
  29151. if (parsedGeometry.matricesIndicesExtra) {
  29152. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  29153. var floatIndices = [];
  29154. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  29155. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  29156. floatIndices.push(matricesIndex & 0x000000FF);
  29157. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  29158. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  29159. floatIndices.push(matricesIndex >> 24);
  29160. }
  29161. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  29162. }
  29163. else {
  29164. delete parsedGeometry.matricesIndices._isExpanded;
  29165. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  29166. }
  29167. }
  29168. if (parsedGeometry.matricesWeights) {
  29169. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeights, parsedGeometry.numBoneInfluencers);
  29170. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  29171. }
  29172. if (parsedGeometry.matricesWeightsExtra) {
  29173. Geometry._CleanMatricesWeights(parsedGeometry.matricesWeightsExtra, parsedGeometry.numBoneInfluencers);
  29174. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  29175. }
  29176. mesh.setIndices(parsedGeometry.indices);
  29177. }
  29178. // SubMeshes
  29179. if (parsedGeometry.subMeshes) {
  29180. mesh.subMeshes = [];
  29181. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  29182. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  29183. var subMesh = new BABYLON.SubMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  29184. }
  29185. }
  29186. // Flat shading
  29187. if (mesh._shouldGenerateFlatShading) {
  29188. mesh.convertToFlatShadedMesh();
  29189. delete mesh._shouldGenerateFlatShading;
  29190. }
  29191. // Update
  29192. mesh.computeWorldMatrix(true);
  29193. // Octree
  29194. if (scene['_selectionOctree']) {
  29195. scene['_selectionOctree'].addMesh(mesh);
  29196. }
  29197. };
  29198. Geometry._CleanMatricesWeights = function (matricesWeights, influencers) {
  29199. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  29200. return;
  29201. }
  29202. var size = matricesWeights.length;
  29203. for (var i = 0; i < size; i += influencers) {
  29204. var weight = 0;
  29205. var biggerIndex = i;
  29206. var biggerWeight = 0;
  29207. for (var j = 0; j < influencers - 1; j++) {
  29208. weight += matricesWeights[i + j];
  29209. if (matricesWeights[i + j] > biggerWeight) {
  29210. biggerWeight = matricesWeights[i + j];
  29211. biggerIndex = i + j;
  29212. }
  29213. }
  29214. matricesWeights[biggerIndex] += Math.max(0, 1.0 - weight);
  29215. }
  29216. };
  29217. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  29218. if (scene.getGeometryByID(parsedVertexData.id)) {
  29219. return null; // null since geometry could be something else than a box...
  29220. }
  29221. var geometry = new Geometry(parsedVertexData.id, scene, null, parsedVertexData.updatable);
  29222. if (BABYLON.Tags) {
  29223. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  29224. }
  29225. if (parsedVertexData.delayLoadingFile) {
  29226. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  29227. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  29228. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  29229. geometry._delayInfo = [];
  29230. if (parsedVertexData.hasUVs) {
  29231. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  29232. }
  29233. if (parsedVertexData.hasUVs2) {
  29234. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  29235. }
  29236. if (parsedVertexData.hasUVs3) {
  29237. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  29238. }
  29239. if (parsedVertexData.hasUVs4) {
  29240. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  29241. }
  29242. if (parsedVertexData.hasUVs5) {
  29243. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  29244. }
  29245. if (parsedVertexData.hasUVs6) {
  29246. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  29247. }
  29248. if (parsedVertexData.hasColors) {
  29249. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  29250. }
  29251. if (parsedVertexData.hasMatricesIndices) {
  29252. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  29253. }
  29254. if (parsedVertexData.hasMatricesWeights) {
  29255. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  29256. }
  29257. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  29258. }
  29259. else {
  29260. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  29261. }
  29262. scene.pushGeometry(geometry, true);
  29263. return geometry;
  29264. };
  29265. return Geometry;
  29266. }());
  29267. BABYLON.Geometry = Geometry;
  29268. /////// Primitives //////////////////////////////////////////////
  29269. (function (Geometry) {
  29270. var Primitives;
  29271. (function (Primitives) {
  29272. /// Abstract class
  29273. var _Primitive = (function (_super) {
  29274. __extends(_Primitive, _super);
  29275. function _Primitive(id, scene, _canBeRegenerated, mesh) {
  29276. var _this = _super.call(this, id, scene, null, false, mesh) || this;
  29277. _this._canBeRegenerated = _canBeRegenerated;
  29278. _this._beingRegenerated = true;
  29279. _this.regenerate();
  29280. _this._beingRegenerated = false;
  29281. return _this;
  29282. }
  29283. _Primitive.prototype.canBeRegenerated = function () {
  29284. return this._canBeRegenerated;
  29285. };
  29286. _Primitive.prototype.regenerate = function () {
  29287. if (!this._canBeRegenerated) {
  29288. return;
  29289. }
  29290. this._beingRegenerated = true;
  29291. this.setAllVerticesData(this._regenerateVertexData(), false);
  29292. this._beingRegenerated = false;
  29293. };
  29294. _Primitive.prototype.asNewGeometry = function (id) {
  29295. return _super.prototype.copy.call(this, id);
  29296. };
  29297. // overrides
  29298. _Primitive.prototype.setAllVerticesData = function (vertexData, updatable) {
  29299. if (!this._beingRegenerated) {
  29300. return;
  29301. }
  29302. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  29303. };
  29304. _Primitive.prototype.setVerticesData = function (kind, data, updatable) {
  29305. if (!this._beingRegenerated) {
  29306. return;
  29307. }
  29308. _super.prototype.setVerticesData.call(this, kind, data, false);
  29309. };
  29310. // to override
  29311. // protected
  29312. _Primitive.prototype._regenerateVertexData = function () {
  29313. throw new Error("Abstract method");
  29314. };
  29315. _Primitive.prototype.copy = function (id) {
  29316. throw new Error("Must be overriden in sub-classes.");
  29317. };
  29318. _Primitive.prototype.serialize = function () {
  29319. var serializationObject = _super.prototype.serialize.call(this);
  29320. serializationObject.canBeRegenerated = this.canBeRegenerated();
  29321. return serializationObject;
  29322. };
  29323. return _Primitive;
  29324. }(Geometry));
  29325. Primitives._Primitive = _Primitive;
  29326. var Ribbon = (function (_super) {
  29327. __extends(Ribbon, _super);
  29328. // Members
  29329. function Ribbon(id, scene, pathArray, closeArray, closePath, offset, canBeRegenerated, mesh, side) {
  29330. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29331. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29332. _this.pathArray = pathArray;
  29333. _this.closeArray = closeArray;
  29334. _this.closePath = closePath;
  29335. _this.offset = offset;
  29336. _this.side = side;
  29337. return _this;
  29338. }
  29339. Ribbon.prototype._regenerateVertexData = function () {
  29340. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  29341. };
  29342. Ribbon.prototype.copy = function (id) {
  29343. return new Ribbon(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), null, this.side);
  29344. };
  29345. return Ribbon;
  29346. }(_Primitive));
  29347. Primitives.Ribbon = Ribbon;
  29348. var Box = (function (_super) {
  29349. __extends(Box, _super);
  29350. // Members
  29351. function Box(id, scene, size, canBeRegenerated, mesh, side) {
  29352. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29353. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29354. _this.size = size;
  29355. _this.side = side;
  29356. return _this;
  29357. }
  29358. Box.prototype._regenerateVertexData = function () {
  29359. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  29360. };
  29361. Box.prototype.copy = function (id) {
  29362. return new Box(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29363. };
  29364. Box.prototype.serialize = function () {
  29365. var serializationObject = _super.prototype.serialize.call(this);
  29366. serializationObject.size = this.size;
  29367. return serializationObject;
  29368. };
  29369. Box.Parse = function (parsedBox, scene) {
  29370. if (scene.getGeometryByID(parsedBox.id)) {
  29371. return null; // null since geometry could be something else than a box...
  29372. }
  29373. var box = new Geometry.Primitives.Box(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  29374. if (BABYLON.Tags) {
  29375. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  29376. }
  29377. scene.pushGeometry(box, true);
  29378. return box;
  29379. };
  29380. return Box;
  29381. }(_Primitive));
  29382. Primitives.Box = Box;
  29383. var Sphere = (function (_super) {
  29384. __extends(Sphere, _super);
  29385. function Sphere(id, scene, segments, diameter, canBeRegenerated, mesh, side) {
  29386. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29387. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29388. _this.segments = segments;
  29389. _this.diameter = diameter;
  29390. _this.side = side;
  29391. return _this;
  29392. }
  29393. Sphere.prototype._regenerateVertexData = function () {
  29394. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  29395. };
  29396. Sphere.prototype.copy = function (id) {
  29397. return new Sphere(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  29398. };
  29399. Sphere.prototype.serialize = function () {
  29400. var serializationObject = _super.prototype.serialize.call(this);
  29401. serializationObject.segments = this.segments;
  29402. serializationObject.diameter = this.diameter;
  29403. return serializationObject;
  29404. };
  29405. Sphere.Parse = function (parsedSphere, scene) {
  29406. if (scene.getGeometryByID(parsedSphere.id)) {
  29407. return null; // null since geometry could be something else than a sphere...
  29408. }
  29409. var sphere = new Geometry.Primitives.Sphere(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  29410. if (BABYLON.Tags) {
  29411. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  29412. }
  29413. scene.pushGeometry(sphere, true);
  29414. return sphere;
  29415. };
  29416. return Sphere;
  29417. }(_Primitive));
  29418. Primitives.Sphere = Sphere;
  29419. var Disc = (function (_super) {
  29420. __extends(Disc, _super);
  29421. // Members
  29422. function Disc(id, scene, radius, tessellation, canBeRegenerated, mesh, side) {
  29423. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29424. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29425. _this.radius = radius;
  29426. _this.tessellation = tessellation;
  29427. _this.side = side;
  29428. return _this;
  29429. }
  29430. Disc.prototype._regenerateVertexData = function () {
  29431. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  29432. };
  29433. Disc.prototype.copy = function (id) {
  29434. return new Disc(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  29435. };
  29436. return Disc;
  29437. }(_Primitive));
  29438. Primitives.Disc = Disc;
  29439. var Cylinder = (function (_super) {
  29440. __extends(Cylinder, _super);
  29441. function Cylinder(id, scene, height, diameterTop, diameterBottom, tessellation, subdivisions, canBeRegenerated, mesh, side) {
  29442. if (subdivisions === void 0) { subdivisions = 1; }
  29443. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29444. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29445. _this.height = height;
  29446. _this.diameterTop = diameterTop;
  29447. _this.diameterBottom = diameterBottom;
  29448. _this.tessellation = tessellation;
  29449. _this.subdivisions = subdivisions;
  29450. _this.side = side;
  29451. return _this;
  29452. }
  29453. Cylinder.prototype._regenerateVertexData = function () {
  29454. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  29455. };
  29456. Cylinder.prototype.copy = function (id) {
  29457. return new Cylinder(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  29458. };
  29459. Cylinder.prototype.serialize = function () {
  29460. var serializationObject = _super.prototype.serialize.call(this);
  29461. serializationObject.height = this.height;
  29462. serializationObject.diameterTop = this.diameterTop;
  29463. serializationObject.diameterBottom = this.diameterBottom;
  29464. serializationObject.tessellation = this.tessellation;
  29465. return serializationObject;
  29466. };
  29467. Cylinder.Parse = function (parsedCylinder, scene) {
  29468. if (scene.getGeometryByID(parsedCylinder.id)) {
  29469. return null; // null since geometry could be something else than a cylinder...
  29470. }
  29471. var cylinder = new Geometry.Primitives.Cylinder(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  29472. if (BABYLON.Tags) {
  29473. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  29474. }
  29475. scene.pushGeometry(cylinder, true);
  29476. return cylinder;
  29477. };
  29478. return Cylinder;
  29479. }(_Primitive));
  29480. Primitives.Cylinder = Cylinder;
  29481. var Torus = (function (_super) {
  29482. __extends(Torus, _super);
  29483. function Torus(id, scene, diameter, thickness, tessellation, canBeRegenerated, mesh, side) {
  29484. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29485. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29486. _this.diameter = diameter;
  29487. _this.thickness = thickness;
  29488. _this.tessellation = tessellation;
  29489. _this.side = side;
  29490. return _this;
  29491. }
  29492. Torus.prototype._regenerateVertexData = function () {
  29493. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  29494. };
  29495. Torus.prototype.copy = function (id) {
  29496. return new Torus(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  29497. };
  29498. Torus.prototype.serialize = function () {
  29499. var serializationObject = _super.prototype.serialize.call(this);
  29500. serializationObject.diameter = this.diameter;
  29501. serializationObject.thickness = this.thickness;
  29502. serializationObject.tessellation = this.tessellation;
  29503. return serializationObject;
  29504. };
  29505. Torus.Parse = function (parsedTorus, scene) {
  29506. if (scene.getGeometryByID(parsedTorus.id)) {
  29507. return null; // null since geometry could be something else than a torus...
  29508. }
  29509. var torus = new Geometry.Primitives.Torus(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  29510. if (BABYLON.Tags) {
  29511. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  29512. }
  29513. scene.pushGeometry(torus, true);
  29514. return torus;
  29515. };
  29516. return Torus;
  29517. }(_Primitive));
  29518. Primitives.Torus = Torus;
  29519. var Ground = (function (_super) {
  29520. __extends(Ground, _super);
  29521. function Ground(id, scene, width, height, subdivisions, canBeRegenerated, mesh) {
  29522. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29523. _this.width = width;
  29524. _this.height = height;
  29525. _this.subdivisions = subdivisions;
  29526. return _this;
  29527. }
  29528. Ground.prototype._regenerateVertexData = function () {
  29529. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  29530. };
  29531. Ground.prototype.copy = function (id) {
  29532. return new Ground(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  29533. };
  29534. Ground.prototype.serialize = function () {
  29535. var serializationObject = _super.prototype.serialize.call(this);
  29536. serializationObject.width = this.width;
  29537. serializationObject.height = this.height;
  29538. serializationObject.subdivisions = this.subdivisions;
  29539. return serializationObject;
  29540. };
  29541. Ground.Parse = function (parsedGround, scene) {
  29542. if (scene.getGeometryByID(parsedGround.id)) {
  29543. return null; // null since geometry could be something else than a ground...
  29544. }
  29545. var ground = new Geometry.Primitives.Ground(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  29546. if (BABYLON.Tags) {
  29547. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  29548. }
  29549. scene.pushGeometry(ground, true);
  29550. return ground;
  29551. };
  29552. return Ground;
  29553. }(_Primitive));
  29554. Primitives.Ground = Ground;
  29555. var TiledGround = (function (_super) {
  29556. __extends(TiledGround, _super);
  29557. function TiledGround(id, scene, xmin, zmin, xmax, zmax, subdivisions, precision, canBeRegenerated, mesh) {
  29558. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29559. _this.xmin = xmin;
  29560. _this.zmin = zmin;
  29561. _this.xmax = xmax;
  29562. _this.zmax = zmax;
  29563. _this.subdivisions = subdivisions;
  29564. _this.precision = precision;
  29565. return _this;
  29566. }
  29567. TiledGround.prototype._regenerateVertexData = function () {
  29568. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  29569. };
  29570. TiledGround.prototype.copy = function (id) {
  29571. return new TiledGround(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  29572. };
  29573. return TiledGround;
  29574. }(_Primitive));
  29575. Primitives.TiledGround = TiledGround;
  29576. var Plane = (function (_super) {
  29577. __extends(Plane, _super);
  29578. function Plane(id, scene, size, canBeRegenerated, mesh, side) {
  29579. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29580. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29581. _this.size = size;
  29582. _this.side = side;
  29583. return _this;
  29584. }
  29585. Plane.prototype._regenerateVertexData = function () {
  29586. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  29587. };
  29588. Plane.prototype.copy = function (id) {
  29589. return new Plane(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  29590. };
  29591. Plane.prototype.serialize = function () {
  29592. var serializationObject = _super.prototype.serialize.call(this);
  29593. serializationObject.size = this.size;
  29594. return serializationObject;
  29595. };
  29596. Plane.Parse = function (parsedPlane, scene) {
  29597. if (scene.getGeometryByID(parsedPlane.id)) {
  29598. return null; // null since geometry could be something else than a ground...
  29599. }
  29600. var plane = new Geometry.Primitives.Plane(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  29601. if (BABYLON.Tags) {
  29602. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  29603. }
  29604. scene.pushGeometry(plane, true);
  29605. return plane;
  29606. };
  29607. return Plane;
  29608. }(_Primitive));
  29609. Primitives.Plane = Plane;
  29610. var TorusKnot = (function (_super) {
  29611. __extends(TorusKnot, _super);
  29612. function TorusKnot(id, scene, radius, tube, radialSegments, tubularSegments, p, q, canBeRegenerated, mesh, side) {
  29613. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  29614. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  29615. _this.radius = radius;
  29616. _this.tube = tube;
  29617. _this.radialSegments = radialSegments;
  29618. _this.tubularSegments = tubularSegments;
  29619. _this.p = p;
  29620. _this.q = q;
  29621. _this.side = side;
  29622. return _this;
  29623. }
  29624. TorusKnot.prototype._regenerateVertexData = function () {
  29625. 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 });
  29626. };
  29627. TorusKnot.prototype.copy = function (id) {
  29628. return new TorusKnot(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  29629. };
  29630. TorusKnot.prototype.serialize = function () {
  29631. var serializationObject = _super.prototype.serialize.call(this);
  29632. serializationObject.radius = this.radius;
  29633. serializationObject.tube = this.tube;
  29634. serializationObject.radialSegments = this.radialSegments;
  29635. serializationObject.tubularSegments = this.tubularSegments;
  29636. serializationObject.p = this.p;
  29637. serializationObject.q = this.q;
  29638. return serializationObject;
  29639. };
  29640. ;
  29641. TorusKnot.Parse = function (parsedTorusKnot, scene) {
  29642. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  29643. return null; // null since geometry could be something else than a ground...
  29644. }
  29645. var torusKnot = new Geometry.Primitives.TorusKnot(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  29646. if (BABYLON.Tags) {
  29647. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  29648. }
  29649. scene.pushGeometry(torusKnot, true);
  29650. return torusKnot;
  29651. };
  29652. return TorusKnot;
  29653. }(_Primitive));
  29654. Primitives.TorusKnot = TorusKnot;
  29655. })(Primitives = Geometry.Primitives || (Geometry.Primitives = {}));
  29656. })(Geometry = BABYLON.Geometry || (BABYLON.Geometry = {}));
  29657. })(BABYLON || (BABYLON = {}));
  29658. //# sourceMappingURL=babylon.geometry.js.map
  29659. var BABYLON;
  29660. (function (BABYLON) {
  29661. var PostProcessManager = (function () {
  29662. function PostProcessManager(scene) {
  29663. this._vertexBuffers = {};
  29664. this._scene = scene;
  29665. }
  29666. PostProcessManager.prototype._prepareBuffers = function () {
  29667. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  29668. return;
  29669. }
  29670. // VBO
  29671. var vertices = [];
  29672. vertices.push(1, 1);
  29673. vertices.push(-1, 1);
  29674. vertices.push(-1, -1);
  29675. vertices.push(1, -1);
  29676. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  29677. // Indices
  29678. var indices = [];
  29679. indices.push(0);
  29680. indices.push(1);
  29681. indices.push(2);
  29682. indices.push(0);
  29683. indices.push(2);
  29684. indices.push(3);
  29685. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  29686. };
  29687. // Methods
  29688. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  29689. var postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29690. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29691. return false;
  29692. }
  29693. postProcesses[0].activate(this._scene.activeCamera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  29694. return true;
  29695. };
  29696. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  29697. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  29698. var engine = this._scene.getEngine();
  29699. for (var index = 0; index < postProcesses.length; index++) {
  29700. if (index < postProcesses.length - 1) {
  29701. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29702. }
  29703. else {
  29704. if (targetTexture) {
  29705. engine.bindFramebuffer(targetTexture, 0, null, null, forceFullscreenViewport);
  29706. }
  29707. else {
  29708. engine.restoreDefaultFramebuffer();
  29709. }
  29710. }
  29711. var pp = postProcesses[index];
  29712. var effect = pp.apply();
  29713. if (effect) {
  29714. pp.onBeforeRenderObservable.notifyObservers(effect);
  29715. // VBOs
  29716. this._prepareBuffers();
  29717. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29718. // Draw order
  29719. engine.draw(true, 0, 6);
  29720. pp.onAfterRenderObservable.notifyObservers(effect);
  29721. }
  29722. }
  29723. // Restore depth buffer
  29724. engine.setDepthBuffer(true);
  29725. engine.setDepthWrite(true);
  29726. };
  29727. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses) {
  29728. postProcesses = postProcesses || this._scene.activeCamera._postProcesses;
  29729. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  29730. return;
  29731. }
  29732. var engine = this._scene.getEngine();
  29733. for (var index = 0, len = postProcesses.length; index < len; index++) {
  29734. if (index < len - 1) {
  29735. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  29736. }
  29737. else {
  29738. if (targetTexture) {
  29739. engine.bindFramebuffer(targetTexture, faceIndex);
  29740. }
  29741. else {
  29742. engine.restoreDefaultFramebuffer();
  29743. }
  29744. }
  29745. if (doNotPresent) {
  29746. break;
  29747. }
  29748. var pp = postProcesses[index];
  29749. var effect = pp.apply();
  29750. if (effect) {
  29751. pp.onBeforeRenderObservable.notifyObservers(effect);
  29752. // VBOs
  29753. this._prepareBuffers();
  29754. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  29755. // Draw order
  29756. engine.draw(true, 0, 6);
  29757. pp.onAfterRenderObservable.notifyObservers(effect);
  29758. }
  29759. }
  29760. // Restore states
  29761. engine.setDepthBuffer(true);
  29762. engine.setDepthWrite(true);
  29763. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  29764. };
  29765. PostProcessManager.prototype.dispose = function () {
  29766. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  29767. if (buffer) {
  29768. buffer.dispose();
  29769. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  29770. }
  29771. if (this._indexBuffer) {
  29772. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  29773. this._indexBuffer = null;
  29774. }
  29775. };
  29776. return PostProcessManager;
  29777. }());
  29778. BABYLON.PostProcessManager = PostProcessManager;
  29779. })(BABYLON || (BABYLON = {}));
  29780. //# sourceMappingURL=babylon.postProcessManager.js.map
  29781. var BABYLON;
  29782. (function (BABYLON) {
  29783. /**
  29784. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  29785. */
  29786. var PerformanceMonitor = (function () {
  29787. /**
  29788. * constructor
  29789. * @param frameSampleSize The number of samples required to saturate the sliding window
  29790. */
  29791. function PerformanceMonitor(frameSampleSize) {
  29792. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  29793. this._enabled = true;
  29794. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  29795. }
  29796. /**
  29797. * Samples current frame
  29798. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  29799. */
  29800. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  29801. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  29802. if (!this._enabled)
  29803. return;
  29804. if (this._lastFrameTimeMs != null) {
  29805. var dt = timeMs - this._lastFrameTimeMs;
  29806. this._rollingFrameTime.add(dt);
  29807. }
  29808. this._lastFrameTimeMs = timeMs;
  29809. };
  29810. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  29811. /**
  29812. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29813. * @return Average frame time in milliseconds
  29814. */
  29815. get: function () {
  29816. return this._rollingFrameTime.average;
  29817. },
  29818. enumerable: true,
  29819. configurable: true
  29820. });
  29821. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  29822. /**
  29823. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  29824. * @return Frame time variance in milliseconds squared
  29825. */
  29826. get: function () {
  29827. return this._rollingFrameTime.variance;
  29828. },
  29829. enumerable: true,
  29830. configurable: true
  29831. });
  29832. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  29833. /**
  29834. * Returns the frame time of the most recent frame
  29835. * @return Frame time in milliseconds
  29836. */
  29837. get: function () {
  29838. return this._rollingFrameTime.history(0);
  29839. },
  29840. enumerable: true,
  29841. configurable: true
  29842. });
  29843. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  29844. /**
  29845. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  29846. * @return Framerate in frames per second
  29847. */
  29848. get: function () {
  29849. return 1000.0 / this._rollingFrameTime.average;
  29850. },
  29851. enumerable: true,
  29852. configurable: true
  29853. });
  29854. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  29855. /**
  29856. * Returns the average framerate in frames per second using the most recent frame time
  29857. * @return Framerate in frames per second
  29858. */
  29859. get: function () {
  29860. return 1000.0 / this._rollingFrameTime.history(0);
  29861. },
  29862. enumerable: true,
  29863. configurable: true
  29864. });
  29865. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  29866. /**
  29867. * Returns true if enough samples have been taken to completely fill the sliding window
  29868. * @return true if saturated
  29869. */
  29870. get: function () {
  29871. return this._rollingFrameTime.isSaturated();
  29872. },
  29873. enumerable: true,
  29874. configurable: true
  29875. });
  29876. /**
  29877. * Enables contributions to the sliding window sample set
  29878. */
  29879. PerformanceMonitor.prototype.enable = function () {
  29880. this._enabled = true;
  29881. };
  29882. /**
  29883. * Disables contributions to the sliding window sample set
  29884. * Samples will not be interpolated over the disabled period
  29885. */
  29886. PerformanceMonitor.prototype.disable = function () {
  29887. this._enabled = false;
  29888. //clear last sample to avoid interpolating over the disabled period when next enabled
  29889. this._lastFrameTimeMs = null;
  29890. this._lastChangeTimeMs = null;
  29891. };
  29892. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  29893. /**
  29894. * Returns true if sampling is enabled
  29895. * @return true if enabled
  29896. */
  29897. get: function () {
  29898. return this._enabled;
  29899. },
  29900. enumerable: true,
  29901. configurable: true
  29902. });
  29903. /**
  29904. * Resets performance monitor
  29905. */
  29906. PerformanceMonitor.prototype.reset = function () {
  29907. //clear last sample to avoid interpolating over the disabled period when next enabled
  29908. this._lastFrameTimeMs = null;
  29909. this._lastChangeTimeMs = null;
  29910. //wipe record
  29911. this._rollingFrameTime.reset();
  29912. };
  29913. return PerformanceMonitor;
  29914. }());
  29915. BABYLON.PerformanceMonitor = PerformanceMonitor;
  29916. /**
  29917. * RollingAverage
  29918. *
  29919. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  29920. */
  29921. var RollingAverage = (function () {
  29922. /**
  29923. * constructor
  29924. * @param length The number of samples required to saturate the sliding window
  29925. */
  29926. function RollingAverage(length) {
  29927. this._samples = new Array(length);
  29928. this.reset();
  29929. }
  29930. /**
  29931. * Adds a sample to the sample set
  29932. * @param v The sample value
  29933. */
  29934. RollingAverage.prototype.add = function (v) {
  29935. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  29936. var delta;
  29937. //we need to check if we've already wrapped round
  29938. if (this.isSaturated()) {
  29939. //remove bottom of stack from mean
  29940. var bottomValue = this._samples[this._pos];
  29941. delta = bottomValue - this.average;
  29942. this.average -= delta / (this._sampleCount - 1);
  29943. this._m2 -= delta * (bottomValue - this.average);
  29944. }
  29945. else {
  29946. this._sampleCount++;
  29947. }
  29948. //add new value to mean
  29949. delta = v - this.average;
  29950. this.average += delta / (this._sampleCount);
  29951. this._m2 += delta * (v - this.average);
  29952. //set the new variance
  29953. this.variance = this._m2 / (this._sampleCount - 1);
  29954. this._samples[this._pos] = v;
  29955. this._pos++;
  29956. this._pos %= this._samples.length; //positive wrap around
  29957. };
  29958. /**
  29959. * Returns previously added values or null if outside of history or outside the sliding window domain
  29960. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  29961. * @return Value previously recorded with add() or null if outside of range
  29962. */
  29963. RollingAverage.prototype.history = function (i) {
  29964. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  29965. return null;
  29966. }
  29967. var i0 = this._wrapPosition(this._pos - 1.0);
  29968. return this._samples[this._wrapPosition(i0 - i)];
  29969. };
  29970. /**
  29971. * Returns true if enough samples have been taken to completely fill the sliding window
  29972. * @return true if sample-set saturated
  29973. */
  29974. RollingAverage.prototype.isSaturated = function () {
  29975. return this._sampleCount >= this._samples.length;
  29976. };
  29977. /**
  29978. * Resets the rolling average (equivalent to 0 samples taken so far)
  29979. */
  29980. RollingAverage.prototype.reset = function () {
  29981. this.average = 0;
  29982. this.variance = 0;
  29983. this._sampleCount = 0;
  29984. this._pos = 0;
  29985. this._m2 = 0;
  29986. };
  29987. /**
  29988. * Wraps a value around the sample range boundaries
  29989. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  29990. * @return Wrapped position in sample range
  29991. */
  29992. RollingAverage.prototype._wrapPosition = function (i) {
  29993. var max = this._samples.length;
  29994. return ((i % max) + max) % max;
  29995. };
  29996. return RollingAverage;
  29997. }());
  29998. BABYLON.RollingAverage = RollingAverage;
  29999. })(BABYLON || (BABYLON = {}));
  30000. //# sourceMappingURL=babylon.performanceMonitor.js.map
  30001. var BABYLON;
  30002. (function (BABYLON) {
  30003. var StandardMaterialDefines = (function (_super) {
  30004. __extends(StandardMaterialDefines, _super);
  30005. function StandardMaterialDefines() {
  30006. var _this = _super.call(this) || this;
  30007. _this.MAINUV1 = false;
  30008. _this.MAINUV2 = false;
  30009. _this.DIFFUSE = false;
  30010. _this.DIFFUSEDIRECTUV = 0;
  30011. _this.AMBIENT = false;
  30012. _this.AMBIENTDIRECTUV = 0;
  30013. _this.OPACITY = false;
  30014. _this.OPACITYDIRECTUV = 0;
  30015. _this.OPACITYRGB = false;
  30016. _this.REFLECTION = false;
  30017. _this.EMISSIVE = false;
  30018. _this.EMISSIVEDIRECTUV = 0;
  30019. _this.SPECULAR = false;
  30020. _this.SPECULARDIRECTUV = 0;
  30021. _this.BUMP = false;
  30022. _this.BUMPDIRECTUV = 0;
  30023. _this.PARALLAX = false;
  30024. _this.PARALLAXOCCLUSION = false;
  30025. _this.SPECULAROVERALPHA = false;
  30026. _this.CLIPPLANE = false;
  30027. _this.ALPHATEST = false;
  30028. _this.ALPHAFROMDIFFUSE = false;
  30029. _this.POINTSIZE = false;
  30030. _this.FOG = false;
  30031. _this.SPECULARTERM = false;
  30032. _this.DIFFUSEFRESNEL = false;
  30033. _this.OPACITYFRESNEL = false;
  30034. _this.REFLECTIONFRESNEL = false;
  30035. _this.REFRACTIONFRESNEL = false;
  30036. _this.EMISSIVEFRESNEL = false;
  30037. _this.FRESNEL = false;
  30038. _this.NORMAL = false;
  30039. _this.UV1 = false;
  30040. _this.UV2 = false;
  30041. _this.VERTEXCOLOR = false;
  30042. _this.VERTEXALPHA = false;
  30043. _this.NUM_BONE_INFLUENCERS = 0;
  30044. _this.BonesPerMesh = 0;
  30045. _this.INSTANCES = false;
  30046. _this.GLOSSINESS = false;
  30047. _this.ROUGHNESS = false;
  30048. _this.EMISSIVEASILLUMINATION = false;
  30049. _this.LINKEMISSIVEWITHDIFFUSE = false;
  30050. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  30051. _this.LIGHTMAP = false;
  30052. _this.LIGHTMAPDIRECTUV = 0;
  30053. _this.USELIGHTMAPASSHADOWMAP = false;
  30054. _this.REFLECTIONMAP_3D = false;
  30055. _this.REFLECTIONMAP_SPHERICAL = false;
  30056. _this.REFLECTIONMAP_PLANAR = false;
  30057. _this.REFLECTIONMAP_CUBIC = false;
  30058. _this.REFLECTIONMAP_PROJECTION = false;
  30059. _this.REFLECTIONMAP_SKYBOX = false;
  30060. _this.REFLECTIONMAP_EXPLICIT = false;
  30061. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  30062. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  30063. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  30064. _this.INVERTCUBICMAP = false;
  30065. _this.LOGARITHMICDEPTH = false;
  30066. _this.REFRACTION = false;
  30067. _this.REFRACTIONMAP_3D = false;
  30068. _this.REFLECTIONOVERALPHA = false;
  30069. _this.TWOSIDEDLIGHTING = false;
  30070. _this.SHADOWFLOAT = false;
  30071. _this.MORPHTARGETS = false;
  30072. _this.MORPHTARGETS_NORMAL = false;
  30073. _this.MORPHTARGETS_TANGENT = false;
  30074. _this.NUM_MORPH_INFLUENCERS = 0;
  30075. _this.USERIGHTHANDEDSYSTEM = false;
  30076. _this.IMAGEPROCESSING = false;
  30077. _this.VIGNETTE = false;
  30078. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  30079. _this.VIGNETTEBLENDMODEOPAQUE = false;
  30080. _this.TONEMAPPING = false;
  30081. _this.CONTRAST = false;
  30082. _this.COLORCURVES = false;
  30083. _this.COLORGRADING = false;
  30084. _this.SAMPLER3DGREENDEPTH = false;
  30085. _this.SAMPLER3DBGRMAP = false;
  30086. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  30087. _this.EXPOSURE = false;
  30088. _this.rebuild();
  30089. return _this;
  30090. }
  30091. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  30092. var modes = [
  30093. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  30094. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  30095. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  30096. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  30097. ];
  30098. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  30099. var mode = modes_1[_i];
  30100. this[mode] = (mode === modeToEnable);
  30101. }
  30102. };
  30103. return StandardMaterialDefines;
  30104. }(BABYLON.MaterialDefines));
  30105. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  30106. var StandardMaterial = (function (_super) {
  30107. __extends(StandardMaterial, _super);
  30108. function StandardMaterial(name, scene) {
  30109. var _this = _super.call(this, name, scene) || this;
  30110. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  30111. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  30112. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  30113. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  30114. _this.specularPower = 64;
  30115. _this._useAlphaFromDiffuseTexture = false;
  30116. _this._useEmissiveAsIllumination = false;
  30117. _this._linkEmissiveWithDiffuse = false;
  30118. _this._useSpecularOverAlpha = false;
  30119. _this._useReflectionOverAlpha = false;
  30120. _this._disableLighting = false;
  30121. _this._useParallax = false;
  30122. _this._useParallaxOcclusion = false;
  30123. _this.parallaxScaleBias = 0.05;
  30124. _this._roughness = 0;
  30125. _this.indexOfRefraction = 0.98;
  30126. _this.invertRefractionY = true;
  30127. _this._useLightmapAsShadowmap = false;
  30128. _this._useReflectionFresnelFromSpecular = false;
  30129. _this._useGlossinessFromSpecularMapAlpha = false;
  30130. _this._maxSimultaneousLights = 4;
  30131. /**
  30132. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  30133. */
  30134. _this._invertNormalMapX = false;
  30135. /**
  30136. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  30137. */
  30138. _this._invertNormalMapY = false;
  30139. /**
  30140. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  30141. */
  30142. _this._twoSidedLighting = false;
  30143. _this._renderTargets = new BABYLON.SmartArray(16);
  30144. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  30145. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  30146. // Setup the default processing configuration to the scene.
  30147. _this._attachImageProcessingConfiguration(null);
  30148. _this.getRenderTargetTextures = function () {
  30149. _this._renderTargets.reset();
  30150. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  30151. _this._renderTargets.push(_this._reflectionTexture);
  30152. }
  30153. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  30154. _this._renderTargets.push(_this._refractionTexture);
  30155. }
  30156. return _this._renderTargets;
  30157. };
  30158. return _this;
  30159. }
  30160. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  30161. /**
  30162. * Gets the image processing configuration used either in this material.
  30163. */
  30164. get: function () {
  30165. return this._imageProcessingConfiguration;
  30166. },
  30167. /**
  30168. * Sets the Default image processing configuration used either in the this material.
  30169. *
  30170. * If sets to null, the scene one is in use.
  30171. */
  30172. set: function (value) {
  30173. this._attachImageProcessingConfiguration(value);
  30174. // Ensure the effect will be rebuilt.
  30175. this._markAllSubMeshesAsTexturesDirty();
  30176. },
  30177. enumerable: true,
  30178. configurable: true
  30179. });
  30180. /**
  30181. * Attaches a new image processing configuration to the Standard Material.
  30182. * @param configuration
  30183. */
  30184. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  30185. var _this = this;
  30186. if (configuration === this._imageProcessingConfiguration) {
  30187. return;
  30188. }
  30189. // Detaches observer.
  30190. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  30191. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  30192. }
  30193. // Pick the scene configuration if needed.
  30194. if (!configuration) {
  30195. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  30196. }
  30197. else {
  30198. this._imageProcessingConfiguration = configuration;
  30199. }
  30200. // Attaches observer.
  30201. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  30202. _this._markAllSubMeshesAsImageProcessingDirty();
  30203. });
  30204. };
  30205. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  30206. /**
  30207. * Gets wether the color curves effect is enabled.
  30208. */
  30209. get: function () {
  30210. return this.imageProcessingConfiguration.colorCurvesEnabled;
  30211. },
  30212. /**
  30213. * Sets wether the color curves effect is enabled.
  30214. */
  30215. set: function (value) {
  30216. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  30217. },
  30218. enumerable: true,
  30219. configurable: true
  30220. });
  30221. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  30222. /**
  30223. * Gets wether the color grading effect is enabled.
  30224. */
  30225. get: function () {
  30226. return this.imageProcessingConfiguration.colorGradingEnabled;
  30227. },
  30228. /**
  30229. * Gets wether the color grading effect is enabled.
  30230. */
  30231. set: function (value) {
  30232. this.imageProcessingConfiguration.colorGradingEnabled = value;
  30233. },
  30234. enumerable: true,
  30235. configurable: true
  30236. });
  30237. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  30238. /**
  30239. * Gets wether tonemapping is enabled or not.
  30240. */
  30241. get: function () {
  30242. return this._imageProcessingConfiguration.toneMappingEnabled;
  30243. },
  30244. /**
  30245. * Sets wether tonemapping is enabled or not
  30246. */
  30247. set: function (value) {
  30248. this._imageProcessingConfiguration.toneMappingEnabled = value;
  30249. },
  30250. enumerable: true,
  30251. configurable: true
  30252. });
  30253. ;
  30254. ;
  30255. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  30256. /**
  30257. * The camera exposure used on this material.
  30258. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30259. * This corresponds to a photographic exposure.
  30260. */
  30261. get: function () {
  30262. return this._imageProcessingConfiguration.exposure;
  30263. },
  30264. /**
  30265. * The camera exposure used on this material.
  30266. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  30267. * This corresponds to a photographic exposure.
  30268. */
  30269. set: function (value) {
  30270. this._imageProcessingConfiguration.exposure = value;
  30271. },
  30272. enumerable: true,
  30273. configurable: true
  30274. });
  30275. ;
  30276. ;
  30277. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  30278. /**
  30279. * Gets The camera contrast used on this material.
  30280. */
  30281. get: function () {
  30282. return this._imageProcessingConfiguration.contrast;
  30283. },
  30284. /**
  30285. * Sets The camera contrast used on this material.
  30286. */
  30287. set: function (value) {
  30288. this._imageProcessingConfiguration.contrast = value;
  30289. },
  30290. enumerable: true,
  30291. configurable: true
  30292. });
  30293. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  30294. /**
  30295. * Gets the Color Grading 2D Lookup Texture.
  30296. */
  30297. get: function () {
  30298. return this._imageProcessingConfiguration.colorGradingTexture;
  30299. },
  30300. /**
  30301. * Sets the Color Grading 2D Lookup Texture.
  30302. */
  30303. set: function (value) {
  30304. this._imageProcessingConfiguration.colorGradingTexture = value;
  30305. },
  30306. enumerable: true,
  30307. configurable: true
  30308. });
  30309. StandardMaterial.prototype.getClassName = function () {
  30310. return "StandardMaterial";
  30311. };
  30312. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  30313. get: function () {
  30314. return this._useLogarithmicDepth;
  30315. },
  30316. set: function (value) {
  30317. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  30318. this._markAllSubMeshesAsMiscDirty();
  30319. },
  30320. enumerable: true,
  30321. configurable: true
  30322. });
  30323. StandardMaterial.prototype.needAlphaBlending = function () {
  30324. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  30325. };
  30326. StandardMaterial.prototype.needAlphaTesting = function () {
  30327. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  30328. };
  30329. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  30330. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  30331. };
  30332. StandardMaterial.prototype.getAlphaTestTexture = function () {
  30333. return this._diffuseTexture;
  30334. };
  30335. /**
  30336. * Child classes can use it to update shaders
  30337. */
  30338. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  30339. if (this.isFrozen) {
  30340. if (this._wasPreviouslyReady && subMesh.effect) {
  30341. return true;
  30342. }
  30343. }
  30344. if (!subMesh._materialDefines) {
  30345. subMesh._materialDefines = new StandardMaterialDefines();
  30346. }
  30347. var scene = this.getScene();
  30348. var defines = subMesh._materialDefines;
  30349. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  30350. if (defines._renderId === scene.getRenderId()) {
  30351. return true;
  30352. }
  30353. }
  30354. var engine = scene.getEngine();
  30355. // Lights
  30356. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  30357. // Textures
  30358. if (defines._areTexturesDirty) {
  30359. defines._needUVs = false;
  30360. defines.MAINUV1 = false;
  30361. defines.MAINUV2 = false;
  30362. if (scene.texturesEnabled) {
  30363. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30364. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  30365. return false;
  30366. }
  30367. else {
  30368. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  30369. }
  30370. }
  30371. else {
  30372. defines.DIFFUSE = false;
  30373. }
  30374. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30375. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  30376. return false;
  30377. }
  30378. else {
  30379. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  30380. }
  30381. }
  30382. else {
  30383. defines.AMBIENT = false;
  30384. }
  30385. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30386. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  30387. return false;
  30388. }
  30389. else {
  30390. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  30391. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  30392. }
  30393. }
  30394. else {
  30395. defines.OPACITY = false;
  30396. }
  30397. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30398. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  30399. return false;
  30400. }
  30401. else {
  30402. defines._needNormals = true;
  30403. defines.REFLECTION = true;
  30404. defines.ROUGHNESS = (this._roughness > 0);
  30405. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  30406. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  30407. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  30408. switch (this._reflectionTexture.coordinatesMode) {
  30409. case BABYLON.Texture.CUBIC_MODE:
  30410. case BABYLON.Texture.INVCUBIC_MODE:
  30411. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  30412. break;
  30413. case BABYLON.Texture.EXPLICIT_MODE:
  30414. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  30415. break;
  30416. case BABYLON.Texture.PLANAR_MODE:
  30417. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  30418. break;
  30419. case BABYLON.Texture.PROJECTION_MODE:
  30420. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  30421. break;
  30422. case BABYLON.Texture.SKYBOX_MODE:
  30423. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  30424. break;
  30425. case BABYLON.Texture.SPHERICAL_MODE:
  30426. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  30427. break;
  30428. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  30429. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  30430. break;
  30431. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  30432. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  30433. break;
  30434. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  30435. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  30436. break;
  30437. }
  30438. }
  30439. }
  30440. else {
  30441. defines.REFLECTION = false;
  30442. }
  30443. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30444. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  30445. return false;
  30446. }
  30447. else {
  30448. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  30449. }
  30450. }
  30451. else {
  30452. defines.EMISSIVE = false;
  30453. }
  30454. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30455. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  30456. return false;
  30457. }
  30458. else {
  30459. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  30460. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  30461. }
  30462. }
  30463. else {
  30464. defines.LIGHTMAP = false;
  30465. }
  30466. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30467. if (!this._specularTexture.isReadyOrNotBlocking()) {
  30468. return false;
  30469. }
  30470. else {
  30471. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  30472. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  30473. }
  30474. }
  30475. else {
  30476. defines.SPECULAR = false;
  30477. }
  30478. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  30479. // Bump texure can not be not blocking.
  30480. if (!this._bumpTexture.isReady()) {
  30481. return false;
  30482. }
  30483. else {
  30484. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  30485. defines.PARALLAX = this._useParallax;
  30486. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  30487. }
  30488. }
  30489. else {
  30490. defines.BUMP = false;
  30491. }
  30492. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30493. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  30494. return false;
  30495. }
  30496. else {
  30497. defines._needUVs = true;
  30498. defines.REFRACTION = true;
  30499. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  30500. }
  30501. }
  30502. else {
  30503. defines.REFRACTION = false;
  30504. }
  30505. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  30506. }
  30507. else {
  30508. defines.DIFFUSE = false;
  30509. defines.AMBIENT = false;
  30510. defines.OPACITY = false;
  30511. defines.REFLECTION = false;
  30512. defines.EMISSIVE = false;
  30513. defines.LIGHTMAP = false;
  30514. defines.BUMP = false;
  30515. defines.REFRACTION = false;
  30516. }
  30517. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  30518. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  30519. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  30520. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  30521. }
  30522. if (defines._areImageProcessingDirty) {
  30523. if (!this._imageProcessingConfiguration.isReady()) {
  30524. return false;
  30525. }
  30526. this._imageProcessingConfiguration.prepareDefines(defines);
  30527. }
  30528. if (defines._areFresnelDirty) {
  30529. if (StandardMaterial.FresnelEnabled) {
  30530. // Fresnel
  30531. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  30532. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  30533. this._reflectionFresnelParameters) {
  30534. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  30535. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  30536. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  30537. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  30538. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  30539. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  30540. defines._needNormals = true;
  30541. defines.FRESNEL = true;
  30542. }
  30543. }
  30544. else {
  30545. defines.FRESNEL = false;
  30546. }
  30547. }
  30548. // Misc.
  30549. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  30550. // Attribs
  30551. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  30552. // Values that need to be evaluated on every frame
  30553. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  30554. // Get correct effect
  30555. if (defines.isDirty) {
  30556. defines.markAsProcessed();
  30557. scene.resetCachedMaterial();
  30558. // Fallbacks
  30559. var fallbacks = new BABYLON.EffectFallbacks();
  30560. if (defines.REFLECTION) {
  30561. fallbacks.addFallback(0, "REFLECTION");
  30562. }
  30563. if (defines.SPECULAR) {
  30564. fallbacks.addFallback(0, "SPECULAR");
  30565. }
  30566. if (defines.BUMP) {
  30567. fallbacks.addFallback(0, "BUMP");
  30568. }
  30569. if (defines.PARALLAX) {
  30570. fallbacks.addFallback(1, "PARALLAX");
  30571. }
  30572. if (defines.PARALLAXOCCLUSION) {
  30573. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  30574. }
  30575. if (defines.SPECULAROVERALPHA) {
  30576. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  30577. }
  30578. if (defines.FOG) {
  30579. fallbacks.addFallback(1, "FOG");
  30580. }
  30581. if (defines.POINTSIZE) {
  30582. fallbacks.addFallback(0, "POINTSIZE");
  30583. }
  30584. if (defines.LOGARITHMICDEPTH) {
  30585. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  30586. }
  30587. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  30588. if (defines.SPECULARTERM) {
  30589. fallbacks.addFallback(0, "SPECULARTERM");
  30590. }
  30591. if (defines.DIFFUSEFRESNEL) {
  30592. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  30593. }
  30594. if (defines.OPACITYFRESNEL) {
  30595. fallbacks.addFallback(2, "OPACITYFRESNEL");
  30596. }
  30597. if (defines.REFLECTIONFRESNEL) {
  30598. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  30599. }
  30600. if (defines.EMISSIVEFRESNEL) {
  30601. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  30602. }
  30603. if (defines.FRESNEL) {
  30604. fallbacks.addFallback(4, "FRESNEL");
  30605. }
  30606. //Attributes
  30607. var attribs = [BABYLON.VertexBuffer.PositionKind];
  30608. if (defines.NORMAL) {
  30609. attribs.push(BABYLON.VertexBuffer.NormalKind);
  30610. }
  30611. if (defines.UV1) {
  30612. attribs.push(BABYLON.VertexBuffer.UVKind);
  30613. }
  30614. if (defines.UV2) {
  30615. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  30616. }
  30617. if (defines.VERTEXCOLOR) {
  30618. attribs.push(BABYLON.VertexBuffer.ColorKind);
  30619. }
  30620. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  30621. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  30622. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  30623. var shaderName = "default";
  30624. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  30625. "vFogInfos", "vFogColor", "pointSize",
  30626. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  30627. "mBones",
  30628. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  30629. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  30630. "logarithmicDepthConstant", "vNormalReoderParams"
  30631. ];
  30632. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  30633. var uniformBuffers = ["Material", "Scene"];
  30634. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  30635. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  30636. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  30637. uniformsNames: uniforms,
  30638. uniformBuffersNames: uniformBuffers,
  30639. samplers: samplers,
  30640. defines: defines,
  30641. maxSimultaneousLights: this._maxSimultaneousLights
  30642. });
  30643. if (this.customShaderNameResolve) {
  30644. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  30645. }
  30646. var join = defines.toString();
  30647. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  30648. attributes: attribs,
  30649. uniformsNames: uniforms,
  30650. uniformBuffersNames: uniformBuffers,
  30651. samplers: samplers,
  30652. defines: join,
  30653. fallbacks: fallbacks,
  30654. onCompiled: this.onCompiled,
  30655. onError: this.onError,
  30656. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  30657. }, engine), defines);
  30658. this.buildUniformLayout();
  30659. }
  30660. if (!subMesh.effect.isReady()) {
  30661. return false;
  30662. }
  30663. defines._renderId = scene.getRenderId();
  30664. this._wasPreviouslyReady = true;
  30665. return true;
  30666. };
  30667. StandardMaterial.prototype.buildUniformLayout = function () {
  30668. // Order is important !
  30669. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  30670. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  30671. this._uniformBuffer.addUniform("opacityParts", 4);
  30672. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  30673. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  30674. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  30675. this._uniformBuffer.addUniform("refractionRightColor", 4);
  30676. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  30677. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  30678. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  30679. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  30680. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  30681. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  30682. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  30683. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  30684. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  30685. this._uniformBuffer.addUniform("vBumpInfos", 3);
  30686. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  30687. this._uniformBuffer.addUniform("ambientMatrix", 16);
  30688. this._uniformBuffer.addUniform("opacityMatrix", 16);
  30689. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  30690. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  30691. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  30692. this._uniformBuffer.addUniform("specularMatrix", 16);
  30693. this._uniformBuffer.addUniform("bumpMatrix", 16);
  30694. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  30695. this._uniformBuffer.addUniform("refractionMatrix", 16);
  30696. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  30697. this._uniformBuffer.addUniform("vSpecularColor", 4);
  30698. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  30699. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  30700. this._uniformBuffer.addUniform("pointSize", 1);
  30701. this._uniformBuffer.create();
  30702. };
  30703. StandardMaterial.prototype.unbind = function () {
  30704. if (this._activeEffect) {
  30705. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  30706. this._activeEffect.setTexture("reflection2DSampler", null);
  30707. }
  30708. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  30709. this._activeEffect.setTexture("refraction2DSampler", null);
  30710. }
  30711. }
  30712. _super.prototype.unbind.call(this);
  30713. };
  30714. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  30715. var scene = this.getScene();
  30716. var defines = subMesh._materialDefines;
  30717. if (!defines) {
  30718. return;
  30719. }
  30720. var effect = subMesh.effect;
  30721. this._activeEffect = effect;
  30722. // Matrices
  30723. this.bindOnlyWorldMatrix(world);
  30724. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  30725. // Bones
  30726. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  30727. if (mustRebind) {
  30728. this._uniformBuffer.bindToEffect(effect, "Material");
  30729. this.bindViewProjection(effect);
  30730. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  30731. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  30732. // Fresnel
  30733. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  30734. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  30735. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  30736. }
  30737. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  30738. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  30739. }
  30740. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  30741. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  30742. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  30743. }
  30744. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  30745. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  30746. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  30747. }
  30748. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  30749. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  30750. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  30751. }
  30752. }
  30753. // Textures
  30754. if (scene.texturesEnabled) {
  30755. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30756. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  30757. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  30758. }
  30759. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30760. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  30761. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  30762. }
  30763. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30764. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  30765. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  30766. }
  30767. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30768. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  30769. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  30770. }
  30771. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30772. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  30773. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  30774. }
  30775. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30776. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  30777. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  30778. }
  30779. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30780. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  30781. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  30782. }
  30783. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30784. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  30785. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  30786. if (scene._mirroredCameraPosition) {
  30787. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 0 : 1.0, this.invertNormalMapX ? 1.0 : -1.0, this.invertNormalMapY ? 0 : 1.0, this.invertNormalMapY ? 1.0 : -1.0);
  30788. }
  30789. else {
  30790. this._uniformBuffer.updateFloat4("vNormalReoderParams", this.invertNormalMapX ? 1.0 : 0, this.invertNormalMapX ? -1.0 : 1.0, this.invertNormalMapY ? 1.0 : 0, this.invertNormalMapY ? -1.0 : 1.0);
  30791. }
  30792. }
  30793. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30794. var depth = 1.0;
  30795. if (!this._refractionTexture.isCube) {
  30796. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  30797. if (this._refractionTexture.depth) {
  30798. depth = this._refractionTexture.depth;
  30799. }
  30800. }
  30801. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  30802. }
  30803. }
  30804. // Point size
  30805. if (this.pointsCloud) {
  30806. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  30807. }
  30808. if (defines.SPECULARTERM) {
  30809. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  30810. }
  30811. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  30812. // Diffuse
  30813. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  30814. }
  30815. // Textures
  30816. if (scene.texturesEnabled) {
  30817. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  30818. effect.setTexture("diffuseSampler", this._diffuseTexture);
  30819. }
  30820. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  30821. effect.setTexture("ambientSampler", this._ambientTexture);
  30822. }
  30823. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  30824. effect.setTexture("opacitySampler", this._opacityTexture);
  30825. }
  30826. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  30827. if (this._reflectionTexture.isCube) {
  30828. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  30829. }
  30830. else {
  30831. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  30832. }
  30833. }
  30834. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  30835. effect.setTexture("emissiveSampler", this._emissiveTexture);
  30836. }
  30837. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  30838. effect.setTexture("lightmapSampler", this._lightmapTexture);
  30839. }
  30840. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  30841. effect.setTexture("specularSampler", this._specularTexture);
  30842. }
  30843. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  30844. effect.setTexture("bumpSampler", this._bumpTexture);
  30845. }
  30846. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  30847. var depth = 1.0;
  30848. if (this._refractionTexture.isCube) {
  30849. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  30850. }
  30851. else {
  30852. effect.setTexture("refraction2DSampler", this._refractionTexture);
  30853. }
  30854. }
  30855. }
  30856. // Clip plane
  30857. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  30858. // Colors
  30859. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  30860. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  30861. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  30862. }
  30863. if (mustRebind || !this.isFrozen) {
  30864. // Lights
  30865. if (scene.lightsEnabled && !this._disableLighting) {
  30866. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  30867. }
  30868. // View
  30869. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  30870. this.bindView(effect);
  30871. }
  30872. // Fog
  30873. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  30874. // Morph targets
  30875. if (defines.NUM_MORPH_INFLUENCERS) {
  30876. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  30877. }
  30878. // Log. depth
  30879. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  30880. // image processing
  30881. this._imageProcessingConfiguration.bind(this._activeEffect);
  30882. }
  30883. this._uniformBuffer.update();
  30884. this._afterBind(mesh, this._activeEffect);
  30885. };
  30886. StandardMaterial.prototype.getAnimatables = function () {
  30887. var results = [];
  30888. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  30889. results.push(this._diffuseTexture);
  30890. }
  30891. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  30892. results.push(this._ambientTexture);
  30893. }
  30894. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  30895. results.push(this._opacityTexture);
  30896. }
  30897. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  30898. results.push(this._reflectionTexture);
  30899. }
  30900. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  30901. results.push(this._emissiveTexture);
  30902. }
  30903. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  30904. results.push(this._specularTexture);
  30905. }
  30906. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  30907. results.push(this._bumpTexture);
  30908. }
  30909. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  30910. results.push(this._lightmapTexture);
  30911. }
  30912. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  30913. results.push(this._refractionTexture);
  30914. }
  30915. return results;
  30916. };
  30917. StandardMaterial.prototype.getActiveTextures = function () {
  30918. var activeTextures = _super.prototype.getActiveTextures.call(this);
  30919. if (this._diffuseTexture) {
  30920. activeTextures.push(this._diffuseTexture);
  30921. }
  30922. if (this._ambientTexture) {
  30923. activeTextures.push(this._ambientTexture);
  30924. }
  30925. if (this._opacityTexture) {
  30926. activeTextures.push(this._opacityTexture);
  30927. }
  30928. if (this._reflectionTexture) {
  30929. activeTextures.push(this._reflectionTexture);
  30930. }
  30931. if (this._emissiveTexture) {
  30932. activeTextures.push(this._emissiveTexture);
  30933. }
  30934. if (this._specularTexture) {
  30935. activeTextures.push(this._specularTexture);
  30936. }
  30937. if (this._bumpTexture) {
  30938. activeTextures.push(this._bumpTexture);
  30939. }
  30940. if (this._lightmapTexture) {
  30941. activeTextures.push(this._lightmapTexture);
  30942. }
  30943. if (this._refractionTexture) {
  30944. activeTextures.push(this._refractionTexture);
  30945. }
  30946. return activeTextures;
  30947. };
  30948. StandardMaterial.prototype.hasTexture = function (texture) {
  30949. if (_super.prototype.hasTexture.call(this, texture)) {
  30950. return true;
  30951. }
  30952. if (this._diffuseTexture === texture) {
  30953. return true;
  30954. }
  30955. if (this._ambientTexture === texture) {
  30956. return true;
  30957. }
  30958. if (this._opacityTexture === texture) {
  30959. return true;
  30960. }
  30961. if (this._reflectionTexture === texture) {
  30962. return true;
  30963. }
  30964. if (this._emissiveTexture === texture) {
  30965. return true;
  30966. }
  30967. if (this._specularTexture === texture) {
  30968. return true;
  30969. }
  30970. if (this._bumpTexture === texture) {
  30971. return true;
  30972. }
  30973. if (this._lightmapTexture === texture) {
  30974. return true;
  30975. }
  30976. if (this._refractionTexture === texture) {
  30977. return true;
  30978. }
  30979. return false;
  30980. };
  30981. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  30982. if (forceDisposeTextures) {
  30983. if (this._diffuseTexture) {
  30984. this._diffuseTexture.dispose();
  30985. }
  30986. if (this._ambientTexture) {
  30987. this._ambientTexture.dispose();
  30988. }
  30989. if (this._opacityTexture) {
  30990. this._opacityTexture.dispose();
  30991. }
  30992. if (this._reflectionTexture) {
  30993. this._reflectionTexture.dispose();
  30994. }
  30995. if (this._emissiveTexture) {
  30996. this._emissiveTexture.dispose();
  30997. }
  30998. if (this._specularTexture) {
  30999. this._specularTexture.dispose();
  31000. }
  31001. if (this._bumpTexture) {
  31002. this._bumpTexture.dispose();
  31003. }
  31004. if (this._lightmapTexture) {
  31005. this._lightmapTexture.dispose();
  31006. }
  31007. if (this._refractionTexture) {
  31008. this._refractionTexture.dispose();
  31009. }
  31010. }
  31011. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31012. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31013. }
  31014. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  31015. };
  31016. StandardMaterial.prototype.clone = function (name) {
  31017. var _this = this;
  31018. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  31019. result.name = name;
  31020. result.id = name;
  31021. return result;
  31022. };
  31023. StandardMaterial.prototype.serialize = function () {
  31024. return BABYLON.SerializationHelper.Serialize(this);
  31025. };
  31026. // Statics
  31027. StandardMaterial.Parse = function (source, scene, rootUrl) {
  31028. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  31029. };
  31030. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  31031. get: function () {
  31032. return StandardMaterial._DiffuseTextureEnabled;
  31033. },
  31034. set: function (value) {
  31035. if (StandardMaterial._DiffuseTextureEnabled === value) {
  31036. return;
  31037. }
  31038. StandardMaterial._DiffuseTextureEnabled = value;
  31039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31040. },
  31041. enumerable: true,
  31042. configurable: true
  31043. });
  31044. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  31045. get: function () {
  31046. return StandardMaterial._AmbientTextureEnabled;
  31047. },
  31048. set: function (value) {
  31049. if (StandardMaterial._AmbientTextureEnabled === value) {
  31050. return;
  31051. }
  31052. StandardMaterial._AmbientTextureEnabled = value;
  31053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31054. },
  31055. enumerable: true,
  31056. configurable: true
  31057. });
  31058. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  31059. get: function () {
  31060. return StandardMaterial._OpacityTextureEnabled;
  31061. },
  31062. set: function (value) {
  31063. if (StandardMaterial._OpacityTextureEnabled === value) {
  31064. return;
  31065. }
  31066. StandardMaterial._OpacityTextureEnabled = value;
  31067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31068. },
  31069. enumerable: true,
  31070. configurable: true
  31071. });
  31072. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  31073. get: function () {
  31074. return StandardMaterial._ReflectionTextureEnabled;
  31075. },
  31076. set: function (value) {
  31077. if (StandardMaterial._ReflectionTextureEnabled === value) {
  31078. return;
  31079. }
  31080. StandardMaterial._ReflectionTextureEnabled = value;
  31081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31082. },
  31083. enumerable: true,
  31084. configurable: true
  31085. });
  31086. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  31087. get: function () {
  31088. return StandardMaterial._EmissiveTextureEnabled;
  31089. },
  31090. set: function (value) {
  31091. if (StandardMaterial._EmissiveTextureEnabled === value) {
  31092. return;
  31093. }
  31094. StandardMaterial._EmissiveTextureEnabled = value;
  31095. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31096. },
  31097. enumerable: true,
  31098. configurable: true
  31099. });
  31100. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  31101. get: function () {
  31102. return StandardMaterial._SpecularTextureEnabled;
  31103. },
  31104. set: function (value) {
  31105. if (StandardMaterial._SpecularTextureEnabled === value) {
  31106. return;
  31107. }
  31108. StandardMaterial._SpecularTextureEnabled = value;
  31109. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31110. },
  31111. enumerable: true,
  31112. configurable: true
  31113. });
  31114. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  31115. get: function () {
  31116. return StandardMaterial._BumpTextureEnabled;
  31117. },
  31118. set: function (value) {
  31119. if (StandardMaterial._BumpTextureEnabled === value) {
  31120. return;
  31121. }
  31122. StandardMaterial._BumpTextureEnabled = value;
  31123. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31124. },
  31125. enumerable: true,
  31126. configurable: true
  31127. });
  31128. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  31129. get: function () {
  31130. return StandardMaterial._LightmapTextureEnabled;
  31131. },
  31132. set: function (value) {
  31133. if (StandardMaterial._LightmapTextureEnabled === value) {
  31134. return;
  31135. }
  31136. StandardMaterial._LightmapTextureEnabled = value;
  31137. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31138. },
  31139. enumerable: true,
  31140. configurable: true
  31141. });
  31142. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  31143. get: function () {
  31144. return StandardMaterial._RefractionTextureEnabled;
  31145. },
  31146. set: function (value) {
  31147. if (StandardMaterial._RefractionTextureEnabled === value) {
  31148. return;
  31149. }
  31150. StandardMaterial._RefractionTextureEnabled = value;
  31151. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31152. },
  31153. enumerable: true,
  31154. configurable: true
  31155. });
  31156. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  31157. get: function () {
  31158. return StandardMaterial._ColorGradingTextureEnabled;
  31159. },
  31160. set: function (value) {
  31161. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  31162. return;
  31163. }
  31164. StandardMaterial._ColorGradingTextureEnabled = value;
  31165. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  31166. },
  31167. enumerable: true,
  31168. configurable: true
  31169. });
  31170. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  31171. get: function () {
  31172. return StandardMaterial._FresnelEnabled;
  31173. },
  31174. set: function (value) {
  31175. if (StandardMaterial._FresnelEnabled === value) {
  31176. return;
  31177. }
  31178. StandardMaterial._FresnelEnabled = value;
  31179. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. // Flags used to enable or disable a type of texture for all Standard Materials
  31185. StandardMaterial._DiffuseTextureEnabled = true;
  31186. StandardMaterial._AmbientTextureEnabled = true;
  31187. StandardMaterial._OpacityTextureEnabled = true;
  31188. StandardMaterial._ReflectionTextureEnabled = true;
  31189. StandardMaterial._EmissiveTextureEnabled = true;
  31190. StandardMaterial._SpecularTextureEnabled = true;
  31191. StandardMaterial._BumpTextureEnabled = true;
  31192. StandardMaterial._LightmapTextureEnabled = true;
  31193. StandardMaterial._RefractionTextureEnabled = true;
  31194. StandardMaterial._ColorGradingTextureEnabled = true;
  31195. StandardMaterial._FresnelEnabled = true;
  31196. __decorate([
  31197. BABYLON.serializeAsTexture("diffuseTexture")
  31198. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  31199. __decorate([
  31200. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31201. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  31202. __decorate([
  31203. BABYLON.serializeAsTexture("ambientTexture")
  31204. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  31205. __decorate([
  31206. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31207. ], StandardMaterial.prototype, "ambientTexture", void 0);
  31208. __decorate([
  31209. BABYLON.serializeAsTexture("opacityTexture")
  31210. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  31211. __decorate([
  31212. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31213. ], StandardMaterial.prototype, "opacityTexture", void 0);
  31214. __decorate([
  31215. BABYLON.serializeAsTexture("reflectionTexture")
  31216. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  31217. __decorate([
  31218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31219. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  31220. __decorate([
  31221. BABYLON.serializeAsTexture("emissiveTexture")
  31222. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  31223. __decorate([
  31224. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31225. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  31226. __decorate([
  31227. BABYLON.serializeAsTexture("specularTexture")
  31228. ], StandardMaterial.prototype, "_specularTexture", void 0);
  31229. __decorate([
  31230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31231. ], StandardMaterial.prototype, "specularTexture", void 0);
  31232. __decorate([
  31233. BABYLON.serializeAsTexture("bumpTexture")
  31234. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  31235. __decorate([
  31236. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31237. ], StandardMaterial.prototype, "bumpTexture", void 0);
  31238. __decorate([
  31239. BABYLON.serializeAsTexture("lightmapTexture")
  31240. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  31241. __decorate([
  31242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31243. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  31244. __decorate([
  31245. BABYLON.serializeAsTexture("refractionTexture")
  31246. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  31247. __decorate([
  31248. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31249. ], StandardMaterial.prototype, "refractionTexture", void 0);
  31250. __decorate([
  31251. BABYLON.serializeAsColor3("ambient")
  31252. ], StandardMaterial.prototype, "ambientColor", void 0);
  31253. __decorate([
  31254. BABYLON.serializeAsColor3("diffuse")
  31255. ], StandardMaterial.prototype, "diffuseColor", void 0);
  31256. __decorate([
  31257. BABYLON.serializeAsColor3("specular")
  31258. ], StandardMaterial.prototype, "specularColor", void 0);
  31259. __decorate([
  31260. BABYLON.serializeAsColor3("emissive")
  31261. ], StandardMaterial.prototype, "emissiveColor", void 0);
  31262. __decorate([
  31263. BABYLON.serialize()
  31264. ], StandardMaterial.prototype, "specularPower", void 0);
  31265. __decorate([
  31266. BABYLON.serialize("useAlphaFromDiffuseTexture")
  31267. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  31268. __decorate([
  31269. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31270. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  31271. __decorate([
  31272. BABYLON.serialize("useEmissiveAsIllumination")
  31273. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  31274. __decorate([
  31275. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31276. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  31277. __decorate([
  31278. BABYLON.serialize("linkEmissiveWithDiffuse")
  31279. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  31280. __decorate([
  31281. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31282. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  31283. __decorate([
  31284. BABYLON.serialize("useSpecularOverAlpha")
  31285. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  31286. __decorate([
  31287. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31288. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  31289. __decorate([
  31290. BABYLON.serialize("useReflectionOverAlpha")
  31291. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  31292. __decorate([
  31293. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31294. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  31295. __decorate([
  31296. BABYLON.serialize("disableLighting")
  31297. ], StandardMaterial.prototype, "_disableLighting", void 0);
  31298. __decorate([
  31299. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31300. ], StandardMaterial.prototype, "disableLighting", void 0);
  31301. __decorate([
  31302. BABYLON.serialize("useParallax")
  31303. ], StandardMaterial.prototype, "_useParallax", void 0);
  31304. __decorate([
  31305. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31306. ], StandardMaterial.prototype, "useParallax", void 0);
  31307. __decorate([
  31308. BABYLON.serialize("useParallaxOcclusion")
  31309. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  31310. __decorate([
  31311. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31312. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  31313. __decorate([
  31314. BABYLON.serialize()
  31315. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  31316. __decorate([
  31317. BABYLON.serialize("roughness")
  31318. ], StandardMaterial.prototype, "_roughness", void 0);
  31319. __decorate([
  31320. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31321. ], StandardMaterial.prototype, "roughness", void 0);
  31322. __decorate([
  31323. BABYLON.serialize()
  31324. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  31325. __decorate([
  31326. BABYLON.serialize()
  31327. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  31328. __decorate([
  31329. BABYLON.serialize("useLightmapAsShadowmap")
  31330. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  31331. __decorate([
  31332. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31333. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  31334. __decorate([
  31335. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  31336. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  31337. __decorate([
  31338. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31339. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  31340. __decorate([
  31341. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  31342. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  31343. __decorate([
  31344. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31345. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  31346. __decorate([
  31347. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  31348. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  31349. __decorate([
  31350. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31351. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  31352. __decorate([
  31353. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  31354. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  31355. __decorate([
  31356. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31357. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  31358. __decorate([
  31359. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  31360. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  31361. __decorate([
  31362. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31363. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  31364. __decorate([
  31365. BABYLON.serialize("useReflectionFresnelFromSpecular")
  31366. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  31367. __decorate([
  31368. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  31369. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  31370. __decorate([
  31371. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  31372. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  31373. __decorate([
  31374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31375. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  31376. __decorate([
  31377. BABYLON.serialize("maxSimultaneousLights")
  31378. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  31379. __decorate([
  31380. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  31381. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  31382. __decorate([
  31383. BABYLON.serialize("invertNormalMapX")
  31384. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  31385. __decorate([
  31386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31387. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  31388. __decorate([
  31389. BABYLON.serialize("invertNormalMapY")
  31390. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  31391. __decorate([
  31392. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31393. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  31394. __decorate([
  31395. BABYLON.serialize("twoSidedLighting")
  31396. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  31397. __decorate([
  31398. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  31399. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  31400. __decorate([
  31401. BABYLON.serialize()
  31402. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  31403. return StandardMaterial;
  31404. }(BABYLON.PushMaterial));
  31405. BABYLON.StandardMaterial = StandardMaterial;
  31406. })(BABYLON || (BABYLON = {}));
  31407. //# sourceMappingURL=babylon.standardMaterial.js.map
  31408. var BABYLON;
  31409. (function (BABYLON) {
  31410. var PBRMaterialDefines = (function (_super) {
  31411. __extends(PBRMaterialDefines, _super);
  31412. function PBRMaterialDefines() {
  31413. var _this = _super.call(this) || this;
  31414. _this.PBR = true;
  31415. _this.MAINUV1 = false;
  31416. _this.MAINUV2 = false;
  31417. _this.UV1 = false;
  31418. _this.UV2 = false;
  31419. _this.ALBEDO = false;
  31420. _this.ALBEDODIRECTUV = 0;
  31421. _this.VERTEXCOLOR = false;
  31422. _this.AMBIENT = false;
  31423. _this.AMBIENTDIRECTUV = 0;
  31424. _this.AMBIENTINGRAYSCALE = false;
  31425. _this.OPACITY = false;
  31426. _this.VERTEXALPHA = false;
  31427. _this.OPACITYDIRECTUV = 0;
  31428. _this.OPACITYRGB = false;
  31429. _this.ALPHATEST = false;
  31430. _this.ALPHABLEND = false;
  31431. _this.ALPHAFROMALBEDO = false;
  31432. _this.ALPHATESTVALUE = 0.5;
  31433. _this.SPECULAROVERALPHA = false;
  31434. _this.RADIANCEOVERALPHA = false;
  31435. _this.ALPHAFRESNEL = false;
  31436. _this.PREMULTIPLYALPHA = false;
  31437. _this.EMISSIVE = false;
  31438. _this.EMISSIVEDIRECTUV = 0;
  31439. _this.REFLECTIVITY = false;
  31440. _this.REFLECTIVITYDIRECTUV = 0;
  31441. _this.SPECULARTERM = false;
  31442. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  31443. _this.MICROSURFACEAUTOMATIC = false;
  31444. _this.LODBASEDMICROSFURACE = false;
  31445. _this.MICROSURFACEMAP = false;
  31446. _this.MICROSURFACEMAPDIRECTUV = 0;
  31447. _this.METALLICWORKFLOW = false;
  31448. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  31449. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  31450. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  31451. _this.AOSTOREINMETALMAPRED = false;
  31452. _this.ENVIRONMENTBRDF = false;
  31453. _this.NORMAL = false;
  31454. _this.TANGENT = false;
  31455. _this.BUMP = false;
  31456. _this.BUMPDIRECTUV = 0;
  31457. _this.PARALLAX = false;
  31458. _this.PARALLAXOCCLUSION = false;
  31459. _this.NORMALXYSCALE = true;
  31460. _this.LIGHTMAP = false;
  31461. _this.LIGHTMAPDIRECTUV = 0;
  31462. _this.USELIGHTMAPASSHADOWMAP = false;
  31463. _this.REFLECTION = false;
  31464. _this.REFLECTIONMAP_3D = false;
  31465. _this.REFLECTIONMAP_SPHERICAL = false;
  31466. _this.REFLECTIONMAP_PLANAR = false;
  31467. _this.REFLECTIONMAP_CUBIC = false;
  31468. _this.REFLECTIONMAP_PROJECTION = false;
  31469. _this.REFLECTIONMAP_SKYBOX = false;
  31470. _this.REFLECTIONMAP_EXPLICIT = false;
  31471. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31472. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31473. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31474. _this.INVERTCUBICMAP = false;
  31475. _this.USESPHERICALFROMREFLECTIONMAP = false;
  31476. _this.USESPHERICALINFRAGMENT = false;
  31477. _this.REFLECTIONMAP_OPPOSITEZ = false;
  31478. _this.LODINREFLECTIONALPHA = false;
  31479. _this.GAMMAREFLECTION = false;
  31480. _this.REFRACTION = false;
  31481. _this.REFRACTIONMAP_3D = false;
  31482. _this.REFRACTIONMAP_OPPOSITEZ = false;
  31483. _this.LODINREFRACTIONALPHA = false;
  31484. _this.GAMMAREFRACTION = false;
  31485. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  31486. _this.INSTANCES = false;
  31487. _this.NUM_BONE_INFLUENCERS = 0;
  31488. _this.BonesPerMesh = 0;
  31489. _this.MORPHTARGETS = false;
  31490. _this.MORPHTARGETS_NORMAL = false;
  31491. _this.MORPHTARGETS_TANGENT = false;
  31492. _this.NUM_MORPH_INFLUENCERS = 0;
  31493. _this.IMAGEPROCESSING = false;
  31494. _this.VIGNETTE = false;
  31495. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  31496. _this.VIGNETTEBLENDMODEOPAQUE = false;
  31497. _this.TONEMAPPING = false;
  31498. _this.CONTRAST = false;
  31499. _this.COLORCURVES = false;
  31500. _this.COLORGRADING = false;
  31501. _this.SAMPLER3DGREENDEPTH = false;
  31502. _this.SAMPLER3DBGRMAP = false;
  31503. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  31504. _this.EXPOSURE = false;
  31505. _this.USEPHYSICALLIGHTFALLOFF = false;
  31506. _this.TWOSIDEDLIGHTING = false;
  31507. _this.SHADOWFLOAT = false;
  31508. _this.USERIGHTHANDEDSYSTEM = false;
  31509. _this.CLIPPLANE = false;
  31510. _this.POINTSIZE = false;
  31511. _this.FOG = false;
  31512. _this.LOGARITHMICDEPTH = false;
  31513. _this.FORCENORMALFORWARD = false;
  31514. _this.rebuild();
  31515. return _this;
  31516. }
  31517. PBRMaterialDefines.prototype.reset = function () {
  31518. _super.prototype.reset.call(this);
  31519. this.ALPHATESTVALUE = 0.5;
  31520. this.PBR = true;
  31521. };
  31522. return PBRMaterialDefines;
  31523. }(BABYLON.MaterialDefines));
  31524. /**
  31525. * The Physically based material base class of BJS.
  31526. *
  31527. * This offers the main features of a standard PBR material.
  31528. * For more information, please refer to the documentation :
  31529. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  31530. */
  31531. var PBRBaseMaterial = (function (_super) {
  31532. __extends(PBRBaseMaterial, _super);
  31533. /**
  31534. * Instantiates a new PBRMaterial instance.
  31535. *
  31536. * @param name The material name
  31537. * @param scene The scene the material will be use in.
  31538. */
  31539. function PBRBaseMaterial(name, scene) {
  31540. var _this = _super.call(this, name, scene) || this;
  31541. /**
  31542. * Intensity of the direct lights e.g. the four lights available in your scene.
  31543. * This impacts both the direct diffuse and specular highlights.
  31544. */
  31545. _this._directIntensity = 1.0;
  31546. /**
  31547. * Intensity of the emissive part of the material.
  31548. * This helps controlling the emissive effect without modifying the emissive color.
  31549. */
  31550. _this._emissiveIntensity = 1.0;
  31551. /**
  31552. * Intensity of the environment e.g. how much the environment will light the object
  31553. * either through harmonics for rough material or through the refelction for shiny ones.
  31554. */
  31555. _this._environmentIntensity = 1.0;
  31556. /**
  31557. * This is a special control allowing the reduction of the specular highlights coming from the
  31558. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  31559. */
  31560. _this._specularIntensity = 1.0;
  31561. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  31562. /**
  31563. * Debug Control allowing disabling the bump map on this material.
  31564. */
  31565. _this._disableBumpMap = false;
  31566. /**
  31567. * AKA Occlusion Texture Intensity in other nomenclature.
  31568. */
  31569. _this._ambientTextureStrength = 1.0;
  31570. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  31571. /**
  31572. * AKA Diffuse Color in other nomenclature.
  31573. */
  31574. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  31575. /**
  31576. * AKA Specular Color in other nomenclature.
  31577. */
  31578. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  31579. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  31580. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  31581. /**
  31582. * AKA Glossiness in other nomenclature.
  31583. */
  31584. _this._microSurface = 0.9;
  31585. /**
  31586. * source material index of refraction (IOR)' / 'destination material IOR.
  31587. */
  31588. _this._indexOfRefraction = 0.66;
  31589. /**
  31590. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  31591. */
  31592. _this._invertRefractionY = false;
  31593. /**
  31594. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  31595. * Materials half opaque for instance using refraction could benefit from this control.
  31596. */
  31597. _this._linkRefractionWithTransparency = false;
  31598. _this._useLightmapAsShadowmap = false;
  31599. /**
  31600. * Specifies that the alpha is coming form the albedo channel alpha channel.
  31601. */
  31602. _this._useAlphaFromAlbedoTexture = false;
  31603. /**
  31604. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  31605. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  31606. */
  31607. _this._useSpecularOverAlpha = true;
  31608. /**
  31609. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  31610. */
  31611. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  31612. /**
  31613. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  31614. */
  31615. _this._useRoughnessFromMetallicTextureAlpha = true;
  31616. /**
  31617. * Specifies if the metallic texture contains the roughness information in its green channel.
  31618. */
  31619. _this._useRoughnessFromMetallicTextureGreen = false;
  31620. /**
  31621. * Specifies if the metallic texture contains the metallness information in its blue channel.
  31622. */
  31623. _this._useMetallnessFromMetallicTextureBlue = false;
  31624. /**
  31625. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  31626. */
  31627. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  31628. /**
  31629. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  31630. */
  31631. _this._useAmbientInGrayScale = false;
  31632. /**
  31633. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  31634. * The material will try to infer what glossiness each pixel should be.
  31635. */
  31636. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  31637. /**
  31638. * BJS is using an harcoded light falloff based on a manually sets up range.
  31639. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  31640. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  31641. */
  31642. _this._usePhysicalLightFalloff = true;
  31643. /**
  31644. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  31645. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  31646. */
  31647. _this._useRadianceOverAlpha = true;
  31648. /**
  31649. * Allows using the bump map in parallax mode.
  31650. */
  31651. _this._useParallax = false;
  31652. /**
  31653. * Allows using the bump map in parallax occlusion mode.
  31654. */
  31655. _this._useParallaxOcclusion = false;
  31656. /**
  31657. * Controls the scale bias of the parallax mode.
  31658. */
  31659. _this._parallaxScaleBias = 0.05;
  31660. /**
  31661. * If sets to true, disables all the lights affecting the material.
  31662. */
  31663. _this._disableLighting = false;
  31664. /**
  31665. * Number of Simultaneous lights allowed on the material.
  31666. */
  31667. _this._maxSimultaneousLights = 4;
  31668. /**
  31669. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  31670. */
  31671. _this._invertNormalMapX = false;
  31672. /**
  31673. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  31674. */
  31675. _this._invertNormalMapY = false;
  31676. /**
  31677. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  31678. */
  31679. _this._twoSidedLighting = false;
  31680. /**
  31681. * Defines the alpha limits in alpha test mode.
  31682. */
  31683. _this._alphaCutOff = 0.4;
  31684. /**
  31685. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  31686. */
  31687. _this._forceAlphaTest = false;
  31688. /**
  31689. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  31690. * in your scene composition.
  31691. */
  31692. _this._preMultiplyAlpha = false;
  31693. /**
  31694. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  31695. * And/Or occlude the blended part.
  31696. */
  31697. _this._useAlphaFresnel = false;
  31698. /**
  31699. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  31700. * from cos thetav and roughness:
  31701. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  31702. */
  31703. _this._environmentBRDFTexture = null;
  31704. /**
  31705. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  31706. */
  31707. _this._forceIrradianceInFragment = false;
  31708. /**
  31709. * Force normal to face away from face.
  31710. * (Temporary internal fix to remove before 3.1)
  31711. */
  31712. _this._forceNormalForward = false;
  31713. _this._renderTargets = new BABYLON.SmartArray(16);
  31714. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  31715. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  31716. _this._tempColor = new BABYLON.Color3();
  31717. // Setup the default processing configuration to the scene.
  31718. _this._attachImageProcessingConfiguration(null);
  31719. _this.getRenderTargetTextures = function () {
  31720. _this._renderTargets.reset();
  31721. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  31722. _this._renderTargets.push(_this._reflectionTexture);
  31723. }
  31724. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  31725. _this._renderTargets.push(_this._refractionTexture);
  31726. }
  31727. return _this._renderTargets;
  31728. };
  31729. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  31730. return _this;
  31731. }
  31732. /**
  31733. * Attaches a new image processing configuration to the PBR Material.
  31734. * @param configuration
  31735. */
  31736. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  31737. var _this = this;
  31738. if (configuration === this._imageProcessingConfiguration) {
  31739. return;
  31740. }
  31741. // Detaches observer.
  31742. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  31743. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  31744. }
  31745. // Pick the scene configuration if needed.
  31746. if (!configuration) {
  31747. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  31748. }
  31749. else {
  31750. this._imageProcessingConfiguration = configuration;
  31751. }
  31752. // Attaches observer.
  31753. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  31754. _this._markAllSubMeshesAsImageProcessingDirty();
  31755. });
  31756. };
  31757. PBRBaseMaterial.prototype.getClassName = function () {
  31758. return "PBRBaseMaterial";
  31759. };
  31760. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  31761. get: function () {
  31762. return this._useLogarithmicDepth;
  31763. },
  31764. set: function (value) {
  31765. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  31766. },
  31767. enumerable: true,
  31768. configurable: true
  31769. });
  31770. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  31771. if (this._linkRefractionWithTransparency) {
  31772. return false;
  31773. }
  31774. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  31775. };
  31776. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  31777. if (this._forceAlphaTest) {
  31778. return true;
  31779. }
  31780. if (this._linkRefractionWithTransparency) {
  31781. return false;
  31782. }
  31783. return this._albedoTexture != null && this._albedoTexture.hasAlpha;
  31784. };
  31785. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  31786. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture;
  31787. };
  31788. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  31789. return this._albedoTexture;
  31790. };
  31791. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  31792. if (this.isFrozen) {
  31793. if (this._wasPreviouslyReady) {
  31794. return true;
  31795. }
  31796. }
  31797. if (!subMesh._materialDefines) {
  31798. subMesh._materialDefines = new PBRMaterialDefines();
  31799. }
  31800. var scene = this.getScene();
  31801. var defines = subMesh._materialDefines;
  31802. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  31803. if (defines._renderId === scene.getRenderId()) {
  31804. return true;
  31805. }
  31806. }
  31807. var engine = scene.getEngine();
  31808. // Lights
  31809. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  31810. defines._needNormals = true;
  31811. // Textures
  31812. if (defines._areTexturesDirty) {
  31813. defines._needUVs = false;
  31814. if (scene.texturesEnabled) {
  31815. if (scene.getEngine().getCaps().textureLOD) {
  31816. defines.LODBASEDMICROSFURACE = true;
  31817. }
  31818. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31819. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  31820. return false;
  31821. }
  31822. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  31823. }
  31824. else {
  31825. defines.ALBEDO = false;
  31826. }
  31827. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  31828. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  31829. return false;
  31830. }
  31831. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  31832. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  31833. }
  31834. else {
  31835. defines.AMBIENT = false;
  31836. }
  31837. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  31838. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  31839. return false;
  31840. }
  31841. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  31842. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  31843. }
  31844. else {
  31845. defines.OPACITY = false;
  31846. }
  31847. var reflectionTexture = this._getReflectionTexture();
  31848. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  31849. if (!reflectionTexture.isReadyOrNotBlocking()) {
  31850. return false;
  31851. }
  31852. defines.REFLECTION = true;
  31853. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  31854. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  31855. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  31856. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  31857. defines.INVERTCUBICMAP = true;
  31858. }
  31859. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  31860. switch (reflectionTexture.coordinatesMode) {
  31861. case BABYLON.Texture.CUBIC_MODE:
  31862. case BABYLON.Texture.INVCUBIC_MODE:
  31863. defines.REFLECTIONMAP_CUBIC = true;
  31864. break;
  31865. case BABYLON.Texture.EXPLICIT_MODE:
  31866. defines.REFLECTIONMAP_EXPLICIT = true;
  31867. break;
  31868. case BABYLON.Texture.PLANAR_MODE:
  31869. defines.REFLECTIONMAP_PLANAR = true;
  31870. break;
  31871. case BABYLON.Texture.PROJECTION_MODE:
  31872. defines.REFLECTIONMAP_PROJECTION = true;
  31873. break;
  31874. case BABYLON.Texture.SKYBOX_MODE:
  31875. defines.REFLECTIONMAP_SKYBOX = true;
  31876. break;
  31877. case BABYLON.Texture.SPHERICAL_MODE:
  31878. defines.REFLECTIONMAP_SPHERICAL = true;
  31879. break;
  31880. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  31881. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  31882. break;
  31883. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  31884. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  31885. break;
  31886. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  31887. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  31888. break;
  31889. }
  31890. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  31891. if (reflectionTexture.sphericalPolynomial) {
  31892. defines.USESPHERICALFROMREFLECTIONMAP = true;
  31893. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  31894. defines.USESPHERICALINFRAGMENT = true;
  31895. }
  31896. }
  31897. }
  31898. }
  31899. else {
  31900. defines.REFLECTION = false;
  31901. defines.REFLECTIONMAP_3D = false;
  31902. defines.REFLECTIONMAP_SPHERICAL = false;
  31903. defines.REFLECTIONMAP_PLANAR = false;
  31904. defines.REFLECTIONMAP_CUBIC = false;
  31905. defines.REFLECTIONMAP_PROJECTION = false;
  31906. defines.REFLECTIONMAP_SKYBOX = false;
  31907. defines.REFLECTIONMAP_EXPLICIT = false;
  31908. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  31909. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  31910. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  31911. defines.INVERTCUBICMAP = false;
  31912. defines.USESPHERICALFROMREFLECTIONMAP = false;
  31913. defines.USESPHERICALINFRAGMENT = false;
  31914. defines.REFLECTIONMAP_OPPOSITEZ = false;
  31915. defines.LODINREFLECTIONALPHA = false;
  31916. defines.GAMMAREFLECTION = false;
  31917. }
  31918. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  31919. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  31920. return false;
  31921. }
  31922. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  31923. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  31924. }
  31925. else {
  31926. defines.LIGHTMAP = false;
  31927. }
  31928. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  31929. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  31930. return false;
  31931. }
  31932. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  31933. }
  31934. else {
  31935. defines.EMISSIVE = false;
  31936. }
  31937. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  31938. if (this._metallicTexture) {
  31939. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  31940. return false;
  31941. }
  31942. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  31943. defines.METALLICWORKFLOW = true;
  31944. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  31945. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  31946. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  31947. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  31948. }
  31949. else if (this._reflectivityTexture) {
  31950. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  31951. return false;
  31952. }
  31953. defines.METALLICWORKFLOW = false;
  31954. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  31955. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  31956. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  31957. }
  31958. else {
  31959. defines.METALLICWORKFLOW = false;
  31960. defines.REFLECTIVITY = false;
  31961. }
  31962. if (this._microSurfaceTexture) {
  31963. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  31964. return false;
  31965. }
  31966. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  31967. }
  31968. else {
  31969. defines.MICROSURFACEMAP = false;
  31970. }
  31971. }
  31972. else {
  31973. defines.REFLECTIVITY = false;
  31974. defines.MICROSURFACEMAP = false;
  31975. }
  31976. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  31977. // Bump texure can not be none blocking.
  31978. if (!this._bumpTexture.isReady()) {
  31979. return false;
  31980. }
  31981. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  31982. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  31983. defines.PARALLAX = true;
  31984. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  31985. }
  31986. else {
  31987. defines.PARALLAX = false;
  31988. }
  31989. defines.USERIGHTHANDEDSYSTEM = scene.useRightHandedSystem;
  31990. }
  31991. else {
  31992. defines.BUMP = false;
  31993. }
  31994. var refractionTexture = this._getRefractionTexture();
  31995. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  31996. if (!refractionTexture.isReadyOrNotBlocking()) {
  31997. return false;
  31998. }
  31999. defines.REFRACTION = true;
  32000. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  32001. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  32002. defines.REFRACTIONMAP_OPPOSITEZ = reflectionTexture.invertZ;
  32003. defines.LODINREFRACTIONALPHA = reflectionTexture.lodLevelInAlpha;
  32004. if (this._linkRefractionWithTransparency) {
  32005. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  32006. }
  32007. }
  32008. else {
  32009. defines.REFRACTION = false;
  32010. }
  32011. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32012. // This is blocking.
  32013. if (!this._environmentBRDFTexture.isReady()) {
  32014. return false;
  32015. }
  32016. defines.ENVIRONMENTBRDF = true;
  32017. }
  32018. if (this._shouldUseAlphaFromAlbedoTexture()) {
  32019. defines.ALPHAFROMALBEDO = true;
  32020. }
  32021. }
  32022. if (this._useSpecularOverAlpha) {
  32023. defines.SPECULAROVERALPHA = true;
  32024. }
  32025. if (this._usePhysicalLightFalloff) {
  32026. defines.USEPHYSICALLIGHTFALLOFF = true;
  32027. }
  32028. if (this._useRadianceOverAlpha) {
  32029. defines.RADIANCEOVERALPHA = true;
  32030. }
  32031. if ((this._metallic !== undefined && this._metallic !== null) || (this._roughness !== undefined && this._roughness !== null)) {
  32032. defines.METALLICWORKFLOW = true;
  32033. }
  32034. if (!this.backFaceCulling && this._twoSidedLighting) {
  32035. defines.TWOSIDEDLIGHTING = true;
  32036. }
  32037. defines.ALPHATESTVALUE = this._alphaCutOff;
  32038. defines.PREMULTIPLYALPHA = this._preMultiplyAlpha;
  32039. defines.ALPHABLEND = this.needAlphaBlending();
  32040. defines.ALPHAFRESNEL = this._useAlphaFresnel;
  32041. }
  32042. if (defines._areImageProcessingDirty) {
  32043. if (!this._imageProcessingConfiguration.isReady()) {
  32044. return false;
  32045. }
  32046. this._imageProcessingConfiguration.prepareDefines(defines);
  32047. }
  32048. defines.FORCENORMALFORWARD = this._forceNormalForward;
  32049. // Misc.
  32050. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, defines);
  32051. // Values that need to be evaluated on every frame
  32052. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances, this._forceAlphaTest);
  32053. // Attribs
  32054. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true)) {
  32055. if (mesh) {
  32056. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32057. mesh.createNormals(true);
  32058. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  32059. }
  32060. }
  32061. }
  32062. // Get correct effect
  32063. if (defines.isDirty) {
  32064. defines.markAsProcessed();
  32065. scene.resetCachedMaterial();
  32066. // Fallbacks
  32067. var fallbacks = new BABYLON.EffectFallbacks();
  32068. if (defines.ENVIRONMENTBRDF) {
  32069. fallbacks.addFallback(0, "ENVIRONMENTBRDF");
  32070. }
  32071. if (defines.REFLECTION) {
  32072. fallbacks.addFallback(0, "REFLECTION");
  32073. }
  32074. if (defines.REFRACTION) {
  32075. fallbacks.addFallback(0, "REFRACTION");
  32076. }
  32077. if (defines.REFLECTIVITY) {
  32078. fallbacks.addFallback(0, "REFLECTIVITY");
  32079. }
  32080. if (defines.BUMP) {
  32081. fallbacks.addFallback(0, "BUMP");
  32082. }
  32083. if (defines.PARALLAX) {
  32084. fallbacks.addFallback(1, "PARALLAX");
  32085. }
  32086. if (defines.PARALLAXOCCLUSION) {
  32087. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  32088. }
  32089. if (defines.SPECULAROVERALPHA) {
  32090. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  32091. }
  32092. if (defines.FOG) {
  32093. fallbacks.addFallback(1, "FOG");
  32094. }
  32095. if (defines.POINTSIZE) {
  32096. fallbacks.addFallback(0, "POINTSIZE");
  32097. }
  32098. if (defines.LOGARITHMICDEPTH) {
  32099. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  32100. }
  32101. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  32102. if (defines.SPECULARTERM) {
  32103. fallbacks.addFallback(0, "SPECULARTERM");
  32104. }
  32105. if (defines.NUM_BONE_INFLUENCERS > 0) {
  32106. fallbacks.addCPUSkinningFallback(0, mesh);
  32107. }
  32108. //Attributes
  32109. var attribs = [BABYLON.VertexBuffer.PositionKind];
  32110. if (defines.NORMAL) {
  32111. attribs.push(BABYLON.VertexBuffer.NormalKind);
  32112. }
  32113. if (defines.TANGENT) {
  32114. attribs.push(BABYLON.VertexBuffer.TangentKind);
  32115. }
  32116. if (defines.UV1) {
  32117. attribs.push(BABYLON.VertexBuffer.UVKind);
  32118. }
  32119. if (defines.UV2) {
  32120. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  32121. }
  32122. if (defines.VERTEXCOLOR) {
  32123. attribs.push(BABYLON.VertexBuffer.ColorKind);
  32124. }
  32125. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  32126. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  32127. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  32128. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  32129. "vFogInfos", "vFogColor", "pointSize",
  32130. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vReflectivityInfos", "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  32131. "mBones",
  32132. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  32133. "vLightingIntensity",
  32134. "logarithmicDepthConstant",
  32135. "vSphericalX", "vSphericalY", "vSphericalZ",
  32136. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  32137. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  32138. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  32139. "vNormalReoderParams"
  32140. ];
  32141. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  32142. "bumpSampler", "lightmapSampler", "opacitySampler",
  32143. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  32144. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  32145. "microSurfaceSampler", "environmentBrdfSampler"];
  32146. var uniformBuffers = ["Material", "Scene"];
  32147. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  32148. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  32149. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  32150. uniformsNames: uniforms,
  32151. uniformBuffersNames: uniformBuffers,
  32152. samplers: samplers,
  32153. defines: defines,
  32154. maxSimultaneousLights: this._maxSimultaneousLights
  32155. });
  32156. var onCompiled = function (effect) {
  32157. if (this.onCompiled) {
  32158. this.onCompiled(effect);
  32159. }
  32160. this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  32161. }.bind(this);
  32162. var join = defines.toString();
  32163. subMesh.setEffect(scene.getEngine().createEffect("pbr", {
  32164. attributes: attribs,
  32165. uniformsNames: uniforms,
  32166. uniformBuffersNames: uniformBuffers,
  32167. samplers: samplers,
  32168. defines: join,
  32169. fallbacks: fallbacks,
  32170. onCompiled: onCompiled,
  32171. onError: this.onError,
  32172. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  32173. }, engine), defines);
  32174. this.buildUniformLayout();
  32175. }
  32176. if (!subMesh.effect.isReady()) {
  32177. return false;
  32178. }
  32179. defines._renderId = scene.getRenderId();
  32180. this._wasPreviouslyReady = true;
  32181. return true;
  32182. };
  32183. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  32184. // Order is important !
  32185. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  32186. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  32187. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  32188. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  32189. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  32190. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  32191. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  32192. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  32193. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  32194. this._uniformBuffer.addUniform("vBumpInfos", 3);
  32195. this._uniformBuffer.addUniform("albedoMatrix", 16);
  32196. this._uniformBuffer.addUniform("ambientMatrix", 16);
  32197. this._uniformBuffer.addUniform("opacityMatrix", 16);
  32198. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  32199. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  32200. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  32201. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  32202. this._uniformBuffer.addUniform("bumpMatrix", 16);
  32203. this._uniformBuffer.addUniform("vNormalReoderParams", 4);
  32204. this._uniformBuffer.addUniform("refractionMatrix", 16);
  32205. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  32206. this._uniformBuffer.addUniform("vReflectionColor", 3);
  32207. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  32208. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  32209. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  32210. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  32211. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  32212. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  32213. this._uniformBuffer.addUniform("pointSize", 1);
  32214. this._uniformBuffer.create();
  32215. };
  32216. PBRBaseMaterial.prototype.unbind = function () {
  32217. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  32218. this._uniformBuffer.setTexture("reflectionSampler", null);
  32219. }
  32220. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  32221. this._uniformBuffer.setTexture("refractionSampler", null);
  32222. }
  32223. _super.prototype.unbind.call(this);
  32224. };
  32225. PBRBaseMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  32226. this._activeEffect.setMatrix("world", world);
  32227. };
  32228. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  32229. var scene = this.getScene();
  32230. var defines = subMesh._materialDefines;
  32231. if (!defines) {
  32232. return;
  32233. }
  32234. var effect = subMesh.effect;
  32235. this._activeEffect = effect;
  32236. // Matrices
  32237. this.bindOnlyWorldMatrix(world);
  32238. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  32239. // Bones
  32240. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  32241. if (mustRebind) {
  32242. this._uniformBuffer.bindToEffect(effect, "Material");
  32243. this.bindViewProjection(effect);
  32244. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  32245. // Texture uniforms
  32246. if (scene.texturesEnabled) {
  32247. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32248. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  32249. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  32250. }
  32251. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32252. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  32253. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  32254. }
  32255. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32256. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  32257. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  32258. }
  32259. var reflectionTexture = this._getReflectionTexture();
  32260. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32261. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  32262. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  32263. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  32264. var polynomials = reflectionTexture.sphericalPolynomial;
  32265. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  32266. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  32267. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  32268. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  32269. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  32270. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  32271. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  32272. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  32273. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  32274. }
  32275. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  32276. }
  32277. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32278. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  32279. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  32280. }
  32281. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32282. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  32283. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  32284. }
  32285. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32286. if (this._metallicTexture) {
  32287. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  32288. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  32289. }
  32290. else if (this._reflectivityTexture) {
  32291. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  32292. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  32293. }
  32294. if (this._microSurfaceTexture) {
  32295. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  32296. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  32297. }
  32298. }
  32299. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32300. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  32301. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  32302. if (scene._mirroredCameraPosition) {
  32303. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 0 : 1.0, this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 0 : 1.0, this._invertNormalMapY ? 1.0 : -1.0);
  32304. }
  32305. else {
  32306. this._uniformBuffer.updateFloat4("vNormalReoderParams", this._invertNormalMapX ? 1.0 : 0, this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? 1.0 : 0, this._invertNormalMapY ? -1.0 : 1.0);
  32307. }
  32308. }
  32309. var refractionTexture = this._getRefractionTexture();
  32310. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32311. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  32312. var depth = 1.0;
  32313. if (!refractionTexture.isCube) {
  32314. if (refractionTexture.depth) {
  32315. depth = refractionTexture.depth;
  32316. }
  32317. }
  32318. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  32319. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  32320. }
  32321. }
  32322. // Point size
  32323. if (this.pointsCloud) {
  32324. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  32325. }
  32326. // Colors
  32327. if (defines.METALLICWORKFLOW) {
  32328. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  32329. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  32330. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  32331. }
  32332. else {
  32333. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  32334. }
  32335. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  32336. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  32337. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  32338. // Misc
  32339. this._lightingInfos.x = this._directIntensity;
  32340. this._lightingInfos.y = this._emissiveIntensity;
  32341. this._lightingInfos.z = this._environmentIntensity;
  32342. this._lightingInfos.w = this._specularIntensity;
  32343. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  32344. }
  32345. // Textures
  32346. if (scene.texturesEnabled) {
  32347. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  32348. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  32349. }
  32350. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  32351. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  32352. }
  32353. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  32354. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  32355. }
  32356. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  32357. if (defines.LODBASEDMICROSFURACE) {
  32358. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  32359. }
  32360. else {
  32361. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  32362. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  32363. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  32364. }
  32365. }
  32366. if (defines.ENVIRONMENTBRDF) {
  32367. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  32368. }
  32369. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  32370. if (defines.LODBASEDMICROSFURACE) {
  32371. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  32372. }
  32373. else {
  32374. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  32375. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  32376. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  32377. }
  32378. }
  32379. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  32380. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  32381. }
  32382. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  32383. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  32384. }
  32385. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  32386. if (this._metallicTexture) {
  32387. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  32388. }
  32389. else if (this._reflectivityTexture) {
  32390. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  32391. }
  32392. if (this._microSurfaceTexture) {
  32393. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  32394. }
  32395. }
  32396. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  32397. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  32398. }
  32399. }
  32400. // Clip plane
  32401. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  32402. // Colors
  32403. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  32404. var eyePosition = scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition;
  32405. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, scene._mirroredCameraPosition ? -1 : 1);
  32406. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  32407. }
  32408. if (mustRebind || !this.isFrozen) {
  32409. // Lights
  32410. if (scene.lightsEnabled && !this._disableLighting) {
  32411. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  32412. }
  32413. // View
  32414. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  32415. this.bindView(effect);
  32416. }
  32417. // Fog
  32418. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  32419. // Morph targets
  32420. if (defines.NUM_MORPH_INFLUENCERS) {
  32421. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  32422. }
  32423. // image processing
  32424. this._imageProcessingConfiguration.bind(this._activeEffect);
  32425. // Log. depth
  32426. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  32427. }
  32428. this._uniformBuffer.update();
  32429. this._afterBind(mesh);
  32430. scene = null;
  32431. };
  32432. PBRBaseMaterial.prototype.getAnimatables = function () {
  32433. var results = [];
  32434. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  32435. results.push(this._albedoTexture);
  32436. }
  32437. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  32438. results.push(this._ambientTexture);
  32439. }
  32440. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  32441. results.push(this._opacityTexture);
  32442. }
  32443. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  32444. results.push(this._reflectionTexture);
  32445. }
  32446. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  32447. results.push(this._emissiveTexture);
  32448. }
  32449. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  32450. results.push(this._metallicTexture);
  32451. }
  32452. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  32453. results.push(this._reflectivityTexture);
  32454. }
  32455. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  32456. results.push(this._bumpTexture);
  32457. }
  32458. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  32459. results.push(this._lightmapTexture);
  32460. }
  32461. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  32462. results.push(this._refractionTexture);
  32463. }
  32464. return results;
  32465. };
  32466. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  32467. if (this._reflectionTexture) {
  32468. return this._reflectionTexture;
  32469. }
  32470. return this.getScene().environmentTexture;
  32471. };
  32472. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  32473. if (this._refractionTexture) {
  32474. return this._refractionTexture;
  32475. }
  32476. if (this._linkRefractionWithTransparency) {
  32477. return this.getScene().environmentTexture;
  32478. }
  32479. return null;
  32480. };
  32481. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  32482. if (forceDisposeTextures) {
  32483. if (this._albedoTexture) {
  32484. this._albedoTexture.dispose();
  32485. }
  32486. if (this._ambientTexture) {
  32487. this._ambientTexture.dispose();
  32488. }
  32489. if (this._opacityTexture) {
  32490. this._opacityTexture.dispose();
  32491. }
  32492. if (this._reflectionTexture) {
  32493. this._reflectionTexture.dispose();
  32494. }
  32495. if (this._environmentBRDFTexture) {
  32496. this._environmentBRDFTexture.dispose();
  32497. }
  32498. if (this._emissiveTexture) {
  32499. this._emissiveTexture.dispose();
  32500. }
  32501. if (this._metallicTexture) {
  32502. this._metallicTexture.dispose();
  32503. }
  32504. if (this._reflectivityTexture) {
  32505. this._reflectivityTexture.dispose();
  32506. }
  32507. if (this._bumpTexture) {
  32508. this._bumpTexture.dispose();
  32509. }
  32510. if (this._lightmapTexture) {
  32511. this._lightmapTexture.dispose();
  32512. }
  32513. if (this._refractionTexture) {
  32514. this._refractionTexture.dispose();
  32515. }
  32516. }
  32517. this._renderTargets.dispose();
  32518. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  32519. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  32520. }
  32521. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  32522. };
  32523. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  32524. __decorate([
  32525. BABYLON.serializeAsImageProcessingConfiguration()
  32526. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  32527. __decorate([
  32528. BABYLON.serialize()
  32529. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  32530. return PBRBaseMaterial;
  32531. }(BABYLON.PushMaterial));
  32532. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  32533. })(BABYLON || (BABYLON = {}));
  32534. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  32535. var BABYLON;
  32536. (function (BABYLON) {
  32537. var Internals;
  32538. (function (Internals) {
  32539. /**
  32540. * The Physically based simple base material of BJS.
  32541. *
  32542. * This enables better naming and convention enforcements on top of the pbrMaterial.
  32543. * It is used as the base class for both the specGloss and metalRough conventions.
  32544. */
  32545. var PBRBaseSimpleMaterial = (function (_super) {
  32546. __extends(PBRBaseSimpleMaterial, _super);
  32547. /**
  32548. * Instantiates a new PBRMaterial instance.
  32549. *
  32550. * @param name The material name
  32551. * @param scene The scene the material will be use in.
  32552. */
  32553. function PBRBaseSimpleMaterial(name, scene) {
  32554. var _this = _super.call(this, name, scene) || this;
  32555. /**
  32556. * Number of Simultaneous lights allowed on the material.
  32557. */
  32558. _this.maxSimultaneousLights = 4;
  32559. /**
  32560. * If sets to true, disables all the lights affecting the material.
  32561. */
  32562. _this.disableLighting = false;
  32563. /**
  32564. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32565. */
  32566. _this.invertNormalMapX = false;
  32567. /**
  32568. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32569. */
  32570. _this.invertNormalMapY = false;
  32571. /**
  32572. * Emissivie color used to self-illuminate the model.
  32573. */
  32574. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32575. /**
  32576. * Occlusion Channel Strenght.
  32577. */
  32578. _this.occlusionStrength = 1.0;
  32579. _this._transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32580. _this._useAmbientInGrayScale = true;
  32581. return _this;
  32582. }
  32583. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "transparencyMode", {
  32584. /**
  32585. * Gets the current transparency mode.
  32586. */
  32587. get: function () {
  32588. return this._transparencyMode;
  32589. },
  32590. /**
  32591. * Sets the transparency mode of the material.
  32592. */
  32593. set: function (value) {
  32594. if (this._transparencyMode === value) {
  32595. return;
  32596. }
  32597. this._transparencyMode = value;
  32598. if (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND) {
  32599. this._forceAlphaTest = true;
  32600. }
  32601. else {
  32602. this._forceAlphaTest = false;
  32603. }
  32604. this._markAllSubMeshesAsTexturesDirty();
  32605. },
  32606. enumerable: true,
  32607. configurable: true
  32608. });
  32609. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  32610. /**
  32611. * Gets the current double sided mode.
  32612. */
  32613. get: function () {
  32614. return this._twoSidedLighting;
  32615. },
  32616. /**
  32617. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32618. */
  32619. set: function (value) {
  32620. if (this._twoSidedLighting === value) {
  32621. return;
  32622. }
  32623. this._twoSidedLighting = value;
  32624. this.backFaceCulling = !value;
  32625. this._markAllSubMeshesAsTexturesDirty();
  32626. },
  32627. enumerable: true,
  32628. configurable: true
  32629. });
  32630. /**
  32631. * Specifies wether or not the alpha value of the albedo texture should be used.
  32632. */
  32633. PBRBaseSimpleMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  32634. return this._albedoTexture && this._albedoTexture.hasAlpha && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  32635. };
  32636. /**
  32637. * Specifies wether or not the meshes using this material should be rendered in alpha blend mode.
  32638. */
  32639. PBRBaseSimpleMaterial.prototype.needAlphaBlending = function () {
  32640. if (this._linkRefractionWithTransparency) {
  32641. return false;
  32642. }
  32643. return (this.alpha < 1.0) ||
  32644. (this._shouldUseAlphaFromAlbedoTexture() &&
  32645. (this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND ||
  32646. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND));
  32647. };
  32648. /**
  32649. * Specifies wether or not the meshes using this material should be rendered in alpha test mode.
  32650. */
  32651. PBRBaseSimpleMaterial.prototype.needAlphaTesting = function () {
  32652. if (this._linkRefractionWithTransparency) {
  32653. return false;
  32654. }
  32655. return this._shouldUseAlphaFromAlbedoTexture() &&
  32656. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  32657. };
  32658. /**
  32659. * Return the active textures of the material.
  32660. */
  32661. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  32662. var activeTextures = _super.prototype.getActiveTextures.call(this);
  32663. if (this.environmentTexture) {
  32664. activeTextures.push(this.environmentTexture);
  32665. }
  32666. if (this.normalTexture) {
  32667. activeTextures.push(this.normalTexture);
  32668. }
  32669. if (this.emissiveTexture) {
  32670. activeTextures.push(this.emissiveTexture);
  32671. }
  32672. if (this.occlusionTexture) {
  32673. activeTextures.push(this.occlusionTexture);
  32674. }
  32675. return activeTextures;
  32676. };
  32677. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  32678. return "PBRBaseSimpleMaterial";
  32679. };
  32680. __decorate([
  32681. BABYLON.serialize(),
  32682. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32683. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  32684. __decorate([
  32685. BABYLON.serialize(),
  32686. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  32687. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  32688. __decorate([
  32689. BABYLON.serializeAsTexture(),
  32690. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  32691. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  32692. __decorate([
  32693. BABYLON.serialize(),
  32694. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32695. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  32696. __decorate([
  32697. BABYLON.serialize(),
  32698. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32699. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  32700. __decorate([
  32701. BABYLON.serializeAsTexture(),
  32702. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  32703. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  32704. __decorate([
  32705. BABYLON.serializeAsColor3("emissive"),
  32706. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32707. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  32708. __decorate([
  32709. BABYLON.serializeAsTexture(),
  32710. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  32711. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  32712. __decorate([
  32713. BABYLON.serialize(),
  32714. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  32715. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  32716. __decorate([
  32717. BABYLON.serializeAsTexture(),
  32718. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  32719. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  32720. __decorate([
  32721. BABYLON.serialize(),
  32722. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  32723. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  32724. __decorate([
  32725. BABYLON.serialize()
  32726. ], PBRBaseSimpleMaterial.prototype, "transparencyMode", null);
  32727. __decorate([
  32728. BABYLON.serialize()
  32729. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  32730. return PBRBaseSimpleMaterial;
  32731. }(BABYLON.PBRBaseMaterial));
  32732. Internals.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  32733. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  32734. })(BABYLON || (BABYLON = {}));
  32735. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  32736. var BABYLON;
  32737. (function (BABYLON) {
  32738. /**
  32739. * The Physically based material of BJS.
  32740. *
  32741. * This offers the main features of a standard PBR material.
  32742. * For more information, please refer to the documentation :
  32743. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  32744. */
  32745. var PBRMaterial = (function (_super) {
  32746. __extends(PBRMaterial, _super);
  32747. /**
  32748. * Instantiates a new PBRMaterial instance.
  32749. *
  32750. * @param name The material name
  32751. * @param scene The scene the material will be use in.
  32752. */
  32753. function PBRMaterial(name, scene) {
  32754. var _this = _super.call(this, name, scene) || this;
  32755. /**
  32756. * Intensity of the direct lights e.g. the four lights available in your scene.
  32757. * This impacts both the direct diffuse and specular highlights.
  32758. */
  32759. _this.directIntensity = 1.0;
  32760. /**
  32761. * Intensity of the emissive part of the material.
  32762. * This helps controlling the emissive effect without modifying the emissive color.
  32763. */
  32764. _this.emissiveIntensity = 1.0;
  32765. /**
  32766. * Intensity of the environment e.g. how much the environment will light the object
  32767. * either through harmonics for rough material or through the refelction for shiny ones.
  32768. */
  32769. _this.environmentIntensity = 1.0;
  32770. /**
  32771. * This is a special control allowing the reduction of the specular highlights coming from the
  32772. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  32773. */
  32774. _this.specularIntensity = 1.0;
  32775. /**
  32776. * Debug Control allowing disabling the bump map on this material.
  32777. */
  32778. _this.disableBumpMap = false;
  32779. /**
  32780. * AKA Occlusion Texture Intensity in other nomenclature.
  32781. */
  32782. _this.ambientTextureStrength = 1.0;
  32783. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  32784. /**
  32785. * AKA Diffuse Color in other nomenclature.
  32786. */
  32787. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  32788. /**
  32789. * AKA Specular Color in other nomenclature.
  32790. */
  32791. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  32792. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  32793. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  32794. /**
  32795. * AKA Glossiness in other nomenclature.
  32796. */
  32797. _this.microSurface = 1.0;
  32798. /**
  32799. * source material index of refraction (IOR)' / 'destination material IOR.
  32800. */
  32801. _this.indexOfRefraction = 0.66;
  32802. /**
  32803. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  32804. */
  32805. _this.invertRefractionY = false;
  32806. /**
  32807. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  32808. * Materials half opaque for instance using refraction could benefit from this control.
  32809. */
  32810. _this.linkRefractionWithTransparency = false;
  32811. _this.useLightmapAsShadowmap = false;
  32812. /**
  32813. * Specifies that the alpha is coming form the albedo channel alpha channel.
  32814. */
  32815. _this.useAlphaFromAlbedoTexture = false;
  32816. /**
  32817. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  32818. */
  32819. _this.forceAlphaTest = false;
  32820. /**
  32821. * Defines the alpha limits in alpha test mode.
  32822. */
  32823. _this.alphaCutOff = 0.4;
  32824. /**
  32825. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  32826. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  32827. */
  32828. _this.useSpecularOverAlpha = true;
  32829. /**
  32830. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  32831. */
  32832. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  32833. /**
  32834. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  32835. */
  32836. _this.useRoughnessFromMetallicTextureAlpha = true;
  32837. /**
  32838. * Specifies if the metallic texture contains the roughness information in its green channel.
  32839. */
  32840. _this.useRoughnessFromMetallicTextureGreen = false;
  32841. /**
  32842. * Specifies if the metallic texture contains the metallness information in its blue channel.
  32843. */
  32844. _this.useMetallnessFromMetallicTextureBlue = false;
  32845. /**
  32846. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  32847. */
  32848. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  32849. /**
  32850. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  32851. */
  32852. _this.useAmbientInGrayScale = false;
  32853. /**
  32854. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  32855. * The material will try to infer what glossiness each pixel should be.
  32856. */
  32857. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  32858. /**
  32859. * BJS is using an harcoded light falloff based on a manually sets up range.
  32860. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  32861. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  32862. */
  32863. _this.usePhysicalLightFalloff = true;
  32864. /**
  32865. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  32866. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  32867. */
  32868. _this.useRadianceOverAlpha = true;
  32869. /**
  32870. * Allows using the bump map in parallax mode.
  32871. */
  32872. _this.useParallax = false;
  32873. /**
  32874. * Allows using the bump map in parallax occlusion mode.
  32875. */
  32876. _this.useParallaxOcclusion = false;
  32877. /**
  32878. * Controls the scale bias of the parallax mode.
  32879. */
  32880. _this.parallaxScaleBias = 0.05;
  32881. /**
  32882. * If sets to true, disables all the lights affecting the material.
  32883. */
  32884. _this.disableLighting = false;
  32885. /**
  32886. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  32887. */
  32888. _this.forceIrradianceInFragment = false;
  32889. /**
  32890. * Number of Simultaneous lights allowed on the material.
  32891. */
  32892. _this.maxSimultaneousLights = 4;
  32893. /**
  32894. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  32895. */
  32896. _this.invertNormalMapX = false;
  32897. /**
  32898. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  32899. */
  32900. _this.invertNormalMapY = false;
  32901. /**
  32902. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  32903. */
  32904. _this.twoSidedLighting = false;
  32905. /**
  32906. * Specifies that the alpha is premultiplied before output (this enables alpha premultiplied blending).
  32907. * in your scene composition.
  32908. */
  32909. _this.preMultiplyAlpha = false;
  32910. /**
  32911. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32912. * And/Or occlude the blended part.
  32913. */
  32914. _this.useAlphaFresnel = false;
  32915. /**
  32916. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  32917. * And/Or occlude the blended part.
  32918. */
  32919. _this.environmentBRDFTexture = null;
  32920. /**
  32921. * Force normal to face away from face.
  32922. * (Temporary internal fix to remove before 3.1)
  32923. */
  32924. _this.forceNormalForward = false;
  32925. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  32926. return _this;
  32927. }
  32928. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  32929. /**
  32930. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  32931. */
  32932. get: function () {
  32933. return this._PBRMATERIAL_OPAQUE;
  32934. },
  32935. enumerable: true,
  32936. configurable: true
  32937. });
  32938. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  32939. /**
  32940. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  32941. */
  32942. get: function () {
  32943. return this._PBRMATERIAL_ALPHATEST;
  32944. },
  32945. enumerable: true,
  32946. configurable: true
  32947. });
  32948. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  32949. /**
  32950. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32951. */
  32952. get: function () {
  32953. return this._PBRMATERIAL_ALPHABLEND;
  32954. },
  32955. enumerable: true,
  32956. configurable: true
  32957. });
  32958. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  32959. /**
  32960. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  32961. * They are also discarded below the alpha cutoff threshold to improve performances.
  32962. */
  32963. get: function () {
  32964. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  32965. },
  32966. enumerable: true,
  32967. configurable: true
  32968. });
  32969. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  32970. /**
  32971. * Gets the image processing configuration used either in this material.
  32972. */
  32973. get: function () {
  32974. return this._imageProcessingConfiguration;
  32975. },
  32976. /**
  32977. * Sets the Default image processing configuration used either in the this material.
  32978. *
  32979. * If sets to null, the scene one is in use.
  32980. */
  32981. set: function (value) {
  32982. this._attachImageProcessingConfiguration(value);
  32983. // Ensure the effect will be rebuilt.
  32984. this._markAllSubMeshesAsTexturesDirty();
  32985. },
  32986. enumerable: true,
  32987. configurable: true
  32988. });
  32989. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  32990. /**
  32991. * Gets wether the color curves effect is enabled.
  32992. */
  32993. get: function () {
  32994. return this.imageProcessingConfiguration.colorCurvesEnabled;
  32995. },
  32996. /**
  32997. * Sets wether the color curves effect is enabled.
  32998. */
  32999. set: function (value) {
  33000. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  33001. },
  33002. enumerable: true,
  33003. configurable: true
  33004. });
  33005. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  33006. /**
  33007. * Gets wether the color grading effect is enabled.
  33008. */
  33009. get: function () {
  33010. return this.imageProcessingConfiguration.colorGradingEnabled;
  33011. },
  33012. /**
  33013. * Gets wether the color grading effect is enabled.
  33014. */
  33015. set: function (value) {
  33016. this.imageProcessingConfiguration.colorGradingEnabled = value;
  33017. },
  33018. enumerable: true,
  33019. configurable: true
  33020. });
  33021. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  33022. /**
  33023. * Gets wether tonemapping is enabled or not.
  33024. */
  33025. get: function () {
  33026. return this._imageProcessingConfiguration.toneMappingEnabled;
  33027. },
  33028. /**
  33029. * Sets wether tonemapping is enabled or not
  33030. */
  33031. set: function (value) {
  33032. this._imageProcessingConfiguration.toneMappingEnabled = value;
  33033. },
  33034. enumerable: true,
  33035. configurable: true
  33036. });
  33037. ;
  33038. ;
  33039. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  33040. /**
  33041. * The camera exposure used on this material.
  33042. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33043. * This corresponds to a photographic exposure.
  33044. */
  33045. get: function () {
  33046. return this._imageProcessingConfiguration.exposure;
  33047. },
  33048. /**
  33049. * The camera exposure used on this material.
  33050. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  33051. * This corresponds to a photographic exposure.
  33052. */
  33053. set: function (value) {
  33054. this._imageProcessingConfiguration.exposure = value;
  33055. },
  33056. enumerable: true,
  33057. configurable: true
  33058. });
  33059. ;
  33060. ;
  33061. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  33062. /**
  33063. * Gets The camera contrast used on this material.
  33064. */
  33065. get: function () {
  33066. return this._imageProcessingConfiguration.contrast;
  33067. },
  33068. /**
  33069. * Sets The camera contrast used on this material.
  33070. */
  33071. set: function (value) {
  33072. this._imageProcessingConfiguration.contrast = value;
  33073. },
  33074. enumerable: true,
  33075. configurable: true
  33076. });
  33077. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  33078. /**
  33079. * Gets the Color Grading 2D Lookup Texture.
  33080. */
  33081. get: function () {
  33082. return this._imageProcessingConfiguration.colorGradingTexture;
  33083. },
  33084. /**
  33085. * Sets the Color Grading 2D Lookup Texture.
  33086. */
  33087. set: function (value) {
  33088. this._imageProcessingConfiguration.colorGradingTexture = value;
  33089. },
  33090. enumerable: true,
  33091. configurable: true
  33092. });
  33093. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  33094. /**
  33095. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33096. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33097. * 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;
  33098. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33099. */
  33100. get: function () {
  33101. return this._imageProcessingConfiguration.colorCurves;
  33102. },
  33103. /**
  33104. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  33105. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  33106. * 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;
  33107. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  33108. */
  33109. set: function (value) {
  33110. this._imageProcessingConfiguration.colorCurves = value;
  33111. },
  33112. enumerable: true,
  33113. configurable: true
  33114. });
  33115. PBRMaterial.prototype.getClassName = function () {
  33116. return "PBRMaterial";
  33117. };
  33118. PBRMaterial.prototype.getActiveTextures = function () {
  33119. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33120. if (this._albedoTexture) {
  33121. activeTextures.push(this._albedoTexture);
  33122. }
  33123. if (this._ambientTexture) {
  33124. activeTextures.push(this._ambientTexture);
  33125. }
  33126. if (this._opacityTexture) {
  33127. activeTextures.push(this._opacityTexture);
  33128. }
  33129. if (this._reflectionTexture) {
  33130. activeTextures.push(this._reflectionTexture);
  33131. }
  33132. if (this._emissiveTexture) {
  33133. activeTextures.push(this._emissiveTexture);
  33134. }
  33135. if (this._reflectivityTexture) {
  33136. activeTextures.push(this._reflectivityTexture);
  33137. }
  33138. if (this._metallicTexture) {
  33139. activeTextures.push(this._metallicTexture);
  33140. }
  33141. if (this._microSurfaceTexture) {
  33142. activeTextures.push(this._microSurfaceTexture);
  33143. }
  33144. if (this._bumpTexture) {
  33145. activeTextures.push(this._bumpTexture);
  33146. }
  33147. if (this._lightmapTexture) {
  33148. activeTextures.push(this._lightmapTexture);
  33149. }
  33150. if (this._refractionTexture) {
  33151. activeTextures.push(this._refractionTexture);
  33152. }
  33153. return activeTextures;
  33154. };
  33155. PBRMaterial.prototype.hasTexture = function (texture) {
  33156. if (_super.prototype.hasTexture.call(this, texture)) {
  33157. return true;
  33158. }
  33159. if (this._albedoTexture === texture) {
  33160. return true;
  33161. }
  33162. if (this._ambientTexture === texture) {
  33163. return true;
  33164. }
  33165. if (this._opacityTexture === texture) {
  33166. return true;
  33167. }
  33168. if (this._reflectionTexture === texture) {
  33169. return true;
  33170. }
  33171. if (this._reflectivityTexture === texture) {
  33172. return true;
  33173. }
  33174. if (this._metallicTexture === texture) {
  33175. return true;
  33176. }
  33177. if (this._microSurfaceTexture === texture) {
  33178. return true;
  33179. }
  33180. if (this._bumpTexture === texture) {
  33181. return true;
  33182. }
  33183. if (this._lightmapTexture === texture) {
  33184. return true;
  33185. }
  33186. if (this._refractionTexture === texture) {
  33187. return true;
  33188. }
  33189. return false;
  33190. };
  33191. PBRMaterial.prototype.clone = function (name) {
  33192. var _this = this;
  33193. return BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  33194. };
  33195. PBRMaterial.prototype.serialize = function () {
  33196. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33197. serializationObject.customType = "BABYLON.PBRMaterial";
  33198. return serializationObject;
  33199. };
  33200. // Statics
  33201. PBRMaterial.Parse = function (source, scene, rootUrl) {
  33202. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  33203. };
  33204. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  33205. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  33206. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  33207. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  33208. __decorate([
  33209. BABYLON.serialize(),
  33210. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33211. ], PBRMaterial.prototype, "directIntensity", void 0);
  33212. __decorate([
  33213. BABYLON.serialize(),
  33214. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33215. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  33216. __decorate([
  33217. BABYLON.serialize(),
  33218. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33219. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  33220. __decorate([
  33221. BABYLON.serialize(),
  33222. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33223. ], PBRMaterial.prototype, "specularIntensity", void 0);
  33224. __decorate([
  33225. BABYLON.serialize(),
  33226. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33227. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  33228. __decorate([
  33229. BABYLON.serializeAsTexture(),
  33230. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33231. ], PBRMaterial.prototype, "albedoTexture", void 0);
  33232. __decorate([
  33233. BABYLON.serializeAsTexture(),
  33234. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33235. ], PBRMaterial.prototype, "ambientTexture", void 0);
  33236. __decorate([
  33237. BABYLON.serialize(),
  33238. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33239. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  33240. __decorate([
  33241. BABYLON.serializeAsTexture(),
  33242. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33243. ], PBRMaterial.prototype, "opacityTexture", void 0);
  33244. __decorate([
  33245. BABYLON.serializeAsTexture(),
  33246. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33247. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  33248. __decorate([
  33249. BABYLON.serializeAsTexture(),
  33250. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33251. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  33252. __decorate([
  33253. BABYLON.serializeAsTexture(),
  33254. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33255. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  33256. __decorate([
  33257. BABYLON.serializeAsTexture(),
  33258. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33259. ], PBRMaterial.prototype, "metallicTexture", void 0);
  33260. __decorate([
  33261. BABYLON.serialize(),
  33262. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33263. ], PBRMaterial.prototype, "metallic", void 0);
  33264. __decorate([
  33265. BABYLON.serialize(),
  33266. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33267. ], PBRMaterial.prototype, "roughness", void 0);
  33268. __decorate([
  33269. BABYLON.serializeAsTexture(),
  33270. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33271. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  33272. __decorate([
  33273. BABYLON.serializeAsTexture(),
  33274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33275. ], PBRMaterial.prototype, "bumpTexture", void 0);
  33276. __decorate([
  33277. BABYLON.serializeAsTexture(),
  33278. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  33279. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  33280. __decorate([
  33281. BABYLON.serializeAsTexture(),
  33282. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33283. ], PBRMaterial.prototype, "refractionTexture", void 0);
  33284. __decorate([
  33285. BABYLON.serializeAsColor3("ambient"),
  33286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33287. ], PBRMaterial.prototype, "ambientColor", void 0);
  33288. __decorate([
  33289. BABYLON.serializeAsColor3("albedo"),
  33290. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33291. ], PBRMaterial.prototype, "albedoColor", void 0);
  33292. __decorate([
  33293. BABYLON.serializeAsColor3("reflectivity"),
  33294. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33295. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  33296. __decorate([
  33297. BABYLON.serializeAsColor3("reflection"),
  33298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33299. ], PBRMaterial.prototype, "reflectionColor", void 0);
  33300. __decorate([
  33301. BABYLON.serializeAsColor3("emissive"),
  33302. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33303. ], PBRMaterial.prototype, "emissiveColor", void 0);
  33304. __decorate([
  33305. BABYLON.serialize(),
  33306. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33307. ], PBRMaterial.prototype, "microSurface", void 0);
  33308. __decorate([
  33309. BABYLON.serialize(),
  33310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33311. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  33312. __decorate([
  33313. BABYLON.serialize(),
  33314. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33315. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  33316. __decorate([
  33317. BABYLON.serialize(),
  33318. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33319. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  33320. __decorate([
  33321. BABYLON.serialize(),
  33322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33323. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  33324. __decorate([
  33325. BABYLON.serialize(),
  33326. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33327. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  33328. __decorate([
  33329. BABYLON.serialize(),
  33330. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33331. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  33332. __decorate([
  33333. BABYLON.serialize(),
  33334. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33335. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  33336. __decorate([
  33337. BABYLON.serialize(),
  33338. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33339. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  33340. __decorate([
  33341. BABYLON.serialize(),
  33342. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33343. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  33344. __decorate([
  33345. BABYLON.serialize(),
  33346. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33347. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  33348. __decorate([
  33349. BABYLON.serialize(),
  33350. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33351. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  33352. __decorate([
  33353. BABYLON.serialize(),
  33354. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33355. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  33356. __decorate([
  33357. BABYLON.serialize(),
  33358. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33359. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  33360. __decorate([
  33361. BABYLON.serialize(),
  33362. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33363. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  33364. __decorate([
  33365. BABYLON.serialize(),
  33366. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33367. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  33368. __decorate([
  33369. BABYLON.serialize(),
  33370. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33371. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  33372. __decorate([
  33373. BABYLON.serialize(),
  33374. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33375. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  33376. __decorate([
  33377. BABYLON.serialize(),
  33378. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33379. ], PBRMaterial.prototype, "useParallax", void 0);
  33380. __decorate([
  33381. BABYLON.serialize(),
  33382. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33383. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  33384. __decorate([
  33385. BABYLON.serialize(),
  33386. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33387. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  33388. __decorate([
  33389. BABYLON.serialize(),
  33390. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33391. ], PBRMaterial.prototype, "disableLighting", void 0);
  33392. __decorate([
  33393. BABYLON.serialize(),
  33394. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33395. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  33396. __decorate([
  33397. BABYLON.serialize(),
  33398. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  33399. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  33400. __decorate([
  33401. BABYLON.serialize(),
  33402. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33403. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  33404. __decorate([
  33405. BABYLON.serialize(),
  33406. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33407. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  33408. __decorate([
  33409. BABYLON.serialize(),
  33410. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33411. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  33412. __decorate([
  33413. BABYLON.serialize(),
  33414. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33415. ], PBRMaterial.prototype, "preMultiplyAlpha", void 0);
  33416. __decorate([
  33417. BABYLON.serialize(),
  33418. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33419. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  33420. __decorate([
  33421. BABYLON.serializeAsTexture(),
  33422. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33423. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  33424. __decorate([
  33425. BABYLON.serialize(),
  33426. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33427. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  33428. return PBRMaterial;
  33429. }(BABYLON.PBRBaseMaterial));
  33430. BABYLON.PBRMaterial = PBRMaterial;
  33431. })(BABYLON || (BABYLON = {}));
  33432. //# sourceMappingURL=babylon.pbrMaterial.js.map
  33433. var BABYLON;
  33434. (function (BABYLON) {
  33435. /**
  33436. * The PBR material of BJS following the metal roughness convention.
  33437. *
  33438. * This fits to the PBR convention in the GLTF definition:
  33439. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  33440. */
  33441. var PBRMetallicRoughnessMaterial = (function (_super) {
  33442. __extends(PBRMetallicRoughnessMaterial, _super);
  33443. /**
  33444. * Instantiates a new PBRMetalRoughnessMaterial instance.
  33445. *
  33446. * @param name The material name
  33447. * @param scene The scene the material will be use in.
  33448. */
  33449. function PBRMetallicRoughnessMaterial(name, scene) {
  33450. var _this = _super.call(this, name, scene) || this;
  33451. _this._useRoughnessFromMetallicTextureAlpha = false;
  33452. _this._useRoughnessFromMetallicTextureGreen = true;
  33453. _this._useMetallnessFromMetallicTextureBlue = true;
  33454. return _this;
  33455. }
  33456. /**
  33457. * Return the currrent class name of the material.
  33458. */
  33459. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  33460. return "PBRMetallicRoughnessMaterial";
  33461. };
  33462. /**
  33463. * Return the active textures of the material.
  33464. */
  33465. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  33466. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33467. if (this.baseTexture) {
  33468. activeTextures.push(this.baseTexture);
  33469. }
  33470. if (this.metallicRoughnessTexture) {
  33471. activeTextures.push(this.metallicRoughnessTexture);
  33472. }
  33473. return activeTextures;
  33474. };
  33475. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  33476. if (_super.prototype.hasTexture.call(this, texture)) {
  33477. return true;
  33478. }
  33479. if (this.baseTexture === texture) {
  33480. return true;
  33481. }
  33482. if (this.metallicRoughnessTexture === texture) {
  33483. return true;
  33484. }
  33485. return false;
  33486. };
  33487. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  33488. var _this = this;
  33489. return BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  33490. };
  33491. /**
  33492. * Serialize the material to a parsable JSON object.
  33493. */
  33494. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  33495. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33496. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  33497. return serializationObject;
  33498. };
  33499. /**
  33500. * Parses a JSON object correponding to the serialize function.
  33501. */
  33502. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  33503. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  33504. };
  33505. __decorate([
  33506. BABYLON.serializeAsColor3(),
  33507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33508. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  33509. __decorate([
  33510. BABYLON.serializeAsTexture(),
  33511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33512. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  33513. __decorate([
  33514. BABYLON.serialize(),
  33515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33516. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  33517. __decorate([
  33518. BABYLON.serialize(),
  33519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  33520. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  33521. __decorate([
  33522. BABYLON.serializeAsTexture(),
  33523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  33524. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  33525. return PBRMetallicRoughnessMaterial;
  33526. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33527. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  33528. })(BABYLON || (BABYLON = {}));
  33529. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  33530. var BABYLON;
  33531. (function (BABYLON) {
  33532. /**
  33533. * The PBR material of BJS following the specular glossiness convention.
  33534. *
  33535. * This fits to the PBR convention in the GLTF definition:
  33536. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  33537. */
  33538. var PBRSpecularGlossinessMaterial = (function (_super) {
  33539. __extends(PBRSpecularGlossinessMaterial, _super);
  33540. /**
  33541. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  33542. *
  33543. * @param name The material name
  33544. * @param scene The scene the material will be use in.
  33545. */
  33546. function PBRSpecularGlossinessMaterial(name, scene) {
  33547. var _this = _super.call(this, name, scene) || this;
  33548. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  33549. return _this;
  33550. }
  33551. /**
  33552. * Return the currrent class name of the material.
  33553. */
  33554. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  33555. return "PBRSpecularGlossinessMaterial";
  33556. };
  33557. /**
  33558. * Return the active textures of the material.
  33559. */
  33560. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  33561. var activeTextures = _super.prototype.getActiveTextures.call(this);
  33562. if (this.diffuseTexture) {
  33563. activeTextures.push(this.diffuseTexture);
  33564. }
  33565. if (this.specularGlossinessTexture) {
  33566. activeTextures.push(this.specularGlossinessTexture);
  33567. }
  33568. return activeTextures;
  33569. };
  33570. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  33571. if (_super.prototype.hasTexture.call(this, texture)) {
  33572. return true;
  33573. }
  33574. if (this.diffuseTexture === texture) {
  33575. return true;
  33576. }
  33577. if (this.specularGlossinessTexture === texture) {
  33578. return true;
  33579. }
  33580. return false;
  33581. };
  33582. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  33583. var _this = this;
  33584. return BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  33585. };
  33586. /**
  33587. * Serialize the material to a parsable JSON object.
  33588. */
  33589. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  33590. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  33591. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  33592. return serializationObject;
  33593. };
  33594. /**
  33595. * Parses a JSON object correponding to the serialize function.
  33596. */
  33597. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  33598. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  33599. };
  33600. __decorate([
  33601. BABYLON.serializeAsColor3("diffuse"),
  33602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  33603. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  33604. __decorate([
  33605. BABYLON.serializeAsTexture(),
  33606. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  33607. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  33608. __decorate([
  33609. BABYLON.serializeAsColor3("specular"),
  33610. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  33611. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  33612. __decorate([
  33613. BABYLON.serialize(),
  33614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  33615. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  33616. __decorate([
  33617. BABYLON.serializeAsTexture(),
  33618. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  33619. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  33620. return PBRSpecularGlossinessMaterial;
  33621. }(BABYLON.Internals.PBRBaseSimpleMaterial));
  33622. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  33623. })(BABYLON || (BABYLON = {}));
  33624. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  33625. var BABYLON;
  33626. (function (BABYLON) {
  33627. BABYLON.CameraInputTypes = {};
  33628. var CameraInputsManager = (function () {
  33629. function CameraInputsManager(camera) {
  33630. this.attached = {};
  33631. this.camera = camera;
  33632. this.checkInputs = function () { };
  33633. }
  33634. CameraInputsManager.prototype.add = function (input) {
  33635. var type = input.getSimpleName();
  33636. if (this.attached[type]) {
  33637. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  33638. return;
  33639. }
  33640. this.attached[type] = input;
  33641. input.camera = this.camera;
  33642. //for checkInputs, we are dynamically creating a function
  33643. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  33644. if (input.checkInputs) {
  33645. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33646. }
  33647. if (this.attachedElement) {
  33648. input.attachControl(this.attachedElement);
  33649. }
  33650. };
  33651. CameraInputsManager.prototype.remove = function (inputToRemove) {
  33652. for (var cam in this.attached) {
  33653. var input = this.attached[cam];
  33654. if (input === inputToRemove) {
  33655. input.detachControl(this.attachedElement);
  33656. input.camera = null;
  33657. delete this.attached[cam];
  33658. this.rebuildInputCheck();
  33659. }
  33660. }
  33661. };
  33662. CameraInputsManager.prototype.removeByType = function (inputType) {
  33663. for (var cam in this.attached) {
  33664. var input = this.attached[cam];
  33665. if (input.getClassName() === inputType) {
  33666. input.detachControl(this.attachedElement);
  33667. input.camera = null;
  33668. delete this.attached[cam];
  33669. this.rebuildInputCheck();
  33670. }
  33671. }
  33672. };
  33673. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  33674. var current = this.checkInputs;
  33675. return function () {
  33676. current();
  33677. fn();
  33678. };
  33679. };
  33680. CameraInputsManager.prototype.attachInput = function (input) {
  33681. input.attachControl(this.attachedElement, this.noPreventDefault);
  33682. };
  33683. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  33684. if (this.attachedElement) {
  33685. return;
  33686. }
  33687. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  33688. this.attachedElement = element;
  33689. this.noPreventDefault = noPreventDefault;
  33690. for (var cam in this.attached) {
  33691. var input = this.attached[cam];
  33692. this.attached[cam].attachControl(element, noPreventDefault);
  33693. }
  33694. };
  33695. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  33696. if (disconnect === void 0) { disconnect = false; }
  33697. if (this.attachedElement !== element) {
  33698. return;
  33699. }
  33700. for (var cam in this.attached) {
  33701. var input = this.attached[cam];
  33702. this.attached[cam].detachControl(element);
  33703. if (disconnect) {
  33704. this.attached[cam].camera = null;
  33705. }
  33706. }
  33707. this.attachedElement = null;
  33708. };
  33709. CameraInputsManager.prototype.rebuildInputCheck = function () {
  33710. this.checkInputs = function () { };
  33711. for (var cam in this.attached) {
  33712. var input = this.attached[cam];
  33713. if (input.checkInputs) {
  33714. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  33715. }
  33716. }
  33717. };
  33718. CameraInputsManager.prototype.clear = function () {
  33719. if (this.attachedElement) {
  33720. this.detachElement(this.attachedElement, true);
  33721. }
  33722. this.attached = {};
  33723. this.attachedElement = null;
  33724. this.checkInputs = function () { };
  33725. };
  33726. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  33727. var inputs = {};
  33728. for (var cam in this.attached) {
  33729. var input = this.attached[cam];
  33730. var res = BABYLON.SerializationHelper.Serialize(input);
  33731. inputs[input.getClassName()] = res;
  33732. }
  33733. serializedCamera.inputsmgr = inputs;
  33734. };
  33735. CameraInputsManager.prototype.parse = function (parsedCamera) {
  33736. var parsedInputs = parsedCamera.inputsmgr;
  33737. if (parsedInputs) {
  33738. this.clear();
  33739. for (var n in parsedInputs) {
  33740. var construct = BABYLON.CameraInputTypes[n];
  33741. if (construct) {
  33742. var parsedinput = parsedInputs[n];
  33743. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  33744. this.add(input);
  33745. }
  33746. }
  33747. }
  33748. else {
  33749. //2016-03-08 this part is for managing backward compatibility
  33750. for (var n in this.attached) {
  33751. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  33752. if (construct) {
  33753. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  33754. this.remove(this.attached[n]);
  33755. this.add(input);
  33756. }
  33757. }
  33758. }
  33759. };
  33760. return CameraInputsManager;
  33761. }());
  33762. BABYLON.CameraInputsManager = CameraInputsManager;
  33763. })(BABYLON || (BABYLON = {}));
  33764. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  33765. var BABYLON;
  33766. (function (BABYLON) {
  33767. var FreeCameraMouseInput = (function () {
  33768. function FreeCameraMouseInput(touchEnabled) {
  33769. if (touchEnabled === void 0) { touchEnabled = true; }
  33770. this.touchEnabled = touchEnabled;
  33771. this.buttons = [0, 1, 2];
  33772. this.angularSensibility = 2000.0;
  33773. }
  33774. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  33775. var _this = this;
  33776. var engine = this.camera.getEngine();
  33777. if (!this._pointerInput) {
  33778. this._pointerInput = function (p, s) {
  33779. var evt = p.event;
  33780. if (!_this.touchEnabled && evt.pointerType === "touch") {
  33781. return;
  33782. }
  33783. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  33784. return;
  33785. }
  33786. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  33787. try {
  33788. evt.srcElement.setPointerCapture(evt.pointerId);
  33789. }
  33790. catch (e) {
  33791. //Nothing to do with the error. Execution will continue.
  33792. }
  33793. _this.previousPosition = {
  33794. x: evt.clientX,
  33795. y: evt.clientY
  33796. };
  33797. if (!noPreventDefault) {
  33798. evt.preventDefault();
  33799. element.focus();
  33800. }
  33801. }
  33802. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  33803. try {
  33804. evt.srcElement.releasePointerCapture(evt.pointerId);
  33805. }
  33806. catch (e) {
  33807. //Nothing to do with the error.
  33808. }
  33809. _this.previousPosition = null;
  33810. if (!noPreventDefault) {
  33811. evt.preventDefault();
  33812. }
  33813. }
  33814. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  33815. if (!_this.previousPosition || engine.isPointerLock) {
  33816. return;
  33817. }
  33818. var offsetX = evt.clientX - _this.previousPosition.x;
  33819. var offsetY = evt.clientY - _this.previousPosition.y;
  33820. if (_this.camera.getScene().useRightHandedSystem) {
  33821. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33822. }
  33823. else {
  33824. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33825. }
  33826. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33827. _this.previousPosition = {
  33828. x: evt.clientX,
  33829. y: evt.clientY
  33830. };
  33831. if (!noPreventDefault) {
  33832. evt.preventDefault();
  33833. }
  33834. }
  33835. };
  33836. }
  33837. this._onMouseMove = function (evt) {
  33838. if (!engine.isPointerLock) {
  33839. return;
  33840. }
  33841. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  33842. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  33843. if (_this.camera.getScene().useRightHandedSystem) {
  33844. _this.camera.cameraRotation.y -= offsetX / _this.angularSensibility;
  33845. }
  33846. else {
  33847. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  33848. }
  33849. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  33850. _this.previousPosition = null;
  33851. if (!noPreventDefault) {
  33852. evt.preventDefault();
  33853. }
  33854. };
  33855. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  33856. element.addEventListener("mousemove", this._onMouseMove, false);
  33857. };
  33858. FreeCameraMouseInput.prototype.detachControl = function (element) {
  33859. if (this._observer && element) {
  33860. this.camera.getScene().onPointerObservable.remove(this._observer);
  33861. element.removeEventListener("mousemove", this._onMouseMove);
  33862. this._observer = null;
  33863. this._onMouseMove = null;
  33864. this.previousPosition = null;
  33865. }
  33866. };
  33867. FreeCameraMouseInput.prototype.getClassName = function () {
  33868. return "FreeCameraMouseInput";
  33869. };
  33870. FreeCameraMouseInput.prototype.getSimpleName = function () {
  33871. return "mouse";
  33872. };
  33873. __decorate([
  33874. BABYLON.serialize()
  33875. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  33876. __decorate([
  33877. BABYLON.serialize()
  33878. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  33879. return FreeCameraMouseInput;
  33880. }());
  33881. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  33882. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  33883. })(BABYLON || (BABYLON = {}));
  33884. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  33885. var BABYLON;
  33886. (function (BABYLON) {
  33887. var FreeCameraKeyboardMoveInput = (function () {
  33888. function FreeCameraKeyboardMoveInput() {
  33889. this._keys = [];
  33890. this.keysUp = [38];
  33891. this.keysDown = [40];
  33892. this.keysLeft = [37];
  33893. this.keysRight = [39];
  33894. }
  33895. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  33896. var _this = this;
  33897. if (!this._onKeyDown) {
  33898. element.tabIndex = 1;
  33899. this._onKeyDown = function (evt) {
  33900. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33901. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33902. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33903. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33904. var index = _this._keys.indexOf(evt.keyCode);
  33905. if (index === -1) {
  33906. _this._keys.push(evt.keyCode);
  33907. }
  33908. if (!noPreventDefault) {
  33909. evt.preventDefault();
  33910. }
  33911. }
  33912. };
  33913. this._onKeyUp = function (evt) {
  33914. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  33915. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  33916. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  33917. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  33918. var index = _this._keys.indexOf(evt.keyCode);
  33919. if (index >= 0) {
  33920. _this._keys.splice(index, 1);
  33921. }
  33922. if (!noPreventDefault) {
  33923. evt.preventDefault();
  33924. }
  33925. }
  33926. };
  33927. element.addEventListener("keydown", this._onKeyDown, false);
  33928. element.addEventListener("keyup", this._onKeyUp, false);
  33929. BABYLON.Tools.RegisterTopRootEvents([
  33930. { name: "blur", handler: this._onLostFocus }
  33931. ]);
  33932. }
  33933. };
  33934. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  33935. if (this._onKeyDown) {
  33936. element.removeEventListener("keydown", this._onKeyDown);
  33937. element.removeEventListener("keyup", this._onKeyUp);
  33938. BABYLON.Tools.UnregisterTopRootEvents([
  33939. { name: "blur", handler: this._onLostFocus }
  33940. ]);
  33941. this._keys = [];
  33942. this._onKeyDown = null;
  33943. this._onKeyUp = null;
  33944. }
  33945. };
  33946. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  33947. if (this._onKeyDown) {
  33948. var camera = this.camera;
  33949. // Keyboard
  33950. for (var index = 0; index < this._keys.length; index++) {
  33951. var keyCode = this._keys[index];
  33952. var speed = camera._computeLocalCameraSpeed();
  33953. if (this.keysLeft.indexOf(keyCode) !== -1) {
  33954. camera._localDirection.copyFromFloats(-speed, 0, 0);
  33955. }
  33956. else if (this.keysUp.indexOf(keyCode) !== -1) {
  33957. camera._localDirection.copyFromFloats(0, 0, speed);
  33958. }
  33959. else if (this.keysRight.indexOf(keyCode) !== -1) {
  33960. camera._localDirection.copyFromFloats(speed, 0, 0);
  33961. }
  33962. else if (this.keysDown.indexOf(keyCode) !== -1) {
  33963. camera._localDirection.copyFromFloats(0, 0, -speed);
  33964. }
  33965. if (camera.getScene().useRightHandedSystem) {
  33966. camera._localDirection.z *= -1;
  33967. }
  33968. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  33969. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  33970. camera.cameraDirection.addInPlace(camera._transformedDirection);
  33971. }
  33972. }
  33973. };
  33974. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  33975. return "FreeCameraKeyboardMoveInput";
  33976. };
  33977. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  33978. this._keys = [];
  33979. };
  33980. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  33981. return "keyboard";
  33982. };
  33983. __decorate([
  33984. BABYLON.serialize()
  33985. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  33986. __decorate([
  33987. BABYLON.serialize()
  33988. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  33989. __decorate([
  33990. BABYLON.serialize()
  33991. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  33992. __decorate([
  33993. BABYLON.serialize()
  33994. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  33995. return FreeCameraKeyboardMoveInput;
  33996. }());
  33997. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  33998. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  33999. })(BABYLON || (BABYLON = {}));
  34000. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  34001. var BABYLON;
  34002. (function (BABYLON) {
  34003. var FreeCameraInputsManager = (function (_super) {
  34004. __extends(FreeCameraInputsManager, _super);
  34005. function FreeCameraInputsManager(camera) {
  34006. return _super.call(this, camera) || this;
  34007. }
  34008. FreeCameraInputsManager.prototype.addKeyboard = function () {
  34009. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  34010. return this;
  34011. };
  34012. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  34013. if (touchEnabled === void 0) { touchEnabled = true; }
  34014. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  34015. return this;
  34016. };
  34017. FreeCameraInputsManager.prototype.addGamepad = function () {
  34018. this.add(new BABYLON.FreeCameraGamepadInput());
  34019. return this;
  34020. };
  34021. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  34022. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  34023. return this;
  34024. };
  34025. FreeCameraInputsManager.prototype.addTouch = function () {
  34026. this.add(new BABYLON.FreeCameraTouchInput());
  34027. return this;
  34028. };
  34029. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  34030. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  34031. return this;
  34032. };
  34033. return FreeCameraInputsManager;
  34034. }(BABYLON.CameraInputsManager));
  34035. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  34036. })(BABYLON || (BABYLON = {}));
  34037. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  34038. /// <reference path="babylon.camera.ts" />
  34039. var BABYLON;
  34040. (function (BABYLON) {
  34041. var TargetCamera = (function (_super) {
  34042. __extends(TargetCamera, _super);
  34043. function TargetCamera(name, position, scene) {
  34044. var _this = _super.call(this, name, position, scene) || this;
  34045. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34046. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  34047. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  34048. _this.speed = 2.0;
  34049. _this.noRotationConstraint = false;
  34050. _this.lockedTarget = null;
  34051. _this._currentTarget = BABYLON.Vector3.Zero();
  34052. _this._viewMatrix = BABYLON.Matrix.Zero();
  34053. _this._camMatrix = BABYLON.Matrix.Zero();
  34054. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  34055. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  34056. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  34057. _this._defaultUpVector = new BABYLON.Vector3(0, 1, 0);
  34058. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  34059. _this._lookAtTemp = BABYLON.Matrix.Zero();
  34060. _this._tempMatrix = BABYLON.Matrix.Zero();
  34061. return _this;
  34062. }
  34063. TargetCamera.prototype.getFrontPosition = function (distance) {
  34064. var direction = this.getTarget().subtract(this.position);
  34065. direction.normalize();
  34066. direction.scaleInPlace(distance);
  34067. return this.globalPosition.add(direction);
  34068. };
  34069. TargetCamera.prototype._getLockedTargetPosition = function () {
  34070. if (!this.lockedTarget) {
  34071. return null;
  34072. }
  34073. if (this.lockedTarget.absolutePosition) {
  34074. this.lockedTarget.computeWorldMatrix();
  34075. }
  34076. return this.lockedTarget.absolutePosition || this.lockedTarget;
  34077. };
  34078. // Cache
  34079. TargetCamera.prototype._initCache = function () {
  34080. _super.prototype._initCache.call(this);
  34081. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34082. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34083. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  34084. };
  34085. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  34086. if (!ignoreParentClass) {
  34087. _super.prototype._updateCache.call(this);
  34088. }
  34089. var lockedTargetPosition = this._getLockedTargetPosition();
  34090. if (!lockedTargetPosition) {
  34091. this._cache.lockedTarget = null;
  34092. }
  34093. else {
  34094. if (!this._cache.lockedTarget) {
  34095. this._cache.lockedTarget = lockedTargetPosition.clone();
  34096. }
  34097. else {
  34098. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  34099. }
  34100. }
  34101. this._cache.rotation.copyFrom(this.rotation);
  34102. if (this.rotationQuaternion)
  34103. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34104. };
  34105. // Synchronized
  34106. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  34107. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  34108. return false;
  34109. }
  34110. var lockedTargetPosition = this._getLockedTargetPosition();
  34111. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  34112. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  34113. };
  34114. // Methods
  34115. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  34116. var engine = this.getEngine();
  34117. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  34118. };
  34119. // Target
  34120. TargetCamera.prototype.setTarget = function (target) {
  34121. this.upVector.normalize();
  34122. BABYLON.Matrix.LookAtLHToRef(this.position, target, this._defaultUpVector, this._camMatrix);
  34123. this._camMatrix.invert();
  34124. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  34125. var vDir = target.subtract(this.position);
  34126. if (vDir.x >= 0.0) {
  34127. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  34128. }
  34129. else {
  34130. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  34131. }
  34132. this.rotation.z = 0;
  34133. if (isNaN(this.rotation.x)) {
  34134. this.rotation.x = 0;
  34135. }
  34136. if (isNaN(this.rotation.y)) {
  34137. this.rotation.y = 0;
  34138. }
  34139. if (isNaN(this.rotation.z)) {
  34140. this.rotation.z = 0;
  34141. }
  34142. if (this.rotationQuaternion) {
  34143. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34144. }
  34145. };
  34146. /**
  34147. * Return the current target position of the camera. This value is expressed in local space.
  34148. */
  34149. TargetCamera.prototype.getTarget = function () {
  34150. return this._currentTarget;
  34151. };
  34152. TargetCamera.prototype._decideIfNeedsToMove = function () {
  34153. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34154. };
  34155. TargetCamera.prototype._updatePosition = function () {
  34156. if (this.parent) {
  34157. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  34158. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  34159. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  34160. return;
  34161. }
  34162. this.position.addInPlace(this.cameraDirection);
  34163. };
  34164. TargetCamera.prototype._checkInputs = function () {
  34165. var needToMove = this._decideIfNeedsToMove();
  34166. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  34167. // Move
  34168. if (needToMove) {
  34169. this._updatePosition();
  34170. }
  34171. // Rotate
  34172. if (needToRotate) {
  34173. this.rotation.x += this.cameraRotation.x;
  34174. this.rotation.y += this.cameraRotation.y;
  34175. //rotate, if quaternion is set and rotation was used
  34176. if (this.rotationQuaternion) {
  34177. var len = this.rotation.lengthSquared();
  34178. if (len) {
  34179. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  34180. }
  34181. }
  34182. if (!this.noRotationConstraint) {
  34183. var limit = (Math.PI / 2) * 0.95;
  34184. if (this.rotation.x > limit)
  34185. this.rotation.x = limit;
  34186. if (this.rotation.x < -limit)
  34187. this.rotation.x = -limit;
  34188. }
  34189. }
  34190. // Inertia
  34191. if (needToMove) {
  34192. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  34193. this.cameraDirection.x = 0;
  34194. }
  34195. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  34196. this.cameraDirection.y = 0;
  34197. }
  34198. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  34199. this.cameraDirection.z = 0;
  34200. }
  34201. this.cameraDirection.scaleInPlace(this.inertia);
  34202. }
  34203. if (needToRotate) {
  34204. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  34205. this.cameraRotation.x = 0;
  34206. }
  34207. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  34208. this.cameraRotation.y = 0;
  34209. }
  34210. this.cameraRotation.scaleInPlace(this.inertia);
  34211. }
  34212. _super.prototype._checkInputs.call(this);
  34213. };
  34214. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  34215. if (this.rotationQuaternion) {
  34216. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  34217. //update the up vector!
  34218. BABYLON.Vector3.TransformNormalToRef(this._defaultUpVector, this._cameraRotationMatrix, this.upVector);
  34219. }
  34220. else {
  34221. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  34222. }
  34223. };
  34224. TargetCamera.prototype._getViewMatrix = function () {
  34225. if (!this.lockedTarget) {
  34226. // Compute
  34227. this._updateCameraRotationMatrix();
  34228. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  34229. // Computing target and final matrix
  34230. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  34231. }
  34232. else {
  34233. this._currentTarget.copyFrom(this._getLockedTargetPosition());
  34234. }
  34235. if (this.getScene().useRightHandedSystem) {
  34236. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34237. }
  34238. else {
  34239. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._viewMatrix);
  34240. }
  34241. return this._viewMatrix;
  34242. };
  34243. /**
  34244. * @override
  34245. * Override Camera.createRigCamera
  34246. */
  34247. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  34248. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  34249. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  34250. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  34251. if (!this.rotationQuaternion) {
  34252. this.rotationQuaternion = new BABYLON.Quaternion();
  34253. }
  34254. rigCamera._cameraRigParams = {};
  34255. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  34256. }
  34257. return rigCamera;
  34258. }
  34259. return null;
  34260. };
  34261. /**
  34262. * @override
  34263. * Override Camera._updateRigCameras
  34264. */
  34265. TargetCamera.prototype._updateRigCameras = function () {
  34266. var camLeft = this._rigCameras[0];
  34267. var camRight = this._rigCameras[1];
  34268. switch (this.cameraRigMode) {
  34269. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  34270. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  34271. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  34272. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  34273. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  34274. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  34275. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  34276. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  34277. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  34278. camLeft.setTarget(this.getTarget());
  34279. camRight.setTarget(this.getTarget());
  34280. break;
  34281. case BABYLON.Camera.RIG_MODE_VR:
  34282. if (camLeft.rotationQuaternion) {
  34283. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34284. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  34285. }
  34286. else {
  34287. camLeft.rotation.copyFrom(this.rotation);
  34288. camRight.rotation.copyFrom(this.rotation);
  34289. }
  34290. camLeft.position.copyFrom(this.position);
  34291. camRight.position.copyFrom(this.position);
  34292. break;
  34293. }
  34294. _super.prototype._updateRigCameras.call(this);
  34295. };
  34296. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  34297. if (!this._rigCamTransformMatrix) {
  34298. this._rigCamTransformMatrix = new BABYLON.Matrix();
  34299. }
  34300. var target = this.getTarget();
  34301. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  34302. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  34303. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  34304. };
  34305. TargetCamera.prototype.getClassName = function () {
  34306. return "TargetCamera";
  34307. };
  34308. __decorate([
  34309. BABYLON.serializeAsVector3()
  34310. ], TargetCamera.prototype, "rotation", void 0);
  34311. __decorate([
  34312. BABYLON.serialize()
  34313. ], TargetCamera.prototype, "speed", void 0);
  34314. __decorate([
  34315. BABYLON.serializeAsMeshReference("lockedTargetId")
  34316. ], TargetCamera.prototype, "lockedTarget", void 0);
  34317. return TargetCamera;
  34318. }(BABYLON.Camera));
  34319. BABYLON.TargetCamera = TargetCamera;
  34320. })(BABYLON || (BABYLON = {}));
  34321. //# sourceMappingURL=babylon.targetCamera.js.map
  34322. var BABYLON;
  34323. (function (BABYLON) {
  34324. var FreeCamera = (function (_super) {
  34325. __extends(FreeCamera, _super);
  34326. function FreeCamera(name, position, scene) {
  34327. var _this = _super.call(this, name, position, scene) || this;
  34328. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  34329. _this.checkCollisions = false;
  34330. _this.applyGravity = false;
  34331. _this._needMoveForGravity = false;
  34332. _this._oldPosition = BABYLON.Vector3.Zero();
  34333. _this._diffPosition = BABYLON.Vector3.Zero();
  34334. _this._newPosition = BABYLON.Vector3.Zero();
  34335. // Collisions
  34336. _this._collisionMask = -1;
  34337. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34338. if (collidedMesh === void 0) { collidedMesh = null; }
  34339. //TODO move this to the collision coordinator!
  34340. if (_this.getScene().workerCollisions)
  34341. newPosition.multiplyInPlace(_this._collider.radius);
  34342. var updatePosition = function (newPos) {
  34343. _this._newPosition.copyFrom(newPos);
  34344. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  34345. var oldPosition = _this.position.clone();
  34346. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  34347. _this.position.addInPlace(_this._diffPosition);
  34348. if (_this.onCollide && collidedMesh) {
  34349. _this.onCollide(collidedMesh);
  34350. }
  34351. }
  34352. };
  34353. updatePosition(newPosition);
  34354. };
  34355. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  34356. _this.inputs.addKeyboard().addMouse();
  34357. return _this;
  34358. }
  34359. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  34360. //-- begin properties for backward compatibility for inputs
  34361. get: function () {
  34362. var mouse = this.inputs.attached["mouse"];
  34363. if (mouse)
  34364. return mouse.angularSensibility;
  34365. },
  34366. set: function (value) {
  34367. var mouse = this.inputs.attached["mouse"];
  34368. if (mouse)
  34369. mouse.angularSensibility = value;
  34370. },
  34371. enumerable: true,
  34372. configurable: true
  34373. });
  34374. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  34375. get: function () {
  34376. var keyboard = this.inputs.attached["keyboard"];
  34377. if (keyboard)
  34378. return keyboard.keysUp;
  34379. },
  34380. set: function (value) {
  34381. var keyboard = this.inputs.attached["keyboard"];
  34382. if (keyboard)
  34383. keyboard.keysUp = value;
  34384. },
  34385. enumerable: true,
  34386. configurable: true
  34387. });
  34388. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  34389. get: function () {
  34390. var keyboard = this.inputs.attached["keyboard"];
  34391. if (keyboard)
  34392. return keyboard.keysDown;
  34393. },
  34394. set: function (value) {
  34395. var keyboard = this.inputs.attached["keyboard"];
  34396. if (keyboard)
  34397. keyboard.keysDown = value;
  34398. },
  34399. enumerable: true,
  34400. configurable: true
  34401. });
  34402. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  34403. get: function () {
  34404. var keyboard = this.inputs.attached["keyboard"];
  34405. if (keyboard)
  34406. return keyboard.keysLeft;
  34407. },
  34408. set: function (value) {
  34409. var keyboard = this.inputs.attached["keyboard"];
  34410. if (keyboard)
  34411. keyboard.keysLeft = value;
  34412. },
  34413. enumerable: true,
  34414. configurable: true
  34415. });
  34416. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  34417. get: function () {
  34418. var keyboard = this.inputs.attached["keyboard"];
  34419. if (keyboard)
  34420. return keyboard.keysRight;
  34421. },
  34422. set: function (value) {
  34423. var keyboard = this.inputs.attached["keyboard"];
  34424. if (keyboard)
  34425. keyboard.keysRight = value;
  34426. },
  34427. enumerable: true,
  34428. configurable: true
  34429. });
  34430. // Controls
  34431. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  34432. this.inputs.attachElement(element, noPreventDefault);
  34433. };
  34434. FreeCamera.prototype.detachControl = function (element) {
  34435. this.inputs.detachElement(element);
  34436. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  34437. this.cameraRotation = new BABYLON.Vector2(0, 0);
  34438. };
  34439. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  34440. get: function () {
  34441. return this._collisionMask;
  34442. },
  34443. set: function (mask) {
  34444. this._collisionMask = !isNaN(mask) ? mask : -1;
  34445. },
  34446. enumerable: true,
  34447. configurable: true
  34448. });
  34449. FreeCamera.prototype._collideWithWorld = function (direction) {
  34450. var globalPosition;
  34451. if (this.parent) {
  34452. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  34453. }
  34454. else {
  34455. globalPosition = this.position;
  34456. }
  34457. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  34458. if (!this._collider) {
  34459. this._collider = new BABYLON.Collider();
  34460. }
  34461. this._collider.radius = this.ellipsoid;
  34462. this._collider.collisionMask = this._collisionMask;
  34463. //no need for clone, as long as gravity is not on.
  34464. var actualDirection = direction;
  34465. //add gravity to the direction to prevent the dual-collision checking
  34466. if (this.applyGravity) {
  34467. //this prevents mending with cameraDirection, a global variable of the free camera class.
  34468. actualDirection = direction.add(this.getScene().gravity);
  34469. }
  34470. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDirection, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  34471. };
  34472. FreeCamera.prototype._checkInputs = function () {
  34473. if (!this._localDirection) {
  34474. this._localDirection = BABYLON.Vector3.Zero();
  34475. this._transformedDirection = BABYLON.Vector3.Zero();
  34476. }
  34477. this.inputs.checkInputs();
  34478. _super.prototype._checkInputs.call(this);
  34479. };
  34480. FreeCamera.prototype._decideIfNeedsToMove = function () {
  34481. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  34482. };
  34483. FreeCamera.prototype._updatePosition = function () {
  34484. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  34485. this._collideWithWorld(this.cameraDirection);
  34486. }
  34487. else {
  34488. _super.prototype._updatePosition.call(this);
  34489. }
  34490. };
  34491. FreeCamera.prototype.dispose = function () {
  34492. this.inputs.clear();
  34493. _super.prototype.dispose.call(this);
  34494. };
  34495. FreeCamera.prototype.getClassName = function () {
  34496. return "FreeCamera";
  34497. };
  34498. __decorate([
  34499. BABYLON.serializeAsVector3()
  34500. ], FreeCamera.prototype, "ellipsoid", void 0);
  34501. __decorate([
  34502. BABYLON.serialize()
  34503. ], FreeCamera.prototype, "checkCollisions", void 0);
  34504. __decorate([
  34505. BABYLON.serialize()
  34506. ], FreeCamera.prototype, "applyGravity", void 0);
  34507. return FreeCamera;
  34508. }(BABYLON.TargetCamera));
  34509. BABYLON.FreeCamera = FreeCamera;
  34510. })(BABYLON || (BABYLON = {}));
  34511. //# sourceMappingURL=babylon.freeCamera.js.map
  34512. var BABYLON;
  34513. (function (BABYLON) {
  34514. var ArcRotateCameraKeyboardMoveInput = (function () {
  34515. function ArcRotateCameraKeyboardMoveInput() {
  34516. this._keys = [];
  34517. this.keysUp = [38];
  34518. this.keysDown = [40];
  34519. this.keysLeft = [37];
  34520. this.keysRight = [39];
  34521. }
  34522. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  34523. var _this = this;
  34524. element.tabIndex = 1;
  34525. this._onKeyDown = function (evt) {
  34526. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34527. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34528. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34529. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34530. var index = _this._keys.indexOf(evt.keyCode);
  34531. if (index === -1) {
  34532. _this._keys.push(evt.keyCode);
  34533. }
  34534. if (evt.preventDefault) {
  34535. if (!noPreventDefault) {
  34536. evt.preventDefault();
  34537. }
  34538. }
  34539. }
  34540. };
  34541. this._onKeyUp = function (evt) {
  34542. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  34543. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  34544. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  34545. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  34546. var index = _this._keys.indexOf(evt.keyCode);
  34547. if (index >= 0) {
  34548. _this._keys.splice(index, 1);
  34549. }
  34550. if (evt.preventDefault) {
  34551. if (!noPreventDefault) {
  34552. evt.preventDefault();
  34553. }
  34554. }
  34555. }
  34556. };
  34557. this._onLostFocus = function () {
  34558. _this._keys = [];
  34559. };
  34560. this._onFocus = function () {
  34561. element.addEventListener("keydown", _this._onKeyDown, false);
  34562. element.addEventListener("keyup", _this._onKeyUp, false);
  34563. };
  34564. this._onBlur = function () {
  34565. element.removeEventListener("keydown", _this._onKeyDown);
  34566. element.removeEventListener("keyup", _this._onKeyUp);
  34567. };
  34568. element.addEventListener("focus", this._onFocus);
  34569. element.addEventListener("blur", this._onBlur);
  34570. BABYLON.Tools.RegisterTopRootEvents([
  34571. { name: "blur", handler: this._onLostFocus }
  34572. ]);
  34573. };
  34574. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  34575. if (element && this._onBlur) {
  34576. this._onBlur();
  34577. element.removeEventListener("focus", this._onFocus);
  34578. element.removeEventListener("blur", this._onBlur);
  34579. }
  34580. BABYLON.Tools.UnregisterTopRootEvents([
  34581. { name: "blur", handler: this._onLostFocus }
  34582. ]);
  34583. this._keys = [];
  34584. this._onKeyDown = null;
  34585. this._onKeyUp = null;
  34586. this._onLostFocus = null;
  34587. this._onBlur = null;
  34588. this._onFocus = null;
  34589. };
  34590. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  34591. if (this._onKeyDown) {
  34592. var camera = this.camera;
  34593. for (var index = 0; index < this._keys.length; index++) {
  34594. var keyCode = this._keys[index];
  34595. if (this.keysLeft.indexOf(keyCode) !== -1) {
  34596. camera.inertialAlphaOffset -= 0.01;
  34597. }
  34598. else if (this.keysUp.indexOf(keyCode) !== -1) {
  34599. camera.inertialBetaOffset -= 0.01;
  34600. }
  34601. else if (this.keysRight.indexOf(keyCode) !== -1) {
  34602. camera.inertialAlphaOffset += 0.01;
  34603. }
  34604. else if (this.keysDown.indexOf(keyCode) !== -1) {
  34605. camera.inertialBetaOffset += 0.01;
  34606. }
  34607. }
  34608. }
  34609. };
  34610. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  34611. return "ArcRotateCameraKeyboardMoveInput";
  34612. };
  34613. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  34614. return "keyboard";
  34615. };
  34616. __decorate([
  34617. BABYLON.serialize()
  34618. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  34619. __decorate([
  34620. BABYLON.serialize()
  34621. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  34622. __decorate([
  34623. BABYLON.serialize()
  34624. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  34625. __decorate([
  34626. BABYLON.serialize()
  34627. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  34628. return ArcRotateCameraKeyboardMoveInput;
  34629. }());
  34630. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  34631. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  34632. })(BABYLON || (BABYLON = {}));
  34633. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  34634. var BABYLON;
  34635. (function (BABYLON) {
  34636. var ArcRotateCameraMouseWheelInput = (function () {
  34637. function ArcRotateCameraMouseWheelInput() {
  34638. this.wheelPrecision = 3.0;
  34639. }
  34640. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  34641. var _this = this;
  34642. this._wheel = function (p, s) {
  34643. //sanity check - this should be a PointerWheel event.
  34644. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  34645. return;
  34646. var event = p.event;
  34647. var delta = 0;
  34648. if (event.wheelDelta) {
  34649. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  34650. }
  34651. else if (event.detail) {
  34652. delta = -event.detail / _this.wheelPrecision;
  34653. }
  34654. if (delta)
  34655. _this.camera.inertialRadiusOffset += delta;
  34656. if (event.preventDefault) {
  34657. if (!noPreventDefault) {
  34658. event.preventDefault();
  34659. }
  34660. }
  34661. };
  34662. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  34663. };
  34664. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  34665. if (this._observer && element) {
  34666. this.camera.getScene().onPointerObservable.remove(this._observer);
  34667. this._observer = null;
  34668. this._wheel = null;
  34669. }
  34670. };
  34671. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  34672. return "ArcRotateCameraMouseWheelInput";
  34673. };
  34674. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  34675. return "mousewheel";
  34676. };
  34677. __decorate([
  34678. BABYLON.serialize()
  34679. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  34680. return ArcRotateCameraMouseWheelInput;
  34681. }());
  34682. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  34683. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  34684. })(BABYLON || (BABYLON = {}));
  34685. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  34686. var BABYLON;
  34687. (function (BABYLON) {
  34688. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  34689. var ArcRotateCameraPointersInput = (function () {
  34690. function ArcRotateCameraPointersInput() {
  34691. this.buttons = [0, 1, 2];
  34692. this.angularSensibilityX = 1000.0;
  34693. this.angularSensibilityY = 1000.0;
  34694. this.pinchPrecision = 6.0;
  34695. this.panningSensibility = 50.0;
  34696. this._isPanClick = false;
  34697. this.pinchInwards = true;
  34698. }
  34699. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  34700. var _this = this;
  34701. var engine = this.camera.getEngine();
  34702. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  34703. var pointA, pointB;
  34704. var previousPinchDistance = 0;
  34705. this._pointerInput = function (p, s) {
  34706. var evt = p.event;
  34707. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  34708. return;
  34709. }
  34710. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  34711. try {
  34712. evt.srcElement.setPointerCapture(evt.pointerId);
  34713. }
  34714. catch (e) {
  34715. //Nothing to do with the error. Execution will continue.
  34716. }
  34717. // Manage panning with pan button click
  34718. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  34719. // manage pointers
  34720. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  34721. if (pointA === undefined) {
  34722. pointA = cacheSoloPointer;
  34723. }
  34724. else if (pointB === undefined) {
  34725. pointB = cacheSoloPointer;
  34726. }
  34727. if (!noPreventDefault) {
  34728. evt.preventDefault();
  34729. element.focus();
  34730. }
  34731. }
  34732. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  34733. try {
  34734. evt.srcElement.releasePointerCapture(evt.pointerId);
  34735. }
  34736. catch (e) {
  34737. //Nothing to do with the error.
  34738. }
  34739. cacheSoloPointer = null;
  34740. previousPinchDistance = 0;
  34741. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  34742. //but emptying completly pointers collection is required to fix a bug on iPhone :
  34743. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  34744. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  34745. pointA = pointB = undefined;
  34746. if (!noPreventDefault) {
  34747. evt.preventDefault();
  34748. }
  34749. }
  34750. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  34751. if (!noPreventDefault) {
  34752. evt.preventDefault();
  34753. }
  34754. // One button down
  34755. if (pointA && pointB === undefined) {
  34756. if (_this.panningSensibility !== 0 &&
  34757. ((evt.ctrlKey && _this.camera._useCtrlForPanning) ||
  34758. (!_this.camera._useCtrlForPanning && _this._isPanClick))) {
  34759. _this.camera
  34760. .inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  34761. _this.camera
  34762. .inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  34763. }
  34764. else {
  34765. var offsetX = evt.clientX - cacheSoloPointer.x;
  34766. var offsetY = evt.clientY - cacheSoloPointer.y;
  34767. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34768. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34769. }
  34770. cacheSoloPointer.x = evt.clientX;
  34771. cacheSoloPointer.y = evt.clientY;
  34772. }
  34773. else if (pointA && pointB) {
  34774. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  34775. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  34776. ed.x = evt.clientX;
  34777. ed.y = evt.clientY;
  34778. var direction = _this.pinchInwards ? 1 : -1;
  34779. var distX = pointA.x - pointB.x;
  34780. var distY = pointA.y - pointB.y;
  34781. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  34782. if (previousPinchDistance === 0) {
  34783. previousPinchDistance = pinchSquaredDistance;
  34784. return;
  34785. }
  34786. if (pinchSquaredDistance !== previousPinchDistance) {
  34787. _this.camera
  34788. .inertialRadiusOffset += (pinchSquaredDistance - previousPinchDistance) /
  34789. (_this.pinchPrecision *
  34790. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  34791. direction);
  34792. previousPinchDistance = pinchSquaredDistance;
  34793. }
  34794. }
  34795. }
  34796. };
  34797. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  34798. this._onContextMenu = function (evt) {
  34799. evt.preventDefault();
  34800. };
  34801. if (!this.camera._useCtrlForPanning) {
  34802. element.addEventListener("contextmenu", this._onContextMenu, false);
  34803. }
  34804. this._onLostFocus = function () {
  34805. //this._keys = [];
  34806. pointA = pointB = undefined;
  34807. previousPinchDistance = 0;
  34808. cacheSoloPointer = null;
  34809. };
  34810. this._onMouseMove = function (evt) {
  34811. if (!engine.isPointerLock) {
  34812. return;
  34813. }
  34814. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  34815. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  34816. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  34817. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  34818. if (!noPreventDefault) {
  34819. evt.preventDefault();
  34820. }
  34821. };
  34822. this._onGestureStart = function (e) {
  34823. if (window.MSGesture === undefined) {
  34824. return;
  34825. }
  34826. if (!_this._MSGestureHandler) {
  34827. _this._MSGestureHandler = new MSGesture();
  34828. _this._MSGestureHandler.target = element;
  34829. }
  34830. _this._MSGestureHandler.addPointer(e.pointerId);
  34831. };
  34832. this._onGesture = function (e) {
  34833. _this.camera.radius *= e.scale;
  34834. if (e.preventDefault) {
  34835. if (!noPreventDefault) {
  34836. e.stopPropagation();
  34837. e.preventDefault();
  34838. }
  34839. }
  34840. };
  34841. element.addEventListener("mousemove", this._onMouseMove, false);
  34842. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  34843. element.addEventListener("MSGestureChange", this._onGesture, false);
  34844. BABYLON.Tools.RegisterTopRootEvents([
  34845. { name: "blur", handler: this._onLostFocus }
  34846. ]);
  34847. };
  34848. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  34849. BABYLON.Tools.UnregisterTopRootEvents([
  34850. { name: "blur", handler: this._onLostFocus }
  34851. ]);
  34852. if (element && this._observer) {
  34853. this.camera.getScene().onPointerObservable.remove(this._observer);
  34854. this._observer = null;
  34855. element.removeEventListener("contextmenu", this._onContextMenu);
  34856. element.removeEventListener("mousemove", this._onMouseMove);
  34857. element.removeEventListener("MSPointerDown", this._onGestureStart);
  34858. element.removeEventListener("MSGestureChange", this._onGesture);
  34859. this._isPanClick = false;
  34860. this.pinchInwards = true;
  34861. this._onMouseMove = null;
  34862. this._onGestureStart = null;
  34863. this._onGesture = null;
  34864. this._MSGestureHandler = null;
  34865. this._onLostFocus = null;
  34866. this._onContextMenu = null;
  34867. }
  34868. };
  34869. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  34870. return "ArcRotateCameraPointersInput";
  34871. };
  34872. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  34873. return "pointers";
  34874. };
  34875. __decorate([
  34876. BABYLON.serialize()
  34877. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  34878. __decorate([
  34879. BABYLON.serialize()
  34880. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  34881. __decorate([
  34882. BABYLON.serialize()
  34883. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  34884. __decorate([
  34885. BABYLON.serialize()
  34886. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  34887. __decorate([
  34888. BABYLON.serialize()
  34889. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  34890. return ArcRotateCameraPointersInput;
  34891. }());
  34892. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  34893. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  34894. })(BABYLON || (BABYLON = {}));
  34895. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  34896. /// <reference path="babylon.targetCamera.ts" />
  34897. /// <reference path="..\Tools\babylon.tools.ts" />
  34898. var BABYLON;
  34899. (function (BABYLON) {
  34900. var ArcRotateCamera = (function (_super) {
  34901. __extends(ArcRotateCamera, _super);
  34902. function ArcRotateCamera(name, alpha, beta, radius, target, scene) {
  34903. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  34904. _this.inertialAlphaOffset = 0;
  34905. _this.inertialBetaOffset = 0;
  34906. _this.inertialRadiusOffset = 0;
  34907. _this.lowerAlphaLimit = null;
  34908. _this.upperAlphaLimit = null;
  34909. _this.lowerBetaLimit = 0.01;
  34910. _this.upperBetaLimit = Math.PI;
  34911. _this.lowerRadiusLimit = null;
  34912. _this.upperRadiusLimit = null;
  34913. _this.inertialPanningX = 0;
  34914. _this.inertialPanningY = 0;
  34915. _this.panningInertia = 0.9;
  34916. //-- end properties for backward compatibility for inputs
  34917. _this.zoomOnFactor = 1;
  34918. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  34919. _this.allowUpsideDown = true;
  34920. _this._viewMatrix = new BABYLON.Matrix();
  34921. // Panning
  34922. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  34923. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  34924. _this.checkCollisions = false;
  34925. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  34926. _this._previousPosition = BABYLON.Vector3.Zero();
  34927. _this._collisionVelocity = BABYLON.Vector3.Zero();
  34928. _this._newPosition = BABYLON.Vector3.Zero();
  34929. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  34930. if (collidedMesh === void 0) { collidedMesh = null; }
  34931. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  34932. newPosition.multiplyInPlace(_this._collider.radius);
  34933. }
  34934. if (!collidedMesh) {
  34935. _this._previousPosition.copyFrom(_this.position);
  34936. }
  34937. else {
  34938. _this.setPosition(newPosition);
  34939. if (_this.onCollide) {
  34940. _this.onCollide(collidedMesh);
  34941. }
  34942. }
  34943. // Recompute because of constraints
  34944. var cosa = Math.cos(_this.alpha);
  34945. var sina = Math.sin(_this.alpha);
  34946. var cosb = Math.cos(_this.beta);
  34947. var sinb = Math.sin(_this.beta);
  34948. if (sinb === 0) {
  34949. sinb = 0.0001;
  34950. }
  34951. var target = _this._getTargetPosition();
  34952. target.addToRef(new BABYLON.Vector3(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb), _this._newPosition);
  34953. _this.position.copyFrom(_this._newPosition);
  34954. var up = _this.upVector;
  34955. if (_this.allowUpsideDown && _this.beta < 0) {
  34956. up = up.clone();
  34957. up = up.negate();
  34958. }
  34959. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  34960. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  34961. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  34962. _this._collisionTriggered = false;
  34963. };
  34964. _this._target = BABYLON.Vector3.Zero();
  34965. if (target) {
  34966. _this.setTarget(target);
  34967. }
  34968. _this.alpha = alpha;
  34969. _this.beta = beta;
  34970. _this.radius = radius;
  34971. _this.getViewMatrix();
  34972. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  34973. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  34974. return _this;
  34975. }
  34976. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  34977. get: function () {
  34978. return this._target;
  34979. },
  34980. set: function (value) {
  34981. this.setTarget(value);
  34982. },
  34983. enumerable: true,
  34984. configurable: true
  34985. });
  34986. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  34987. //-- begin properties for backward compatibility for inputs
  34988. get: function () {
  34989. var pointers = this.inputs.attached["pointers"];
  34990. if (pointers)
  34991. return pointers.angularSensibilityX;
  34992. },
  34993. set: function (value) {
  34994. var pointers = this.inputs.attached["pointers"];
  34995. if (pointers) {
  34996. pointers.angularSensibilityX = value;
  34997. }
  34998. },
  34999. enumerable: true,
  35000. configurable: true
  35001. });
  35002. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  35003. get: function () {
  35004. var pointers = this.inputs.attached["pointers"];
  35005. if (pointers)
  35006. return pointers.angularSensibilityY;
  35007. },
  35008. set: function (value) {
  35009. var pointers = this.inputs.attached["pointers"];
  35010. if (pointers) {
  35011. pointers.angularSensibilityY = value;
  35012. }
  35013. },
  35014. enumerable: true,
  35015. configurable: true
  35016. });
  35017. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  35018. get: function () {
  35019. var pointers = this.inputs.attached["pointers"];
  35020. if (pointers)
  35021. return pointers.pinchPrecision;
  35022. },
  35023. set: function (value) {
  35024. var pointers = this.inputs.attached["pointers"];
  35025. if (pointers) {
  35026. pointers.pinchPrecision = value;
  35027. }
  35028. },
  35029. enumerable: true,
  35030. configurable: true
  35031. });
  35032. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  35033. get: function () {
  35034. var pointers = this.inputs.attached["pointers"];
  35035. if (pointers)
  35036. return pointers.panningSensibility;
  35037. },
  35038. set: function (value) {
  35039. var pointers = this.inputs.attached["pointers"];
  35040. if (pointers) {
  35041. pointers.panningSensibility = value;
  35042. }
  35043. },
  35044. enumerable: true,
  35045. configurable: true
  35046. });
  35047. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  35048. get: function () {
  35049. var keyboard = this.inputs.attached["keyboard"];
  35050. if (keyboard)
  35051. return keyboard.keysUp;
  35052. },
  35053. set: function (value) {
  35054. var keyboard = this.inputs.attached["keyboard"];
  35055. if (keyboard)
  35056. keyboard.keysUp = value;
  35057. },
  35058. enumerable: true,
  35059. configurable: true
  35060. });
  35061. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  35062. get: function () {
  35063. var keyboard = this.inputs.attached["keyboard"];
  35064. if (keyboard)
  35065. return keyboard.keysDown;
  35066. },
  35067. set: function (value) {
  35068. var keyboard = this.inputs.attached["keyboard"];
  35069. if (keyboard)
  35070. keyboard.keysDown = value;
  35071. },
  35072. enumerable: true,
  35073. configurable: true
  35074. });
  35075. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  35076. get: function () {
  35077. var keyboard = this.inputs.attached["keyboard"];
  35078. if (keyboard)
  35079. return keyboard.keysLeft;
  35080. },
  35081. set: function (value) {
  35082. var keyboard = this.inputs.attached["keyboard"];
  35083. if (keyboard)
  35084. keyboard.keysLeft = value;
  35085. },
  35086. enumerable: true,
  35087. configurable: true
  35088. });
  35089. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  35090. get: function () {
  35091. var keyboard = this.inputs.attached["keyboard"];
  35092. if (keyboard)
  35093. return keyboard.keysRight;
  35094. },
  35095. set: function (value) {
  35096. var keyboard = this.inputs.attached["keyboard"];
  35097. if (keyboard)
  35098. keyboard.keysRight = value;
  35099. },
  35100. enumerable: true,
  35101. configurable: true
  35102. });
  35103. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  35104. get: function () {
  35105. var mousewheel = this.inputs.attached["mousewheel"];
  35106. if (mousewheel)
  35107. return mousewheel.wheelPrecision;
  35108. },
  35109. set: function (value) {
  35110. var mousewheel = this.inputs.attached["mousewheel"];
  35111. if (mousewheel)
  35112. mousewheel.wheelPrecision = value;
  35113. },
  35114. enumerable: true,
  35115. configurable: true
  35116. });
  35117. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  35118. get: function () {
  35119. return this._bouncingBehavior;
  35120. },
  35121. enumerable: true,
  35122. configurable: true
  35123. });
  35124. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  35125. get: function () {
  35126. return this._bouncingBehavior != null;
  35127. },
  35128. set: function (value) {
  35129. if (value === this.useBouncingBehavior) {
  35130. return;
  35131. }
  35132. if (value) {
  35133. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  35134. this.addBehavior(this._bouncingBehavior);
  35135. }
  35136. else {
  35137. this.removeBehavior(this._bouncingBehavior);
  35138. this._bouncingBehavior = null;
  35139. }
  35140. },
  35141. enumerable: true,
  35142. configurable: true
  35143. });
  35144. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  35145. get: function () {
  35146. return this._framingBehavior;
  35147. },
  35148. enumerable: true,
  35149. configurable: true
  35150. });
  35151. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  35152. get: function () {
  35153. return this._framingBehavior != null;
  35154. },
  35155. set: function (value) {
  35156. if (value === this.useFramingBehavior) {
  35157. return;
  35158. }
  35159. if (value) {
  35160. this._framingBehavior = new BABYLON.FramingBehavior();
  35161. this.addBehavior(this._framingBehavior);
  35162. }
  35163. else {
  35164. this.removeBehavior(this._framingBehavior);
  35165. this._framingBehavior = null;
  35166. }
  35167. },
  35168. enumerable: true,
  35169. configurable: true
  35170. });
  35171. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  35172. get: function () {
  35173. return this._autoRotationBehavior;
  35174. },
  35175. enumerable: true,
  35176. configurable: true
  35177. });
  35178. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  35179. get: function () {
  35180. return this._autoRotationBehavior != null;
  35181. },
  35182. set: function (value) {
  35183. if (value === this.useAutoRotationBehavior) {
  35184. return;
  35185. }
  35186. if (value) {
  35187. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  35188. this.addBehavior(this._autoRotationBehavior);
  35189. }
  35190. else {
  35191. this.removeBehavior(this._autoRotationBehavior);
  35192. this._autoRotationBehavior = null;
  35193. }
  35194. },
  35195. enumerable: true,
  35196. configurable: true
  35197. });
  35198. // Cache
  35199. ArcRotateCamera.prototype._initCache = function () {
  35200. _super.prototype._initCache.call(this);
  35201. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  35202. this._cache.alpha = undefined;
  35203. this._cache.beta = undefined;
  35204. this._cache.radius = undefined;
  35205. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  35206. };
  35207. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  35208. if (!ignoreParentClass) {
  35209. _super.prototype._updateCache.call(this);
  35210. }
  35211. this._cache._target.copyFrom(this._getTargetPosition());
  35212. this._cache.alpha = this.alpha;
  35213. this._cache.beta = this.beta;
  35214. this._cache.radius = this.radius;
  35215. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  35216. };
  35217. ArcRotateCamera.prototype._getTargetPosition = function () {
  35218. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  35219. var pos = this._targetHost.getAbsolutePosition();
  35220. if (this._targetBoundingCenter) {
  35221. pos.addToRef(this._targetBoundingCenter, this._target);
  35222. }
  35223. else {
  35224. this._target.copyFrom(pos);
  35225. }
  35226. }
  35227. var lockedTargetPosition = this._getLockedTargetPosition();
  35228. if (lockedTargetPosition) {
  35229. return lockedTargetPosition;
  35230. }
  35231. return this._target;
  35232. };
  35233. // Synchronized
  35234. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  35235. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  35236. return false;
  35237. return this._cache._target.equals(this._getTargetPosition())
  35238. && this._cache.alpha === this.alpha
  35239. && this._cache.beta === this.beta
  35240. && this._cache.radius === this.radius
  35241. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  35242. };
  35243. // Methods
  35244. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  35245. var _this = this;
  35246. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  35247. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  35248. this._useCtrlForPanning = useCtrlForPanning;
  35249. this._panningMouseButton = panningMouseButton;
  35250. this.inputs.attachElement(element, noPreventDefault);
  35251. this._reset = function () {
  35252. _this.inertialAlphaOffset = 0;
  35253. _this.inertialBetaOffset = 0;
  35254. _this.inertialRadiusOffset = 0;
  35255. };
  35256. };
  35257. ArcRotateCamera.prototype.detachControl = function (element) {
  35258. this.inputs.detachElement(element);
  35259. if (this._reset) {
  35260. this._reset();
  35261. }
  35262. };
  35263. ArcRotateCamera.prototype._checkInputs = function () {
  35264. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  35265. if (this._collisionTriggered) {
  35266. return;
  35267. }
  35268. this.inputs.checkInputs();
  35269. // Inertia
  35270. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  35271. if (this.getScene().useRightHandedSystem) {
  35272. this.alpha -= this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35273. }
  35274. else {
  35275. this.alpha += this.beta <= 0 ? -this.inertialAlphaOffset : this.inertialAlphaOffset;
  35276. }
  35277. this.beta += this.inertialBetaOffset;
  35278. this.radius -= this.inertialRadiusOffset;
  35279. this.inertialAlphaOffset *= this.inertia;
  35280. this.inertialBetaOffset *= this.inertia;
  35281. this.inertialRadiusOffset *= this.inertia;
  35282. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  35283. this.inertialAlphaOffset = 0;
  35284. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  35285. this.inertialBetaOffset = 0;
  35286. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  35287. this.inertialRadiusOffset = 0;
  35288. }
  35289. // Panning inertia
  35290. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  35291. if (!this._localDirection) {
  35292. this._localDirection = BABYLON.Vector3.Zero();
  35293. this._transformedDirection = BABYLON.Vector3.Zero();
  35294. }
  35295. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  35296. this._localDirection.multiplyInPlace(this.panningAxis);
  35297. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  35298. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  35299. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  35300. if (!this.panningAxis.y) {
  35301. this._transformedDirection.y = 0;
  35302. }
  35303. if (!this._targetHost) {
  35304. this._target.addInPlace(this._transformedDirection);
  35305. }
  35306. this.inertialPanningX *= this.panningInertia;
  35307. this.inertialPanningY *= this.panningInertia;
  35308. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  35309. this.inertialPanningX = 0;
  35310. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  35311. this.inertialPanningY = 0;
  35312. }
  35313. // Limits
  35314. this._checkLimits();
  35315. _super.prototype._checkInputs.call(this);
  35316. };
  35317. ArcRotateCamera.prototype._checkLimits = function () {
  35318. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  35319. if (this.allowUpsideDown && this.beta > Math.PI) {
  35320. this.beta = this.beta - (2 * Math.PI);
  35321. }
  35322. }
  35323. else {
  35324. if (this.beta < this.lowerBetaLimit) {
  35325. this.beta = this.lowerBetaLimit;
  35326. }
  35327. }
  35328. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  35329. if (this.allowUpsideDown && this.beta < -Math.PI) {
  35330. this.beta = this.beta + (2 * Math.PI);
  35331. }
  35332. }
  35333. else {
  35334. if (this.beta > this.upperBetaLimit) {
  35335. this.beta = this.upperBetaLimit;
  35336. }
  35337. }
  35338. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  35339. this.alpha = this.lowerAlphaLimit;
  35340. }
  35341. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  35342. this.alpha = this.upperAlphaLimit;
  35343. }
  35344. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  35345. this.radius = this.lowerRadiusLimit;
  35346. }
  35347. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  35348. this.radius = this.upperRadiusLimit;
  35349. }
  35350. };
  35351. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  35352. var radiusv3 = this.position.subtract(this._getTargetPosition());
  35353. this.radius = radiusv3.length();
  35354. if (this.radius === 0) {
  35355. this.radius = 0.0001; // Just to avoid division by zero
  35356. }
  35357. // Alpha
  35358. this.alpha = Math.acos(radiusv3.x / Math.sqrt(Math.pow(radiusv3.x, 2) + Math.pow(radiusv3.z, 2)));
  35359. if (radiusv3.z < 0) {
  35360. this.alpha = 2 * Math.PI - this.alpha;
  35361. }
  35362. // Beta
  35363. this.beta = Math.acos(radiusv3.y / this.radius);
  35364. this._checkLimits();
  35365. };
  35366. ArcRotateCamera.prototype.setPosition = function (position) {
  35367. if (this.position.equals(position)) {
  35368. return;
  35369. }
  35370. this.position.copyFrom(position);
  35371. this.rebuildAnglesAndRadius();
  35372. };
  35373. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  35374. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  35375. if (allowSamePosition === void 0) { allowSamePosition = false; }
  35376. if (target.getBoundingInfo) {
  35377. if (toBoundingCenter) {
  35378. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  35379. }
  35380. else {
  35381. this._targetBoundingCenter = null;
  35382. }
  35383. this._targetHost = target;
  35384. this._target = this._getTargetPosition();
  35385. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  35386. }
  35387. else {
  35388. var newTarget = target;
  35389. var currentTarget = this._getTargetPosition();
  35390. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  35391. return;
  35392. }
  35393. this._targetHost = null;
  35394. this._target = newTarget;
  35395. this._targetBoundingCenter = null;
  35396. this.onMeshTargetChangedObservable.notifyObservers(null);
  35397. }
  35398. this.rebuildAnglesAndRadius();
  35399. };
  35400. ArcRotateCamera.prototype._getViewMatrix = function () {
  35401. // Compute
  35402. var cosa = Math.cos(this.alpha);
  35403. var sina = Math.sin(this.alpha);
  35404. var cosb = Math.cos(this.beta);
  35405. var sinb = Math.sin(this.beta);
  35406. if (sinb === 0) {
  35407. sinb = 0.0001;
  35408. }
  35409. var target = this._getTargetPosition();
  35410. target.addToRef(new BABYLON.Vector3(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb), this._newPosition);
  35411. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  35412. if (!this._collider) {
  35413. this._collider = new BABYLON.Collider();
  35414. }
  35415. this._collider.radius = this.collisionRadius;
  35416. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  35417. this._collisionTriggered = true;
  35418. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  35419. }
  35420. else {
  35421. this.position.copyFrom(this._newPosition);
  35422. var up = this.upVector;
  35423. if (this.allowUpsideDown && sinb < 0) {
  35424. up = up.clone();
  35425. up = up.negate();
  35426. }
  35427. if (this.getScene().useRightHandedSystem) {
  35428. BABYLON.Matrix.LookAtRHToRef(this.position, target, up, this._viewMatrix);
  35429. }
  35430. else {
  35431. BABYLON.Matrix.LookAtLHToRef(this.position, target, up, this._viewMatrix);
  35432. }
  35433. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  35434. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  35435. }
  35436. this._currentTarget = target;
  35437. return this._viewMatrix;
  35438. };
  35439. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  35440. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35441. meshes = meshes || this.getScene().meshes;
  35442. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  35443. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  35444. this.radius = distance * this.zoomOnFactor;
  35445. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  35446. };
  35447. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  35448. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  35449. var meshesOrMinMaxVector;
  35450. var distance;
  35451. if (meshesOrMinMaxVectorAndDistance.min === undefined) {
  35452. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  35453. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshesOrMinMaxVector);
  35454. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  35455. }
  35456. else {
  35457. meshesOrMinMaxVector = meshesOrMinMaxVectorAndDistance;
  35458. distance = meshesOrMinMaxVectorAndDistance.distance;
  35459. }
  35460. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  35461. if (!doNotUpdateMaxZ) {
  35462. this.maxZ = distance * 2;
  35463. }
  35464. };
  35465. /**
  35466. * @override
  35467. * Override Camera.createRigCamera
  35468. */
  35469. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  35470. var alphaShift;
  35471. switch (this.cameraRigMode) {
  35472. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35473. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35474. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35475. case BABYLON.Camera.RIG_MODE_VR:
  35476. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  35477. break;
  35478. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35479. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  35480. break;
  35481. }
  35482. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  35483. rigCam._cameraRigParams = {};
  35484. return rigCam;
  35485. };
  35486. /**
  35487. * @override
  35488. * Override Camera._updateRigCameras
  35489. */
  35490. ArcRotateCamera.prototype._updateRigCameras = function () {
  35491. var camLeft = this._rigCameras[0];
  35492. var camRight = this._rigCameras[1];
  35493. camLeft.beta = camRight.beta = this.beta;
  35494. camLeft.radius = camRight.radius = this.radius;
  35495. switch (this.cameraRigMode) {
  35496. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  35497. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  35498. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  35499. case BABYLON.Camera.RIG_MODE_VR:
  35500. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35501. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35502. break;
  35503. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  35504. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  35505. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  35506. break;
  35507. }
  35508. _super.prototype._updateRigCameras.call(this);
  35509. };
  35510. ArcRotateCamera.prototype.dispose = function () {
  35511. this.inputs.clear();
  35512. _super.prototype.dispose.call(this);
  35513. };
  35514. ArcRotateCamera.prototype.getClassName = function () {
  35515. return "ArcRotateCamera";
  35516. };
  35517. __decorate([
  35518. BABYLON.serialize()
  35519. ], ArcRotateCamera.prototype, "alpha", void 0);
  35520. __decorate([
  35521. BABYLON.serialize()
  35522. ], ArcRotateCamera.prototype, "beta", void 0);
  35523. __decorate([
  35524. BABYLON.serialize()
  35525. ], ArcRotateCamera.prototype, "radius", void 0);
  35526. __decorate([
  35527. BABYLON.serializeAsVector3("target")
  35528. ], ArcRotateCamera.prototype, "_target", void 0);
  35529. __decorate([
  35530. BABYLON.serialize()
  35531. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  35532. __decorate([
  35533. BABYLON.serialize()
  35534. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  35535. __decorate([
  35536. BABYLON.serialize()
  35537. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  35538. __decorate([
  35539. BABYLON.serialize()
  35540. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  35541. __decorate([
  35542. BABYLON.serialize()
  35543. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  35544. __decorate([
  35545. BABYLON.serialize()
  35546. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  35547. __decorate([
  35548. BABYLON.serialize()
  35549. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  35550. __decorate([
  35551. BABYLON.serialize()
  35552. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  35553. __decorate([
  35554. BABYLON.serialize()
  35555. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  35556. __decorate([
  35557. BABYLON.serialize()
  35558. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  35559. __decorate([
  35560. BABYLON.serialize()
  35561. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  35562. __decorate([
  35563. BABYLON.serialize()
  35564. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  35565. __decorate([
  35566. BABYLON.serialize()
  35567. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  35568. __decorate([
  35569. BABYLON.serialize()
  35570. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  35571. return ArcRotateCamera;
  35572. }(BABYLON.TargetCamera));
  35573. BABYLON.ArcRotateCamera = ArcRotateCamera;
  35574. })(BABYLON || (BABYLON = {}));
  35575. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  35576. /// <reference path="..\Cameras\babylon.cameraInputsManager.ts" />
  35577. var BABYLON;
  35578. (function (BABYLON) {
  35579. var ArcRotateCameraInputsManager = (function (_super) {
  35580. __extends(ArcRotateCameraInputsManager, _super);
  35581. function ArcRotateCameraInputsManager(camera) {
  35582. return _super.call(this, camera) || this;
  35583. }
  35584. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  35585. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  35586. return this;
  35587. };
  35588. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  35589. this.add(new BABYLON.ArcRotateCameraPointersInput());
  35590. return this;
  35591. };
  35592. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  35593. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  35594. return this;
  35595. };
  35596. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  35597. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  35598. return this;
  35599. };
  35600. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  35601. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  35602. return this;
  35603. };
  35604. return ArcRotateCameraInputsManager;
  35605. }(BABYLON.CameraInputsManager));
  35606. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  35607. })(BABYLON || (BABYLON = {}));
  35608. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  35609. var BABYLON;
  35610. (function (BABYLON) {
  35611. var HemisphericLight = (function (_super) {
  35612. __extends(HemisphericLight, _super);
  35613. /**
  35614. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  35615. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  35616. * The HemisphericLight can't cast shadows.
  35617. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35618. */
  35619. function HemisphericLight(name, direction, scene) {
  35620. var _this = _super.call(this, name, scene) || this;
  35621. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  35622. _this.direction = direction || BABYLON.Vector3.Up();
  35623. return _this;
  35624. }
  35625. HemisphericLight.prototype._buildUniformLayout = function () {
  35626. this._uniformBuffer.addUniform("vLightData", 4);
  35627. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35628. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35629. this._uniformBuffer.addUniform("vLightGround", 3);
  35630. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35631. this._uniformBuffer.addUniform("depthValues", 2);
  35632. this._uniformBuffer.create();
  35633. };
  35634. /**
  35635. * Returns the string "HemisphericLight".
  35636. */
  35637. HemisphericLight.prototype.getClassName = function () {
  35638. return "HemisphericLight";
  35639. };
  35640. /**
  35641. * Sets the HemisphericLight direction towards the passed target (Vector3).
  35642. * Returns the updated direction.
  35643. */
  35644. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  35645. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  35646. return this.direction;
  35647. };
  35648. HemisphericLight.prototype.getShadowGenerator = function () {
  35649. return null;
  35650. };
  35651. /**
  35652. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  35653. * Returns the HemisphericLight.
  35654. */
  35655. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  35656. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  35657. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  35658. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  35659. return this;
  35660. };
  35661. HemisphericLight.prototype._getWorldMatrix = function () {
  35662. if (!this._worldMatrix) {
  35663. this._worldMatrix = BABYLON.Matrix.Identity();
  35664. }
  35665. return this._worldMatrix;
  35666. };
  35667. /**
  35668. * Returns the integer 3.
  35669. */
  35670. HemisphericLight.prototype.getTypeID = function () {
  35671. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  35672. };
  35673. __decorate([
  35674. BABYLON.serializeAsColor3()
  35675. ], HemisphericLight.prototype, "groundColor", void 0);
  35676. __decorate([
  35677. BABYLON.serializeAsVector3()
  35678. ], HemisphericLight.prototype, "direction", void 0);
  35679. return HemisphericLight;
  35680. }(BABYLON.Light));
  35681. BABYLON.HemisphericLight = HemisphericLight;
  35682. })(BABYLON || (BABYLON = {}));
  35683. //# sourceMappingURL=babylon.hemisphericLight.js.map
  35684. var BABYLON;
  35685. (function (BABYLON) {
  35686. var ShadowLight = (function (_super) {
  35687. __extends(ShadowLight, _super);
  35688. function ShadowLight() {
  35689. var _this = _super !== null && _super.apply(this, arguments) || this;
  35690. _this._needProjectionMatrixCompute = true;
  35691. return _this;
  35692. }
  35693. Object.defineProperty(ShadowLight.prototype, "direction", {
  35694. get: function () {
  35695. return this._direction;
  35696. },
  35697. set: function (value) {
  35698. this._direction = value;
  35699. },
  35700. enumerable: true,
  35701. configurable: true
  35702. });
  35703. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  35704. get: function () {
  35705. return this._shadowMinZ;
  35706. },
  35707. set: function (value) {
  35708. this._shadowMinZ = value;
  35709. this.forceProjectionMatrixCompute();
  35710. },
  35711. enumerable: true,
  35712. configurable: true
  35713. });
  35714. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  35715. get: function () {
  35716. return this._shadowMaxZ;
  35717. },
  35718. set: function (value) {
  35719. this._shadowMaxZ = value;
  35720. this.forceProjectionMatrixCompute();
  35721. },
  35722. enumerable: true,
  35723. configurable: true
  35724. });
  35725. /**
  35726. * Computes the light transformed position/direction in case the light is parented. Returns true if parented, else false.
  35727. */
  35728. ShadowLight.prototype.computeTransformedInformation = function () {
  35729. if (this.parent && this.parent.getWorldMatrix) {
  35730. if (!this.transformedPosition) {
  35731. this.transformedPosition = BABYLON.Vector3.Zero();
  35732. }
  35733. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  35734. // In case the direction is present.
  35735. if (this.direction) {
  35736. if (!this.transformedDirection) {
  35737. this.transformedDirection = BABYLON.Vector3.Zero();
  35738. }
  35739. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  35740. }
  35741. return true;
  35742. }
  35743. return false;
  35744. };
  35745. /**
  35746. * Return the depth scale used for the shadow map.
  35747. */
  35748. ShadowLight.prototype.getDepthScale = function () {
  35749. return 50.0;
  35750. };
  35751. /**
  35752. * Returns the light direction (Vector3) for any passed face index.
  35753. */
  35754. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  35755. return this.transformedDirection ? this.transformedDirection : this.direction;
  35756. };
  35757. /**
  35758. * Returns the DirectionalLight absolute position in the World.
  35759. */
  35760. ShadowLight.prototype.getAbsolutePosition = function () {
  35761. return this.transformedPosition ? this.transformedPosition : this.position;
  35762. };
  35763. /**
  35764. * Sets the DirectionalLight direction toward the passed target (Vector3).
  35765. * Returns the updated DirectionalLight direction (Vector3).
  35766. */
  35767. ShadowLight.prototype.setDirectionToTarget = function (target) {
  35768. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  35769. return this.direction;
  35770. };
  35771. /**
  35772. * Returns the light rotation (Vector3).
  35773. */
  35774. ShadowLight.prototype.getRotation = function () {
  35775. this.direction.normalize();
  35776. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  35777. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  35778. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  35779. };
  35780. /**
  35781. * Boolean : false by default.
  35782. */
  35783. ShadowLight.prototype.needCube = function () {
  35784. return false;
  35785. };
  35786. /**
  35787. * Specifies wether or not the projection matrix should be recomputed this frame.
  35788. */
  35789. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  35790. return this._needProjectionMatrixCompute;
  35791. };
  35792. /**
  35793. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  35794. */
  35795. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  35796. this._needProjectionMatrixCompute = true;
  35797. };
  35798. /**
  35799. * Get the world matrix of the sahdow lights.
  35800. */
  35801. ShadowLight.prototype._getWorldMatrix = function () {
  35802. if (!this._worldMatrix) {
  35803. this._worldMatrix = BABYLON.Matrix.Identity();
  35804. }
  35805. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  35806. return this._worldMatrix;
  35807. };
  35808. /**
  35809. * Gets the minZ used for shadow according to both the scene and the light.
  35810. * @param activeCamera
  35811. */
  35812. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  35813. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  35814. };
  35815. /**
  35816. * Gets the maxZ used for shadow according to both the scene and the light.
  35817. * @param activeCamera
  35818. */
  35819. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  35820. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  35821. };
  35822. /**
  35823. * Sets the projection matrix according to the type of light and custom projection matrix definition.
  35824. * Returns the light.
  35825. */
  35826. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35827. if (this.customProjectionMatrixBuilder) {
  35828. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  35829. }
  35830. else {
  35831. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  35832. }
  35833. return this;
  35834. };
  35835. __decorate([
  35836. BABYLON.serializeAsVector3()
  35837. ], ShadowLight.prototype, "position", void 0);
  35838. __decorate([
  35839. BABYLON.serializeAsVector3()
  35840. ], ShadowLight.prototype, "direction", null);
  35841. __decorate([
  35842. BABYLON.serialize()
  35843. ], ShadowLight.prototype, "shadowMinZ", null);
  35844. __decorate([
  35845. BABYLON.serialize()
  35846. ], ShadowLight.prototype, "shadowMaxZ", null);
  35847. return ShadowLight;
  35848. }(BABYLON.Light));
  35849. BABYLON.ShadowLight = ShadowLight;
  35850. })(BABYLON || (BABYLON = {}));
  35851. //# sourceMappingURL=babylon.shadowLight.js.map
  35852. var BABYLON;
  35853. (function (BABYLON) {
  35854. var PointLight = (function (_super) {
  35855. __extends(PointLight, _super);
  35856. /**
  35857. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  35858. * A PointLight emits the light in every direction.
  35859. * It can cast shadows.
  35860. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  35861. * ```javascript
  35862. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  35863. * ```
  35864. * Documentation : http://doc.babylonjs.com/tutorials/lights
  35865. */
  35866. function PointLight(name, position, scene) {
  35867. var _this = _super.call(this, name, scene) || this;
  35868. _this._shadowAngle = Math.PI / 2;
  35869. _this.position = position;
  35870. return _this;
  35871. }
  35872. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  35873. /**
  35874. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35875. * This specifies what angle the shadow will use to be created.
  35876. *
  35877. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35878. */
  35879. get: function () {
  35880. return this._shadowAngle;
  35881. },
  35882. /**
  35883. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35884. * This specifies what angle the shadow will use to be created.
  35885. *
  35886. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  35887. */
  35888. set: function (value) {
  35889. this._shadowAngle = value;
  35890. this.forceProjectionMatrixCompute();
  35891. },
  35892. enumerable: true,
  35893. configurable: true
  35894. });
  35895. Object.defineProperty(PointLight.prototype, "direction", {
  35896. get: function () {
  35897. return this._direction;
  35898. },
  35899. /**
  35900. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  35901. */
  35902. set: function (value) {
  35903. var previousNeedCube = this.needCube();
  35904. this._direction = value;
  35905. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  35906. this._shadowGenerator.recreateShadowMap();
  35907. }
  35908. },
  35909. enumerable: true,
  35910. configurable: true
  35911. });
  35912. /**
  35913. * Returns the string "PointLight"
  35914. */
  35915. PointLight.prototype.getClassName = function () {
  35916. return "PointLight";
  35917. };
  35918. /**
  35919. * Returns the integer 0.
  35920. */
  35921. PointLight.prototype.getTypeID = function () {
  35922. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  35923. };
  35924. /**
  35925. * Specifies wether or not the shadowmap should be a cube texture.
  35926. */
  35927. PointLight.prototype.needCube = function () {
  35928. return !this.direction;
  35929. };
  35930. /**
  35931. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  35932. */
  35933. PointLight.prototype.getShadowDirection = function (faceIndex) {
  35934. if (this.direction) {
  35935. return _super.prototype.getShadowDirection.call(this, faceIndex);
  35936. }
  35937. else {
  35938. switch (faceIndex) {
  35939. case 0:
  35940. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  35941. case 1:
  35942. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  35943. case 2:
  35944. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  35945. case 3:
  35946. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  35947. case 4:
  35948. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  35949. case 5:
  35950. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  35951. }
  35952. }
  35953. return BABYLON.Vector3.Zero();
  35954. };
  35955. /**
  35956. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  35957. * - fov = PI / 2
  35958. * - aspect ratio : 1.0
  35959. * - z-near and far equal to the active camera minZ and maxZ.
  35960. * Returns the PointLight.
  35961. */
  35962. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  35963. var activeCamera = this.getScene().activeCamera;
  35964. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  35965. };
  35966. PointLight.prototype._buildUniformLayout = function () {
  35967. this._uniformBuffer.addUniform("vLightData", 4);
  35968. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  35969. this._uniformBuffer.addUniform("vLightSpecular", 3);
  35970. this._uniformBuffer.addUniform("shadowsInfo", 3);
  35971. this._uniformBuffer.addUniform("depthValues", 2);
  35972. this._uniformBuffer.create();
  35973. };
  35974. /**
  35975. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  35976. * Returns the PointLight.
  35977. */
  35978. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  35979. if (this.computeTransformedInformation()) {
  35980. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  35981. return this;
  35982. }
  35983. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  35984. return this;
  35985. };
  35986. __decorate([
  35987. BABYLON.serialize()
  35988. ], PointLight.prototype, "shadowAngle", null);
  35989. return PointLight;
  35990. }(BABYLON.ShadowLight));
  35991. BABYLON.PointLight = PointLight;
  35992. })(BABYLON || (BABYLON = {}));
  35993. //# sourceMappingURL=babylon.pointLight.js.map
  35994. /// <reference path="babylon.light.ts" />
  35995. var BABYLON;
  35996. (function (BABYLON) {
  35997. var DirectionalLight = (function (_super) {
  35998. __extends(DirectionalLight, _super);
  35999. /**
  36000. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  36001. * The directional light is emitted from everywhere in the given direction.
  36002. * It can cast shawdows.
  36003. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36004. */
  36005. function DirectionalLight(name, direction, scene) {
  36006. var _this = _super.call(this, name, scene) || this;
  36007. _this._shadowFrustumSize = 0;
  36008. _this._shadowOrthoScale = 0.5;
  36009. _this.autoUpdateExtends = true;
  36010. // Cache
  36011. _this._orthoLeft = Number.MAX_VALUE;
  36012. _this._orthoRight = Number.MIN_VALUE;
  36013. _this._orthoTop = Number.MIN_VALUE;
  36014. _this._orthoBottom = Number.MAX_VALUE;
  36015. _this.position = direction.scale(-1.0);
  36016. _this.direction = direction;
  36017. return _this;
  36018. }
  36019. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  36020. /**
  36021. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  36022. */
  36023. get: function () {
  36024. return this._shadowFrustumSize;
  36025. },
  36026. /**
  36027. * Specifies a fix frustum size for the shadow generation.
  36028. */
  36029. set: function (value) {
  36030. this._shadowFrustumSize = value;
  36031. this.forceProjectionMatrixCompute();
  36032. },
  36033. enumerable: true,
  36034. configurable: true
  36035. });
  36036. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  36037. get: function () {
  36038. return this._shadowOrthoScale;
  36039. },
  36040. set: function (value) {
  36041. this._shadowOrthoScale = value;
  36042. this.forceProjectionMatrixCompute();
  36043. },
  36044. enumerable: true,
  36045. configurable: true
  36046. });
  36047. /**
  36048. * Returns the string "DirectionalLight".
  36049. */
  36050. DirectionalLight.prototype.getClassName = function () {
  36051. return "DirectionalLight";
  36052. };
  36053. /**
  36054. * Returns the integer 1.
  36055. */
  36056. DirectionalLight.prototype.getTypeID = function () {
  36057. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  36058. };
  36059. /**
  36060. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  36061. * Returns the DirectionalLight Shadow projection matrix.
  36062. */
  36063. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36064. if (this.shadowFrustumSize > 0) {
  36065. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  36066. }
  36067. else {
  36068. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  36069. }
  36070. };
  36071. /**
  36072. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  36073. * Returns the DirectionalLight Shadow projection matrix.
  36074. */
  36075. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  36076. var activeCamera = this.getScene().activeCamera;
  36077. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36078. };
  36079. /**
  36080. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  36081. * Returns the DirectionalLight Shadow projection matrix.
  36082. */
  36083. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36084. var activeCamera = this.getScene().activeCamera;
  36085. // Check extends
  36086. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  36087. var tempVector3 = BABYLON.Vector3.Zero();
  36088. this._orthoLeft = Number.MAX_VALUE;
  36089. this._orthoRight = Number.MIN_VALUE;
  36090. this._orthoTop = Number.MIN_VALUE;
  36091. this._orthoBottom = Number.MAX_VALUE;
  36092. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  36093. var mesh = renderList[meshIndex];
  36094. if (!mesh) {
  36095. continue;
  36096. }
  36097. var boundingInfo = mesh.getBoundingInfo();
  36098. if (!boundingInfo) {
  36099. continue;
  36100. }
  36101. var boundingBox = boundingInfo.boundingBox;
  36102. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  36103. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  36104. if (tempVector3.x < this._orthoLeft)
  36105. this._orthoLeft = tempVector3.x;
  36106. if (tempVector3.y < this._orthoBottom)
  36107. this._orthoBottom = tempVector3.y;
  36108. if (tempVector3.x > this._orthoRight)
  36109. this._orthoRight = tempVector3.x;
  36110. if (tempVector3.y > this._orthoTop)
  36111. this._orthoTop = tempVector3.y;
  36112. }
  36113. }
  36114. }
  36115. var xOffset = this._orthoRight - this._orthoLeft;
  36116. var yOffset = this._orthoTop - this._orthoBottom;
  36117. BABYLON.Matrix.OrthoOffCenterLHToRef(this._orthoLeft - xOffset * this.shadowOrthoScale, this._orthoRight + xOffset * this.shadowOrthoScale, this._orthoBottom - yOffset * this.shadowOrthoScale, this._orthoTop + yOffset * this.shadowOrthoScale, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  36118. };
  36119. DirectionalLight.prototype._buildUniformLayout = function () {
  36120. this._uniformBuffer.addUniform("vLightData", 4);
  36121. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36122. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36123. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36124. this._uniformBuffer.addUniform("depthValues", 2);
  36125. this._uniformBuffer.create();
  36126. };
  36127. /**
  36128. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  36129. * Returns the DirectionalLight.
  36130. */
  36131. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  36132. if (this.computeTransformedInformation()) {
  36133. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  36134. return this;
  36135. }
  36136. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  36137. return this;
  36138. };
  36139. /**
  36140. * Gets the minZ used for shadow according to both the scene and the light.
  36141. *
  36142. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36143. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36144. * @param activeCamera
  36145. */
  36146. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  36147. return 1;
  36148. };
  36149. /**
  36150. * Gets the maxZ used for shadow according to both the scene and the light.
  36151. *
  36152. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  36153. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  36154. * @param activeCamera
  36155. */
  36156. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  36157. return 1;
  36158. };
  36159. __decorate([
  36160. BABYLON.serialize()
  36161. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  36162. __decorate([
  36163. BABYLON.serialize()
  36164. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  36165. __decorate([
  36166. BABYLON.serialize()
  36167. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  36168. return DirectionalLight;
  36169. }(BABYLON.ShadowLight));
  36170. BABYLON.DirectionalLight = DirectionalLight;
  36171. })(BABYLON || (BABYLON = {}));
  36172. //# sourceMappingURL=babylon.directionalLight.js.map
  36173. var BABYLON;
  36174. (function (BABYLON) {
  36175. var SpotLight = (function (_super) {
  36176. __extends(SpotLight, _super);
  36177. /**
  36178. * Creates a SpotLight object in the scene with the passed parameters :
  36179. * - `position` (Vector3) is the initial SpotLight position,
  36180. * - `direction` (Vector3) is the initial SpotLight direction,
  36181. * - `angle` (float, in radians) is the spot light cone angle,
  36182. * - `exponent` (float) is the light decay speed with the distance from the emission spot.
  36183. * A spot light is a simply light oriented cone.
  36184. * It can cast shadows.
  36185. * Documentation : http://doc.babylonjs.com/tutorials/lights
  36186. */
  36187. function SpotLight(name, position, direction, angle, exponent, scene) {
  36188. var _this = _super.call(this, name, scene) || this;
  36189. _this.position = position;
  36190. _this.direction = direction;
  36191. _this.angle = angle;
  36192. _this.exponent = exponent;
  36193. return _this;
  36194. }
  36195. Object.defineProperty(SpotLight.prototype, "angle", {
  36196. get: function () {
  36197. return this._angle;
  36198. },
  36199. set: function (value) {
  36200. this._angle = value;
  36201. this.forceProjectionMatrixCompute();
  36202. },
  36203. enumerable: true,
  36204. configurable: true
  36205. });
  36206. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  36207. get: function () {
  36208. return this._shadowAngleScale;
  36209. },
  36210. /**
  36211. * Allows scaling the angle of the light for shadow generation only.
  36212. */
  36213. set: function (value) {
  36214. this._shadowAngleScale = value;
  36215. this.forceProjectionMatrixCompute();
  36216. },
  36217. enumerable: true,
  36218. configurable: true
  36219. });
  36220. /**
  36221. * Returns the string "SpotLight".
  36222. */
  36223. SpotLight.prototype.getClassName = function () {
  36224. return "SpotLight";
  36225. };
  36226. /**
  36227. * Returns the integer 2.
  36228. */
  36229. SpotLight.prototype.getTypeID = function () {
  36230. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  36231. };
  36232. /**
  36233. * Sets the passed matrix "matrix" as perspective projection matrix for the shadows and the passed view matrix with the fov equal to the SpotLight angle and and aspect ratio of 1.0.
  36234. * Returns the SpotLight.
  36235. */
  36236. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  36237. var activeCamera = this.getScene().activeCamera;
  36238. this._shadowAngleScale = this._shadowAngleScale || 1;
  36239. var angle = this._shadowAngleScale * this._angle;
  36240. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  36241. };
  36242. SpotLight.prototype._buildUniformLayout = function () {
  36243. this._uniformBuffer.addUniform("vLightData", 4);
  36244. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  36245. this._uniformBuffer.addUniform("vLightSpecular", 3);
  36246. this._uniformBuffer.addUniform("vLightDirection", 3);
  36247. this._uniformBuffer.addUniform("shadowsInfo", 3);
  36248. this._uniformBuffer.addUniform("depthValues", 2);
  36249. this._uniformBuffer.create();
  36250. };
  36251. /**
  36252. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  36253. * Return the SpotLight.
  36254. */
  36255. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  36256. var normalizeDirection;
  36257. if (this.computeTransformedInformation()) {
  36258. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  36259. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  36260. }
  36261. else {
  36262. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  36263. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  36264. }
  36265. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  36266. return this;
  36267. };
  36268. __decorate([
  36269. BABYLON.serialize()
  36270. ], SpotLight.prototype, "angle", null);
  36271. __decorate([
  36272. BABYLON.serialize()
  36273. /**
  36274. * Allows scaling the angle of the light for shadow generation only.
  36275. */
  36276. ], SpotLight.prototype, "shadowAngleScale", null);
  36277. __decorate([
  36278. BABYLON.serialize()
  36279. ], SpotLight.prototype, "exponent", void 0);
  36280. return SpotLight;
  36281. }(BABYLON.ShadowLight));
  36282. BABYLON.SpotLight = SpotLight;
  36283. })(BABYLON || (BABYLON = {}));
  36284. //# sourceMappingURL=babylon.spotLight.js.map
  36285. var BABYLON;
  36286. (function (BABYLON) {
  36287. var AnimationRange = (function () {
  36288. function AnimationRange(name, from, to) {
  36289. this.name = name;
  36290. this.from = from;
  36291. this.to = to;
  36292. }
  36293. AnimationRange.prototype.clone = function () {
  36294. return new AnimationRange(this.name, this.from, this.to);
  36295. };
  36296. return AnimationRange;
  36297. }());
  36298. BABYLON.AnimationRange = AnimationRange;
  36299. /**
  36300. * Composed of a frame, and an action function
  36301. */
  36302. var AnimationEvent = (function () {
  36303. function AnimationEvent(frame, action, onlyOnce) {
  36304. this.frame = frame;
  36305. this.action = action;
  36306. this.onlyOnce = onlyOnce;
  36307. this.isDone = false;
  36308. }
  36309. return AnimationEvent;
  36310. }());
  36311. BABYLON.AnimationEvent = AnimationEvent;
  36312. var PathCursor = (function () {
  36313. function PathCursor(path) {
  36314. this.path = path;
  36315. this._onchange = new Array();
  36316. this.value = 0;
  36317. this.animations = new Array();
  36318. }
  36319. PathCursor.prototype.getPoint = function () {
  36320. var point = this.path.getPointAtLengthPosition(this.value);
  36321. return new BABYLON.Vector3(point.x, 0, point.y);
  36322. };
  36323. PathCursor.prototype.moveAhead = function (step) {
  36324. if (step === void 0) { step = 0.002; }
  36325. this.move(step);
  36326. return this;
  36327. };
  36328. PathCursor.prototype.moveBack = function (step) {
  36329. if (step === void 0) { step = 0.002; }
  36330. this.move(-step);
  36331. return this;
  36332. };
  36333. PathCursor.prototype.move = function (step) {
  36334. if (Math.abs(step) > 1) {
  36335. throw "step size should be less than 1.";
  36336. }
  36337. this.value += step;
  36338. this.ensureLimits();
  36339. this.raiseOnChange();
  36340. return this;
  36341. };
  36342. PathCursor.prototype.ensureLimits = function () {
  36343. while (this.value > 1) {
  36344. this.value -= 1;
  36345. }
  36346. while (this.value < 0) {
  36347. this.value += 1;
  36348. }
  36349. return this;
  36350. };
  36351. // used by animation engine
  36352. PathCursor.prototype.markAsDirty = function (propertyName) {
  36353. this.ensureLimits();
  36354. this.raiseOnChange();
  36355. return this;
  36356. };
  36357. PathCursor.prototype.raiseOnChange = function () {
  36358. var _this = this;
  36359. this._onchange.forEach(function (f) { return f(_this); });
  36360. return this;
  36361. };
  36362. PathCursor.prototype.onchange = function (f) {
  36363. this._onchange.push(f);
  36364. return this;
  36365. };
  36366. return PathCursor;
  36367. }());
  36368. BABYLON.PathCursor = PathCursor;
  36369. var Animation = (function () {
  36370. function Animation(name, targetProperty, framePerSecond, dataType, loopMode, enableBlending) {
  36371. this.name = name;
  36372. this.targetProperty = targetProperty;
  36373. this.framePerSecond = framePerSecond;
  36374. this.dataType = dataType;
  36375. this.loopMode = loopMode;
  36376. this.enableBlending = enableBlending;
  36377. this._offsetsCache = {};
  36378. this._highLimitsCache = {};
  36379. this._stopped = false;
  36380. this._blendingFactor = 0;
  36381. // The set of event that will be linked to this animation
  36382. this._events = new Array();
  36383. this.allowMatricesInterpolation = false;
  36384. this.blendingSpeed = 0.01;
  36385. this._ranges = {};
  36386. this.targetPropertyPath = targetProperty.split(".");
  36387. this.dataType = dataType;
  36388. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  36389. }
  36390. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  36391. var dataType = undefined;
  36392. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  36393. dataType = Animation.ANIMATIONTYPE_FLOAT;
  36394. }
  36395. else if (from instanceof BABYLON.Quaternion) {
  36396. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  36397. }
  36398. else if (from instanceof BABYLON.Vector3) {
  36399. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  36400. }
  36401. else if (from instanceof BABYLON.Vector2) {
  36402. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  36403. }
  36404. else if (from instanceof BABYLON.Color3) {
  36405. dataType = Animation.ANIMATIONTYPE_COLOR3;
  36406. }
  36407. else if (from instanceof BABYLON.Size) {
  36408. dataType = Animation.ANIMATIONTYPE_SIZE;
  36409. }
  36410. if (dataType == undefined) {
  36411. return null;
  36412. }
  36413. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  36414. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  36415. animation.setKeys(keys);
  36416. if (easingFunction !== undefined) {
  36417. animation.setEasingFunction(easingFunction);
  36418. }
  36419. return animation;
  36420. };
  36421. /**
  36422. * Sets up an animation.
  36423. * @param property the property to animate
  36424. * @param animationType the animation type to apply
  36425. * @param easingFunction the easing function used in the animation
  36426. * @returns The created animation
  36427. */
  36428. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  36429. var animation = new BABYLON.Animation(property + "Animation", property, framePerSecond, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  36430. animation.setEasingFunction(easingFunction);
  36431. return animation;
  36432. };
  36433. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36434. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36435. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36436. };
  36437. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  36438. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  36439. node.animations.push(animation);
  36440. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  36441. };
  36442. /**
  36443. * Transition property of the Camera to the target Value.
  36444. * @param property The property to transition
  36445. * @param targetValue The target Value of the property
  36446. * @param host The object where the property to animate belongs
  36447. * @param scene Scene used to run the animation
  36448. * @param frameRate Framerate (in frame/s) to use
  36449. * @param transition The transition type we want to use
  36450. * @param duration The duration of the animation, in milliseconds
  36451. * @param onAnimationEnd Call back trigger at the end of the animation.
  36452. */
  36453. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  36454. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  36455. if (duration <= 0) {
  36456. host[property] = targetValue;
  36457. if (onAnimationEnd) {
  36458. onAnimationEnd();
  36459. }
  36460. return;
  36461. }
  36462. var endFrame = frameRate * (duration / 1000);
  36463. transition.setKeys([{
  36464. frame: 0,
  36465. value: host[property].clone ? host[property].clone() : host[property]
  36466. },
  36467. {
  36468. frame: endFrame,
  36469. value: targetValue
  36470. }]);
  36471. if (!host.animations) {
  36472. host.animations = [];
  36473. }
  36474. host.animations.push(transition);
  36475. var animation = scene.beginAnimation(host, 0, endFrame, false);
  36476. animation.onAnimationEnd = onAnimationEnd;
  36477. return animation;
  36478. };
  36479. // Methods
  36480. /**
  36481. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  36482. */
  36483. Animation.prototype.toString = function (fullDetails) {
  36484. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  36485. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  36486. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  36487. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  36488. if (fullDetails) {
  36489. ret += ", Ranges: {";
  36490. var first = true;
  36491. for (var name in this._ranges) {
  36492. if (first) {
  36493. ret += ", ";
  36494. first = false;
  36495. }
  36496. ret += name;
  36497. }
  36498. ret += "}";
  36499. }
  36500. return ret;
  36501. };
  36502. /**
  36503. * Add an event to this animation.
  36504. */
  36505. Animation.prototype.addEvent = function (event) {
  36506. this._events.push(event);
  36507. };
  36508. /**
  36509. * Remove all events found at the given frame
  36510. * @param frame
  36511. */
  36512. Animation.prototype.removeEvents = function (frame) {
  36513. for (var index = 0; index < this._events.length; index++) {
  36514. if (this._events[index].frame === frame) {
  36515. this._events.splice(index, 1);
  36516. index--;
  36517. }
  36518. }
  36519. };
  36520. Animation.prototype.createRange = function (name, from, to) {
  36521. // check name not already in use; could happen for bones after serialized
  36522. if (!this._ranges[name]) {
  36523. this._ranges[name] = new AnimationRange(name, from, to);
  36524. }
  36525. };
  36526. Animation.prototype.deleteRange = function (name, deleteFrames) {
  36527. if (deleteFrames === void 0) { deleteFrames = true; }
  36528. if (this._ranges[name]) {
  36529. if (deleteFrames) {
  36530. var from = this._ranges[name].from;
  36531. var to = this._ranges[name].to;
  36532. // this loop MUST go high to low for multiple splices to work
  36533. for (var key = this._keys.length - 1; key >= 0; key--) {
  36534. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  36535. this._keys.splice(key, 1);
  36536. }
  36537. }
  36538. }
  36539. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  36540. }
  36541. };
  36542. Animation.prototype.getRange = function (name) {
  36543. return this._ranges[name];
  36544. };
  36545. Animation.prototype.reset = function () {
  36546. this._offsetsCache = {};
  36547. this._highLimitsCache = {};
  36548. this.currentFrame = 0;
  36549. this._blendingFactor = 0;
  36550. this._originalBlendValue = null;
  36551. };
  36552. Animation.prototype.isStopped = function () {
  36553. return this._stopped;
  36554. };
  36555. Animation.prototype.getKeys = function () {
  36556. return this._keys;
  36557. };
  36558. Animation.prototype.getHighestFrame = function () {
  36559. var ret = 0;
  36560. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  36561. if (ret < this._keys[key].frame) {
  36562. ret = this._keys[key].frame;
  36563. }
  36564. }
  36565. return ret;
  36566. };
  36567. Animation.prototype.getEasingFunction = function () {
  36568. return this._easingFunction;
  36569. };
  36570. Animation.prototype.setEasingFunction = function (easingFunction) {
  36571. this._easingFunction = easingFunction;
  36572. };
  36573. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  36574. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  36575. };
  36576. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36577. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36578. };
  36579. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  36580. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  36581. };
  36582. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36583. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  36584. };
  36585. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  36586. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  36587. };
  36588. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36589. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36590. };
  36591. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  36592. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  36593. };
  36594. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  36595. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  36596. };
  36597. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  36598. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  36599. };
  36600. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  36601. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  36602. };
  36603. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient) {
  36604. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  36605. };
  36606. Animation.prototype.clone = function () {
  36607. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  36608. clone.enableBlending = this.enableBlending;
  36609. clone.blendingSpeed = this.blendingSpeed;
  36610. if (this._keys) {
  36611. clone.setKeys(this._keys);
  36612. }
  36613. if (this._ranges) {
  36614. clone._ranges = {};
  36615. for (var name in this._ranges) {
  36616. clone._ranges[name] = this._ranges[name].clone();
  36617. }
  36618. }
  36619. return clone;
  36620. };
  36621. Animation.prototype.setKeys = function (values) {
  36622. this._keys = values.slice(0);
  36623. this._offsetsCache = {};
  36624. this._highLimitsCache = {};
  36625. };
  36626. Animation.prototype._getKeyValue = function (value) {
  36627. if (typeof value === "function") {
  36628. return value();
  36629. }
  36630. return value;
  36631. };
  36632. Animation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  36633. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  36634. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  36635. }
  36636. this.currentFrame = currentFrame;
  36637. // Try to get a hash to find the right key
  36638. var startKeyIndex = 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));
  36639. if (this._keys[startKeyIndex].frame >= currentFrame) {
  36640. while (startKeyIndex - 1 >= 0 && this._keys[startKeyIndex].frame >= currentFrame) {
  36641. startKeyIndex--;
  36642. }
  36643. }
  36644. for (var key = startKeyIndex; key < this._keys.length; key++) {
  36645. var endKey = this._keys[key + 1];
  36646. if (endKey.frame >= currentFrame) {
  36647. var startKey = this._keys[key];
  36648. var startValue = this._getKeyValue(startKey.value);
  36649. var endValue = this._getKeyValue(endKey.value);
  36650. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  36651. var frameDelta = endKey.frame - startKey.frame;
  36652. // gradient : percent of currentFrame between the frame inf and the frame sup
  36653. var gradient = (currentFrame - startKey.frame) / frameDelta;
  36654. // check for easingFunction and correction of gradient
  36655. if (this._easingFunction != null) {
  36656. gradient = this._easingFunction.ease(gradient);
  36657. }
  36658. switch (this.dataType) {
  36659. // Float
  36660. case Animation.ANIMATIONTYPE_FLOAT:
  36661. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  36662. switch (loopMode) {
  36663. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36664. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36665. return floatValue;
  36666. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36667. return offsetValue * repeatCount + floatValue;
  36668. }
  36669. break;
  36670. // Quaternion
  36671. case Animation.ANIMATIONTYPE_QUATERNION:
  36672. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  36673. switch (loopMode) {
  36674. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36675. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36676. return quatValue;
  36677. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36678. return quatValue.add(offsetValue.scale(repeatCount));
  36679. }
  36680. return quatValue;
  36681. // Vector3
  36682. case Animation.ANIMATIONTYPE_VECTOR3:
  36683. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  36684. switch (loopMode) {
  36685. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36686. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36687. return vec3Value;
  36688. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36689. return vec3Value.add(offsetValue.scale(repeatCount));
  36690. }
  36691. // Vector2
  36692. case Animation.ANIMATIONTYPE_VECTOR2:
  36693. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  36694. switch (loopMode) {
  36695. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36696. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36697. return vec2Value;
  36698. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36699. return vec2Value.add(offsetValue.scale(repeatCount));
  36700. }
  36701. // Size
  36702. case Animation.ANIMATIONTYPE_SIZE:
  36703. switch (loopMode) {
  36704. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36705. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36706. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  36707. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36708. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36709. }
  36710. // Color3
  36711. case Animation.ANIMATIONTYPE_COLOR3:
  36712. switch (loopMode) {
  36713. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36714. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36715. return this.color3InterpolateFunction(startValue, endValue, gradient);
  36716. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36717. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  36718. }
  36719. // Matrix
  36720. case Animation.ANIMATIONTYPE_MATRIX:
  36721. switch (loopMode) {
  36722. case Animation.ANIMATIONLOOPMODE_CYCLE:
  36723. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  36724. if (this.allowMatricesInterpolation) {
  36725. return this.matrixInterpolateFunction(startValue, endValue, gradient);
  36726. }
  36727. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  36728. return startValue;
  36729. }
  36730. default:
  36731. break;
  36732. }
  36733. break;
  36734. }
  36735. }
  36736. return this._getKeyValue(this._keys[this._keys.length - 1].value);
  36737. };
  36738. Animation.prototype.setValue = function (currentValue, blend) {
  36739. if (blend === void 0) { blend = false; }
  36740. // Set value
  36741. var path;
  36742. var destination;
  36743. if (this.targetPropertyPath.length > 1) {
  36744. var property = this._target[this.targetPropertyPath[0]];
  36745. for (var index = 1; index < this.targetPropertyPath.length - 1; index++) {
  36746. property = property[this.targetPropertyPath[index]];
  36747. }
  36748. path = this.targetPropertyPath[this.targetPropertyPath.length - 1];
  36749. destination = property;
  36750. }
  36751. else {
  36752. path = this.targetPropertyPath[0];
  36753. destination = this._target;
  36754. }
  36755. // Blending
  36756. if (this.enableBlending && this._blendingFactor <= 1.0) {
  36757. if (!this._originalBlendValue) {
  36758. if (destination[path].clone) {
  36759. this._originalBlendValue = destination[path].clone();
  36760. }
  36761. else {
  36762. this._originalBlendValue = destination[path];
  36763. }
  36764. }
  36765. if (this._originalBlendValue.prototype) {
  36766. if (this._originalBlendValue.prototype.Lerp) {
  36767. destination[path] = this._originalBlendValue.construtor.prototype.Lerp(currentValue, this._originalBlendValue, this._blendingFactor);
  36768. }
  36769. else {
  36770. destination[path] = currentValue;
  36771. }
  36772. }
  36773. else if (this._originalBlendValue.m) {
  36774. destination[path] = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  36775. }
  36776. else {
  36777. destination[path] = this._originalBlendValue * (1.0 - this._blendingFactor) + this._blendingFactor * currentValue;
  36778. }
  36779. this._blendingFactor += this.blendingSpeed;
  36780. }
  36781. else {
  36782. destination[path] = currentValue;
  36783. }
  36784. if (this._target.markAsDirty) {
  36785. this._target.markAsDirty(this.targetProperty);
  36786. }
  36787. };
  36788. Animation.prototype.goToFrame = function (frame) {
  36789. if (frame < this._keys[0].frame) {
  36790. frame = this._keys[0].frame;
  36791. }
  36792. else if (frame > this._keys[this._keys.length - 1].frame) {
  36793. frame = this._keys[this._keys.length - 1].frame;
  36794. }
  36795. var currentValue = this._interpolate(frame, 0, this.loopMode);
  36796. this.setValue(currentValue);
  36797. };
  36798. Animation.prototype.animate = function (delay, from, to, loop, speedRatio, blend) {
  36799. if (blend === void 0) { blend = false; }
  36800. if (!this.targetPropertyPath || this.targetPropertyPath.length < 1) {
  36801. this._stopped = true;
  36802. return false;
  36803. }
  36804. var returnValue = true;
  36805. // Adding a start key at frame 0 if missing
  36806. if (this._keys[0].frame !== 0) {
  36807. var newKey = { frame: 0, value: this._keys[0].value };
  36808. this._keys.splice(0, 0, newKey);
  36809. }
  36810. // Check limits
  36811. if (from < this._keys[0].frame || from > this._keys[this._keys.length - 1].frame) {
  36812. from = this._keys[0].frame;
  36813. }
  36814. if (to < this._keys[0].frame || to > this._keys[this._keys.length - 1].frame) {
  36815. to = this._keys[this._keys.length - 1].frame;
  36816. }
  36817. //to and from cannot be the same key
  36818. if (from === to) {
  36819. from++;
  36820. }
  36821. // Compute ratio
  36822. var range = to - from;
  36823. var offsetValue;
  36824. // ratio represents the frame delta between from and to
  36825. var ratio = delay * (this.framePerSecond * speedRatio) / 1000.0;
  36826. var highLimitValue = 0;
  36827. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) {
  36828. returnValue = false;
  36829. highLimitValue = this._getKeyValue(this._keys[this._keys.length - 1].value);
  36830. }
  36831. else {
  36832. // Get max value if required
  36833. if (this.loopMode !== Animation.ANIMATIONLOOPMODE_CYCLE) {
  36834. var keyOffset = to.toString() + from.toString();
  36835. if (!this._offsetsCache[keyOffset]) {
  36836. var fromValue = this._interpolate(from, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36837. var toValue = this._interpolate(to, 0, Animation.ANIMATIONLOOPMODE_CYCLE);
  36838. switch (this.dataType) {
  36839. // Float
  36840. case Animation.ANIMATIONTYPE_FLOAT:
  36841. this._offsetsCache[keyOffset] = toValue - fromValue;
  36842. break;
  36843. // Quaternion
  36844. case Animation.ANIMATIONTYPE_QUATERNION:
  36845. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36846. break;
  36847. // Vector3
  36848. case Animation.ANIMATIONTYPE_VECTOR3:
  36849. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36850. // Vector2
  36851. case Animation.ANIMATIONTYPE_VECTOR2:
  36852. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36853. // Size
  36854. case Animation.ANIMATIONTYPE_SIZE:
  36855. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36856. // Color3
  36857. case Animation.ANIMATIONTYPE_COLOR3:
  36858. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  36859. default:
  36860. break;
  36861. }
  36862. this._highLimitsCache[keyOffset] = toValue;
  36863. }
  36864. highLimitValue = this._highLimitsCache[keyOffset];
  36865. offsetValue = this._offsetsCache[keyOffset];
  36866. }
  36867. }
  36868. if (offsetValue === undefined) {
  36869. switch (this.dataType) {
  36870. // Float
  36871. case Animation.ANIMATIONTYPE_FLOAT:
  36872. offsetValue = 0;
  36873. break;
  36874. // Quaternion
  36875. case Animation.ANIMATIONTYPE_QUATERNION:
  36876. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  36877. break;
  36878. // Vector3
  36879. case Animation.ANIMATIONTYPE_VECTOR3:
  36880. offsetValue = BABYLON.Vector3.Zero();
  36881. break;
  36882. // Vector2
  36883. case Animation.ANIMATIONTYPE_VECTOR2:
  36884. offsetValue = BABYLON.Vector2.Zero();
  36885. break;
  36886. // Size
  36887. case Animation.ANIMATIONTYPE_SIZE:
  36888. offsetValue = BABYLON.Size.Zero();
  36889. break;
  36890. // Color3
  36891. case Animation.ANIMATIONTYPE_COLOR3:
  36892. offsetValue = BABYLON.Color3.Black();
  36893. }
  36894. }
  36895. // Compute value
  36896. var repeatCount = (ratio / range) >> 0;
  36897. var currentFrame = returnValue ? from + ratio % range : to;
  36898. var currentValue = this._interpolate(currentFrame, repeatCount, this.loopMode, offsetValue, highLimitValue);
  36899. // Set value
  36900. this.setValue(currentValue);
  36901. // Check events
  36902. for (var index = 0; index < this._events.length; index++) {
  36903. // Make sure current frame has passed event frame and that event frame is within the current range
  36904. // Also, handle both forward and reverse animations
  36905. if ((range > 0 && currentFrame >= this._events[index].frame && this._events[index].frame >= from) ||
  36906. (range < 0 && currentFrame <= this._events[index].frame && this._events[index].frame <= from)) {
  36907. var event = this._events[index];
  36908. if (!event.isDone) {
  36909. // If event should be done only once, remove it.
  36910. if (event.onlyOnce) {
  36911. this._events.splice(index, 1);
  36912. index--;
  36913. }
  36914. event.isDone = true;
  36915. event.action();
  36916. } // Don't do anything if the event has already be done.
  36917. }
  36918. else if (this._events[index].isDone && !this._events[index].onlyOnce) {
  36919. // reset event, the animation is looping
  36920. this._events[index].isDone = false;
  36921. }
  36922. }
  36923. if (!returnValue) {
  36924. this._stopped = true;
  36925. }
  36926. return returnValue;
  36927. };
  36928. Animation.prototype.serialize = function () {
  36929. var serializationObject = {};
  36930. serializationObject.name = this.name;
  36931. serializationObject.property = this.targetProperty;
  36932. serializationObject.framePerSecond = this.framePerSecond;
  36933. serializationObject.dataType = this.dataType;
  36934. serializationObject.loopBehavior = this.loopMode;
  36935. serializationObject.enableBlending = this.enableBlending;
  36936. serializationObject.blendingSpeed = this.blendingSpeed;
  36937. var dataType = this.dataType;
  36938. serializationObject.keys = [];
  36939. var keys = this.getKeys();
  36940. for (var index = 0; index < keys.length; index++) {
  36941. var animationKey = keys[index];
  36942. var key = {};
  36943. key.frame = animationKey.frame;
  36944. switch (dataType) {
  36945. case Animation.ANIMATIONTYPE_FLOAT:
  36946. key.values = [animationKey.value];
  36947. break;
  36948. case Animation.ANIMATIONTYPE_QUATERNION:
  36949. case Animation.ANIMATIONTYPE_MATRIX:
  36950. case Animation.ANIMATIONTYPE_VECTOR3:
  36951. case Animation.ANIMATIONTYPE_COLOR3:
  36952. key.values = animationKey.value.asArray();
  36953. break;
  36954. }
  36955. serializationObject.keys.push(key);
  36956. }
  36957. serializationObject.ranges = [];
  36958. for (var name in this._ranges) {
  36959. var range = {};
  36960. range.name = name;
  36961. range.from = this._ranges[name].from;
  36962. range.to = this._ranges[name].to;
  36963. serializationObject.ranges.push(range);
  36964. }
  36965. return serializationObject;
  36966. };
  36967. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  36968. get: function () {
  36969. return Animation._ANIMATIONTYPE_FLOAT;
  36970. },
  36971. enumerable: true,
  36972. configurable: true
  36973. });
  36974. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  36975. get: function () {
  36976. return Animation._ANIMATIONTYPE_VECTOR3;
  36977. },
  36978. enumerable: true,
  36979. configurable: true
  36980. });
  36981. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  36982. get: function () {
  36983. return Animation._ANIMATIONTYPE_VECTOR2;
  36984. },
  36985. enumerable: true,
  36986. configurable: true
  36987. });
  36988. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  36989. get: function () {
  36990. return Animation._ANIMATIONTYPE_SIZE;
  36991. },
  36992. enumerable: true,
  36993. configurable: true
  36994. });
  36995. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  36996. get: function () {
  36997. return Animation._ANIMATIONTYPE_QUATERNION;
  36998. },
  36999. enumerable: true,
  37000. configurable: true
  37001. });
  37002. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  37003. get: function () {
  37004. return Animation._ANIMATIONTYPE_MATRIX;
  37005. },
  37006. enumerable: true,
  37007. configurable: true
  37008. });
  37009. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  37010. get: function () {
  37011. return Animation._ANIMATIONTYPE_COLOR3;
  37012. },
  37013. enumerable: true,
  37014. configurable: true
  37015. });
  37016. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  37017. get: function () {
  37018. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  37019. },
  37020. enumerable: true,
  37021. configurable: true
  37022. });
  37023. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  37024. get: function () {
  37025. return Animation._ANIMATIONLOOPMODE_CYCLE;
  37026. },
  37027. enumerable: true,
  37028. configurable: true
  37029. });
  37030. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  37031. get: function () {
  37032. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  37033. },
  37034. enumerable: true,
  37035. configurable: true
  37036. });
  37037. Animation.Parse = function (parsedAnimation) {
  37038. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  37039. var dataType = parsedAnimation.dataType;
  37040. var keys = [];
  37041. var data;
  37042. var index;
  37043. if (parsedAnimation.enableBlending) {
  37044. animation.enableBlending = parsedAnimation.enableBlending;
  37045. }
  37046. if (parsedAnimation.blendingSpeed) {
  37047. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  37048. }
  37049. for (index = 0; index < parsedAnimation.keys.length; index++) {
  37050. var key = parsedAnimation.keys[index];
  37051. switch (dataType) {
  37052. case Animation.ANIMATIONTYPE_FLOAT:
  37053. data = key.values[0];
  37054. break;
  37055. case Animation.ANIMATIONTYPE_QUATERNION:
  37056. data = BABYLON.Quaternion.FromArray(key.values);
  37057. break;
  37058. case Animation.ANIMATIONTYPE_MATRIX:
  37059. data = BABYLON.Matrix.FromArray(key.values);
  37060. break;
  37061. case Animation.ANIMATIONTYPE_COLOR3:
  37062. data = BABYLON.Color3.FromArray(key.values);
  37063. break;
  37064. case Animation.ANIMATIONTYPE_VECTOR3:
  37065. default:
  37066. data = BABYLON.Vector3.FromArray(key.values);
  37067. break;
  37068. }
  37069. keys.push({
  37070. frame: key.frame,
  37071. value: data
  37072. });
  37073. }
  37074. animation.setKeys(keys);
  37075. if (parsedAnimation.ranges) {
  37076. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  37077. data = parsedAnimation.ranges[index];
  37078. animation.createRange(data.name, data.from, data.to);
  37079. }
  37080. }
  37081. return animation;
  37082. };
  37083. Animation.AppendSerializedAnimations = function (source, destination) {
  37084. if (source.animations) {
  37085. destination.animations = [];
  37086. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  37087. var animation = source.animations[animationIndex];
  37088. destination.animations.push(animation.serialize());
  37089. }
  37090. }
  37091. };
  37092. // Statics
  37093. Animation._ANIMATIONTYPE_FLOAT = 0;
  37094. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  37095. Animation._ANIMATIONTYPE_QUATERNION = 2;
  37096. Animation._ANIMATIONTYPE_MATRIX = 3;
  37097. Animation._ANIMATIONTYPE_COLOR3 = 4;
  37098. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  37099. Animation._ANIMATIONTYPE_SIZE = 6;
  37100. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  37101. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  37102. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  37103. return Animation;
  37104. }());
  37105. BABYLON.Animation = Animation;
  37106. })(BABYLON || (BABYLON = {}));
  37107. //# sourceMappingURL=babylon.animation.js.map
  37108. var BABYLON;
  37109. (function (BABYLON) {
  37110. var Animatable = (function () {
  37111. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  37112. if (fromFrame === void 0) { fromFrame = 0; }
  37113. if (toFrame === void 0) { toFrame = 100; }
  37114. if (loopAnimation === void 0) { loopAnimation = false; }
  37115. if (speedRatio === void 0) { speedRatio = 1.0; }
  37116. this.target = target;
  37117. this.fromFrame = fromFrame;
  37118. this.toFrame = toFrame;
  37119. this.loopAnimation = loopAnimation;
  37120. this.speedRatio = speedRatio;
  37121. this.onAnimationEnd = onAnimationEnd;
  37122. this._localDelayOffset = null;
  37123. this._pausedDelay = null;
  37124. this._animations = new Array();
  37125. this._paused = false;
  37126. this.animationStarted = false;
  37127. if (animations) {
  37128. this.appendAnimations(target, animations);
  37129. }
  37130. this._scene = scene;
  37131. scene._activeAnimatables.push(this);
  37132. }
  37133. // Methods
  37134. Animatable.prototype.getAnimations = function () {
  37135. return this._animations;
  37136. };
  37137. Animatable.prototype.appendAnimations = function (target, animations) {
  37138. for (var index = 0; index < animations.length; index++) {
  37139. var animation = animations[index];
  37140. animation._target = target;
  37141. this._animations.push(animation);
  37142. }
  37143. };
  37144. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  37145. var animations = this._animations;
  37146. for (var index = 0; index < animations.length; index++) {
  37147. if (animations[index].targetProperty === property) {
  37148. return animations[index];
  37149. }
  37150. }
  37151. return null;
  37152. };
  37153. Animatable.prototype.reset = function () {
  37154. var animations = this._animations;
  37155. for (var index = 0; index < animations.length; index++) {
  37156. animations[index].reset();
  37157. }
  37158. this._localDelayOffset = null;
  37159. this._pausedDelay = null;
  37160. };
  37161. Animatable.prototype.enableBlending = function (blendingSpeed) {
  37162. var animations = this._animations;
  37163. for (var index = 0; index < animations.length; index++) {
  37164. animations[index].enableBlending = true;
  37165. animations[index].blendingSpeed = blendingSpeed;
  37166. }
  37167. };
  37168. Animatable.prototype.disableBlending = function () {
  37169. var animations = this._animations;
  37170. for (var index = 0; index < animations.length; index++) {
  37171. animations[index].enableBlending = false;
  37172. }
  37173. };
  37174. Animatable.prototype.goToFrame = function (frame) {
  37175. var animations = this._animations;
  37176. if (animations[0]) {
  37177. var fps = animations[0].framePerSecond;
  37178. var currentFrame = animations[0].currentFrame;
  37179. var adjustTime = frame - currentFrame;
  37180. var delay = adjustTime * 1000 / fps;
  37181. this._localDelayOffset -= delay;
  37182. }
  37183. for (var index = 0; index < animations.length; index++) {
  37184. animations[index].goToFrame(frame);
  37185. }
  37186. };
  37187. Animatable.prototype.pause = function () {
  37188. if (this._paused) {
  37189. return;
  37190. }
  37191. this._paused = true;
  37192. };
  37193. Animatable.prototype.restart = function () {
  37194. this._paused = false;
  37195. };
  37196. Animatable.prototype.stop = function (animationName) {
  37197. if (animationName) {
  37198. var idx = this._scene._activeAnimatables.indexOf(this);
  37199. if (idx > -1) {
  37200. var animations = this._animations;
  37201. for (var index = animations.length - 1; index >= 0; index--) {
  37202. if (typeof animationName === "string" && animations[index].name != animationName) {
  37203. continue;
  37204. }
  37205. animations[index].reset();
  37206. animations.splice(index, 1);
  37207. }
  37208. if (animations.length == 0) {
  37209. this._scene._activeAnimatables.splice(idx, 1);
  37210. if (this.onAnimationEnd) {
  37211. this.onAnimationEnd();
  37212. }
  37213. }
  37214. }
  37215. }
  37216. else {
  37217. var index = this._scene._activeAnimatables.indexOf(this);
  37218. if (index > -1) {
  37219. this._scene._activeAnimatables.splice(index, 1);
  37220. var animations = this._animations;
  37221. for (var index = 0; index < animations.length; index++) {
  37222. animations[index].reset();
  37223. }
  37224. if (this.onAnimationEnd) {
  37225. this.onAnimationEnd();
  37226. }
  37227. }
  37228. }
  37229. };
  37230. Animatable.prototype._animate = function (delay) {
  37231. if (this._paused) {
  37232. this.animationStarted = false;
  37233. if (this._pausedDelay === null) {
  37234. this._pausedDelay = delay;
  37235. }
  37236. return true;
  37237. }
  37238. if (this._localDelayOffset === null) {
  37239. this._localDelayOffset = delay;
  37240. }
  37241. else if (this._pausedDelay !== null) {
  37242. this._localDelayOffset += delay - this._pausedDelay;
  37243. this._pausedDelay = null;
  37244. }
  37245. // Animating
  37246. var running = false;
  37247. var animations = this._animations;
  37248. var index;
  37249. for (index = 0; index < animations.length; index++) {
  37250. var animation = animations[index];
  37251. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this.speedRatio);
  37252. running = running || isRunning;
  37253. }
  37254. this.animationStarted = running;
  37255. if (!running) {
  37256. // Remove from active animatables
  37257. index = this._scene._activeAnimatables.indexOf(this);
  37258. this._scene._activeAnimatables.splice(index, 1);
  37259. }
  37260. if (!running && this.onAnimationEnd) {
  37261. this.onAnimationEnd();
  37262. this.onAnimationEnd = null;
  37263. }
  37264. return running;
  37265. };
  37266. return Animatable;
  37267. }());
  37268. BABYLON.Animatable = Animatable;
  37269. })(BABYLON || (BABYLON = {}));
  37270. //# sourceMappingURL=babylon.animatable.js.map
  37271. var BABYLON;
  37272. (function (BABYLON) {
  37273. var EasingFunction = (function () {
  37274. function EasingFunction() {
  37275. // Properties
  37276. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  37277. }
  37278. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  37279. get: function () {
  37280. return EasingFunction._EASINGMODE_EASEIN;
  37281. },
  37282. enumerable: true,
  37283. configurable: true
  37284. });
  37285. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  37286. get: function () {
  37287. return EasingFunction._EASINGMODE_EASEOUT;
  37288. },
  37289. enumerable: true,
  37290. configurable: true
  37291. });
  37292. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  37293. get: function () {
  37294. return EasingFunction._EASINGMODE_EASEINOUT;
  37295. },
  37296. enumerable: true,
  37297. configurable: true
  37298. });
  37299. EasingFunction.prototype.setEasingMode = function (easingMode) {
  37300. var n = Math.min(Math.max(easingMode, 0), 2);
  37301. this._easingMode = n;
  37302. };
  37303. EasingFunction.prototype.getEasingMode = function () {
  37304. return this._easingMode;
  37305. };
  37306. EasingFunction.prototype.easeInCore = function (gradient) {
  37307. throw new Error('You must implement this method');
  37308. };
  37309. EasingFunction.prototype.ease = function (gradient) {
  37310. switch (this._easingMode) {
  37311. case EasingFunction.EASINGMODE_EASEIN:
  37312. return this.easeInCore(gradient);
  37313. case EasingFunction.EASINGMODE_EASEOUT:
  37314. return (1 - this.easeInCore(1 - gradient));
  37315. }
  37316. if (gradient >= 0.5) {
  37317. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  37318. }
  37319. return (this.easeInCore(gradient * 2) * 0.5);
  37320. };
  37321. //Statics
  37322. EasingFunction._EASINGMODE_EASEIN = 0;
  37323. EasingFunction._EASINGMODE_EASEOUT = 1;
  37324. EasingFunction._EASINGMODE_EASEINOUT = 2;
  37325. return EasingFunction;
  37326. }());
  37327. BABYLON.EasingFunction = EasingFunction;
  37328. var CircleEase = (function (_super) {
  37329. __extends(CircleEase, _super);
  37330. function CircleEase() {
  37331. return _super !== null && _super.apply(this, arguments) || this;
  37332. }
  37333. CircleEase.prototype.easeInCore = function (gradient) {
  37334. gradient = Math.max(0, Math.min(1, gradient));
  37335. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  37336. };
  37337. return CircleEase;
  37338. }(EasingFunction));
  37339. BABYLON.CircleEase = CircleEase;
  37340. var BackEase = (function (_super) {
  37341. __extends(BackEase, _super);
  37342. function BackEase(amplitude) {
  37343. if (amplitude === void 0) { amplitude = 1; }
  37344. var _this = _super.call(this) || this;
  37345. _this.amplitude = amplitude;
  37346. return _this;
  37347. }
  37348. BackEase.prototype.easeInCore = function (gradient) {
  37349. var num = Math.max(0, this.amplitude);
  37350. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  37351. };
  37352. return BackEase;
  37353. }(EasingFunction));
  37354. BABYLON.BackEase = BackEase;
  37355. var BounceEase = (function (_super) {
  37356. __extends(BounceEase, _super);
  37357. function BounceEase(bounces, bounciness) {
  37358. if (bounces === void 0) { bounces = 3; }
  37359. if (bounciness === void 0) { bounciness = 2; }
  37360. var _this = _super.call(this) || this;
  37361. _this.bounces = bounces;
  37362. _this.bounciness = bounciness;
  37363. return _this;
  37364. }
  37365. BounceEase.prototype.easeInCore = function (gradient) {
  37366. var y = Math.max(0.0, this.bounces);
  37367. var bounciness = this.bounciness;
  37368. if (bounciness <= 1.0) {
  37369. bounciness = 1.001;
  37370. }
  37371. var num9 = Math.pow(bounciness, y);
  37372. var num5 = 1.0 - bounciness;
  37373. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  37374. var num15 = gradient * num4;
  37375. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  37376. var num3 = Math.floor(num65);
  37377. var num13 = num3 + 1.0;
  37378. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  37379. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  37380. var num7 = (num8 + num12) * 0.5;
  37381. var num6 = gradient - num7;
  37382. var num2 = num7 - num8;
  37383. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  37384. };
  37385. return BounceEase;
  37386. }(EasingFunction));
  37387. BABYLON.BounceEase = BounceEase;
  37388. var CubicEase = (function (_super) {
  37389. __extends(CubicEase, _super);
  37390. function CubicEase() {
  37391. return _super !== null && _super.apply(this, arguments) || this;
  37392. }
  37393. CubicEase.prototype.easeInCore = function (gradient) {
  37394. return (gradient * gradient * gradient);
  37395. };
  37396. return CubicEase;
  37397. }(EasingFunction));
  37398. BABYLON.CubicEase = CubicEase;
  37399. var ElasticEase = (function (_super) {
  37400. __extends(ElasticEase, _super);
  37401. function ElasticEase(oscillations, springiness) {
  37402. if (oscillations === void 0) { oscillations = 3; }
  37403. if (springiness === void 0) { springiness = 3; }
  37404. var _this = _super.call(this) || this;
  37405. _this.oscillations = oscillations;
  37406. _this.springiness = springiness;
  37407. return _this;
  37408. }
  37409. ElasticEase.prototype.easeInCore = function (gradient) {
  37410. var num2;
  37411. var num3 = Math.max(0.0, this.oscillations);
  37412. var num = Math.max(0.0, this.springiness);
  37413. if (num == 0) {
  37414. num2 = gradient;
  37415. }
  37416. else {
  37417. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  37418. }
  37419. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  37420. };
  37421. return ElasticEase;
  37422. }(EasingFunction));
  37423. BABYLON.ElasticEase = ElasticEase;
  37424. var ExponentialEase = (function (_super) {
  37425. __extends(ExponentialEase, _super);
  37426. function ExponentialEase(exponent) {
  37427. if (exponent === void 0) { exponent = 2; }
  37428. var _this = _super.call(this) || this;
  37429. _this.exponent = exponent;
  37430. return _this;
  37431. }
  37432. ExponentialEase.prototype.easeInCore = function (gradient) {
  37433. if (this.exponent <= 0) {
  37434. return gradient;
  37435. }
  37436. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  37437. };
  37438. return ExponentialEase;
  37439. }(EasingFunction));
  37440. BABYLON.ExponentialEase = ExponentialEase;
  37441. var PowerEase = (function (_super) {
  37442. __extends(PowerEase, _super);
  37443. function PowerEase(power) {
  37444. if (power === void 0) { power = 2; }
  37445. var _this = _super.call(this) || this;
  37446. _this.power = power;
  37447. return _this;
  37448. }
  37449. PowerEase.prototype.easeInCore = function (gradient) {
  37450. var y = Math.max(0.0, this.power);
  37451. return Math.pow(gradient, y);
  37452. };
  37453. return PowerEase;
  37454. }(EasingFunction));
  37455. BABYLON.PowerEase = PowerEase;
  37456. var QuadraticEase = (function (_super) {
  37457. __extends(QuadraticEase, _super);
  37458. function QuadraticEase() {
  37459. return _super !== null && _super.apply(this, arguments) || this;
  37460. }
  37461. QuadraticEase.prototype.easeInCore = function (gradient) {
  37462. return (gradient * gradient);
  37463. };
  37464. return QuadraticEase;
  37465. }(EasingFunction));
  37466. BABYLON.QuadraticEase = QuadraticEase;
  37467. var QuarticEase = (function (_super) {
  37468. __extends(QuarticEase, _super);
  37469. function QuarticEase() {
  37470. return _super !== null && _super.apply(this, arguments) || this;
  37471. }
  37472. QuarticEase.prototype.easeInCore = function (gradient) {
  37473. return (gradient * gradient * gradient * gradient);
  37474. };
  37475. return QuarticEase;
  37476. }(EasingFunction));
  37477. BABYLON.QuarticEase = QuarticEase;
  37478. var QuinticEase = (function (_super) {
  37479. __extends(QuinticEase, _super);
  37480. function QuinticEase() {
  37481. return _super !== null && _super.apply(this, arguments) || this;
  37482. }
  37483. QuinticEase.prototype.easeInCore = function (gradient) {
  37484. return (gradient * gradient * gradient * gradient * gradient);
  37485. };
  37486. return QuinticEase;
  37487. }(EasingFunction));
  37488. BABYLON.QuinticEase = QuinticEase;
  37489. var SineEase = (function (_super) {
  37490. __extends(SineEase, _super);
  37491. function SineEase() {
  37492. return _super !== null && _super.apply(this, arguments) || this;
  37493. }
  37494. SineEase.prototype.easeInCore = function (gradient) {
  37495. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  37496. };
  37497. return SineEase;
  37498. }(EasingFunction));
  37499. BABYLON.SineEase = SineEase;
  37500. var BezierCurveEase = (function (_super) {
  37501. __extends(BezierCurveEase, _super);
  37502. function BezierCurveEase(x1, y1, x2, y2) {
  37503. if (x1 === void 0) { x1 = 0; }
  37504. if (y1 === void 0) { y1 = 0; }
  37505. if (x2 === void 0) { x2 = 1; }
  37506. if (y2 === void 0) { y2 = 1; }
  37507. var _this = _super.call(this) || this;
  37508. _this.x1 = x1;
  37509. _this.y1 = y1;
  37510. _this.x2 = x2;
  37511. _this.y2 = y2;
  37512. return _this;
  37513. }
  37514. BezierCurveEase.prototype.easeInCore = function (gradient) {
  37515. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  37516. };
  37517. return BezierCurveEase;
  37518. }(EasingFunction));
  37519. BABYLON.BezierCurveEase = BezierCurveEase;
  37520. })(BABYLON || (BABYLON = {}));
  37521. //# sourceMappingURL=babylon.easing.js.map
  37522. var BABYLON;
  37523. (function (BABYLON) {
  37524. var Condition = (function () {
  37525. function Condition(actionManager) {
  37526. this._actionManager = actionManager;
  37527. }
  37528. Condition.prototype.isValid = function () {
  37529. return true;
  37530. };
  37531. Condition.prototype._getProperty = function (propertyPath) {
  37532. return this._actionManager._getProperty(propertyPath);
  37533. };
  37534. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  37535. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37536. };
  37537. Condition.prototype.serialize = function () {
  37538. };
  37539. Condition.prototype._serialize = function (serializedCondition) {
  37540. return {
  37541. type: 2,
  37542. children: [],
  37543. name: serializedCondition.name,
  37544. properties: serializedCondition.properties
  37545. };
  37546. };
  37547. return Condition;
  37548. }());
  37549. BABYLON.Condition = Condition;
  37550. var ValueCondition = (function (_super) {
  37551. __extends(ValueCondition, _super);
  37552. function ValueCondition(actionManager, target, propertyPath, value, operator) {
  37553. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  37554. var _this = _super.call(this, actionManager) || this;
  37555. _this.propertyPath = propertyPath;
  37556. _this.value = value;
  37557. _this.operator = operator;
  37558. _this._target = target;
  37559. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  37560. _this._property = _this._getProperty(_this.propertyPath);
  37561. return _this;
  37562. }
  37563. Object.defineProperty(ValueCondition, "IsEqual", {
  37564. get: function () {
  37565. return ValueCondition._IsEqual;
  37566. },
  37567. enumerable: true,
  37568. configurable: true
  37569. });
  37570. Object.defineProperty(ValueCondition, "IsDifferent", {
  37571. get: function () {
  37572. return ValueCondition._IsDifferent;
  37573. },
  37574. enumerable: true,
  37575. configurable: true
  37576. });
  37577. Object.defineProperty(ValueCondition, "IsGreater", {
  37578. get: function () {
  37579. return ValueCondition._IsGreater;
  37580. },
  37581. enumerable: true,
  37582. configurable: true
  37583. });
  37584. Object.defineProperty(ValueCondition, "IsLesser", {
  37585. get: function () {
  37586. return ValueCondition._IsLesser;
  37587. },
  37588. enumerable: true,
  37589. configurable: true
  37590. });
  37591. // Methods
  37592. ValueCondition.prototype.isValid = function () {
  37593. switch (this.operator) {
  37594. case ValueCondition.IsGreater:
  37595. return this._effectiveTarget[this._property] > this.value;
  37596. case ValueCondition.IsLesser:
  37597. return this._effectiveTarget[this._property] < this.value;
  37598. case ValueCondition.IsEqual:
  37599. case ValueCondition.IsDifferent:
  37600. var check;
  37601. if (this.value.equals) {
  37602. check = this.value.equals(this._effectiveTarget[this._property]);
  37603. }
  37604. else {
  37605. check = this.value === this._effectiveTarget[this._property];
  37606. }
  37607. return this.operator === ValueCondition.IsEqual ? check : !check;
  37608. }
  37609. return false;
  37610. };
  37611. ValueCondition.prototype.serialize = function () {
  37612. return this._serialize({
  37613. name: "ValueCondition",
  37614. properties: [
  37615. BABYLON.Action._GetTargetProperty(this._target),
  37616. { name: "propertyPath", value: this.propertyPath },
  37617. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  37618. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  37619. ]
  37620. });
  37621. };
  37622. ValueCondition.GetOperatorName = function (operator) {
  37623. switch (operator) {
  37624. case ValueCondition._IsEqual: return "IsEqual";
  37625. case ValueCondition._IsDifferent: return "IsDifferent";
  37626. case ValueCondition._IsGreater: return "IsGreater";
  37627. case ValueCondition._IsLesser: return "IsLesser";
  37628. default: return "";
  37629. }
  37630. };
  37631. // Statics
  37632. ValueCondition._IsEqual = 0;
  37633. ValueCondition._IsDifferent = 1;
  37634. ValueCondition._IsGreater = 2;
  37635. ValueCondition._IsLesser = 3;
  37636. return ValueCondition;
  37637. }(Condition));
  37638. BABYLON.ValueCondition = ValueCondition;
  37639. var PredicateCondition = (function (_super) {
  37640. __extends(PredicateCondition, _super);
  37641. function PredicateCondition(actionManager, predicate) {
  37642. var _this = _super.call(this, actionManager) || this;
  37643. _this.predicate = predicate;
  37644. return _this;
  37645. }
  37646. PredicateCondition.prototype.isValid = function () {
  37647. return this.predicate();
  37648. };
  37649. return PredicateCondition;
  37650. }(Condition));
  37651. BABYLON.PredicateCondition = PredicateCondition;
  37652. var StateCondition = (function (_super) {
  37653. __extends(StateCondition, _super);
  37654. function StateCondition(actionManager, target, value) {
  37655. var _this = _super.call(this, actionManager) || this;
  37656. _this.value = value;
  37657. _this._target = target;
  37658. return _this;
  37659. }
  37660. // Methods
  37661. StateCondition.prototype.isValid = function () {
  37662. return this._target.state === this.value;
  37663. };
  37664. StateCondition.prototype.serialize = function () {
  37665. return this._serialize({
  37666. name: "StateCondition",
  37667. properties: [
  37668. BABYLON.Action._GetTargetProperty(this._target),
  37669. { name: "value", value: this.value }
  37670. ]
  37671. });
  37672. };
  37673. return StateCondition;
  37674. }(Condition));
  37675. BABYLON.StateCondition = StateCondition;
  37676. })(BABYLON || (BABYLON = {}));
  37677. //# sourceMappingURL=babylon.condition.js.map
  37678. var BABYLON;
  37679. (function (BABYLON) {
  37680. var Action = (function () {
  37681. function Action(triggerOptions, condition) {
  37682. this.triggerOptions = triggerOptions;
  37683. if (triggerOptions.parameter) {
  37684. this.trigger = triggerOptions.trigger;
  37685. this._triggerParameter = triggerOptions.parameter;
  37686. }
  37687. else {
  37688. this.trigger = triggerOptions;
  37689. }
  37690. this._nextActiveAction = this;
  37691. this._condition = condition;
  37692. }
  37693. // Methods
  37694. Action.prototype._prepare = function () {
  37695. };
  37696. Action.prototype.getTriggerParameter = function () {
  37697. return this._triggerParameter;
  37698. };
  37699. Action.prototype._executeCurrent = function (evt) {
  37700. if (this._nextActiveAction._condition) {
  37701. var condition = this._nextActiveAction._condition;
  37702. var currentRenderId = this._actionManager.getScene().getRenderId();
  37703. // We cache the current evaluation for the current frame
  37704. if (condition._evaluationId === currentRenderId) {
  37705. if (!condition._currentResult) {
  37706. return;
  37707. }
  37708. }
  37709. else {
  37710. condition._evaluationId = currentRenderId;
  37711. if (!condition.isValid()) {
  37712. condition._currentResult = false;
  37713. return;
  37714. }
  37715. condition._currentResult = true;
  37716. }
  37717. }
  37718. this._nextActiveAction.execute(evt);
  37719. this.skipToNextActiveAction();
  37720. };
  37721. Action.prototype.execute = function (evt) {
  37722. };
  37723. Action.prototype.skipToNextActiveAction = function () {
  37724. if (this._nextActiveAction._child) {
  37725. if (!this._nextActiveAction._child._actionManager) {
  37726. this._nextActiveAction._child._actionManager = this._actionManager;
  37727. }
  37728. this._nextActiveAction = this._nextActiveAction._child;
  37729. }
  37730. else {
  37731. this._nextActiveAction = this;
  37732. }
  37733. };
  37734. Action.prototype.then = function (action) {
  37735. this._child = action;
  37736. action._actionManager = this._actionManager;
  37737. action._prepare();
  37738. return action;
  37739. };
  37740. Action.prototype._getProperty = function (propertyPath) {
  37741. return this._actionManager._getProperty(propertyPath);
  37742. };
  37743. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  37744. return this._actionManager._getEffectiveTarget(target, propertyPath);
  37745. };
  37746. Action.prototype.serialize = function (parent) {
  37747. };
  37748. // Called by BABYLON.Action objects in serialize(...). Internal use
  37749. Action.prototype._serialize = function (serializedAction, parent) {
  37750. var serializationObject = {
  37751. type: 1,
  37752. children: [],
  37753. name: serializedAction.name,
  37754. properties: serializedAction.properties || []
  37755. };
  37756. // Serialize child
  37757. if (this._child) {
  37758. this._child.serialize(serializationObject);
  37759. }
  37760. // Check if "this" has a condition
  37761. if (this._condition) {
  37762. var serializedCondition = this._condition.serialize();
  37763. serializedCondition.children.push(serializationObject);
  37764. if (parent) {
  37765. parent.children.push(serializedCondition);
  37766. }
  37767. return serializedCondition;
  37768. }
  37769. if (parent) {
  37770. parent.children.push(serializationObject);
  37771. }
  37772. return serializationObject;
  37773. };
  37774. Action._SerializeValueAsString = function (value) {
  37775. if (typeof value === "number") {
  37776. return value.toString();
  37777. }
  37778. if (typeof value === "boolean") {
  37779. return value ? "true" : "false";
  37780. }
  37781. if (value instanceof BABYLON.Vector2) {
  37782. return value.x + ", " + value.y;
  37783. }
  37784. if (value instanceof BABYLON.Vector3) {
  37785. return value.x + ", " + value.y + ", " + value.z;
  37786. }
  37787. if (value instanceof BABYLON.Color3) {
  37788. return value.r + ", " + value.g + ", " + value.b;
  37789. }
  37790. if (value instanceof BABYLON.Color4) {
  37791. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  37792. }
  37793. return value; // string
  37794. };
  37795. Action._GetTargetProperty = function (target) {
  37796. return {
  37797. name: "target",
  37798. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  37799. : target instanceof BABYLON.Light ? "LightProperties"
  37800. : target instanceof BABYLON.Camera ? "CameraProperties"
  37801. : "SceneProperties",
  37802. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  37803. };
  37804. };
  37805. return Action;
  37806. }());
  37807. BABYLON.Action = Action;
  37808. })(BABYLON || (BABYLON = {}));
  37809. //# sourceMappingURL=babylon.action.js.map
  37810. var BABYLON;
  37811. (function (BABYLON) {
  37812. /**
  37813. * ActionEvent is the event beint sent when an action is triggered.
  37814. */
  37815. var ActionEvent = (function () {
  37816. /**
  37817. * @param source The mesh or sprite that triggered the action.
  37818. * @param pointerX The X mouse cursor position at the time of the event
  37819. * @param pointerY The Y mouse cursor position at the time of the event
  37820. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  37821. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  37822. */
  37823. function ActionEvent(source, pointerX, pointerY, meshUnderPointer, sourceEvent, additionalData) {
  37824. this.source = source;
  37825. this.pointerX = pointerX;
  37826. this.pointerY = pointerY;
  37827. this.meshUnderPointer = meshUnderPointer;
  37828. this.sourceEvent = sourceEvent;
  37829. this.additionalData = additionalData;
  37830. }
  37831. /**
  37832. * Helper function to auto-create an ActionEvent from a source mesh.
  37833. * @param source The source mesh that triggered the event
  37834. * @param evt {Event} The original (browser) event
  37835. */
  37836. ActionEvent.CreateNew = function (source, evt, additionalData) {
  37837. var scene = source.getScene();
  37838. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37839. };
  37840. /**
  37841. * Helper function to auto-create an ActionEvent from a source mesh.
  37842. * @param source The source sprite that triggered the event
  37843. * @param scene Scene associated with the sprite
  37844. * @param evt {Event} The original (browser) event
  37845. */
  37846. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  37847. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  37848. };
  37849. /**
  37850. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  37851. * @param scene the scene where the event occurred
  37852. * @param evt {Event} The original (browser) event
  37853. */
  37854. ActionEvent.CreateNewFromScene = function (scene, evt) {
  37855. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  37856. };
  37857. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  37858. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  37859. };
  37860. return ActionEvent;
  37861. }());
  37862. BABYLON.ActionEvent = ActionEvent;
  37863. /**
  37864. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  37865. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  37866. */
  37867. var ActionManager = (function () {
  37868. function ActionManager(scene) {
  37869. // Members
  37870. this.actions = new Array();
  37871. this.hoverCursor = '';
  37872. this._scene = scene;
  37873. scene._actionManagers.push(this);
  37874. }
  37875. Object.defineProperty(ActionManager, "NothingTrigger", {
  37876. get: function () {
  37877. return ActionManager._NothingTrigger;
  37878. },
  37879. enumerable: true,
  37880. configurable: true
  37881. });
  37882. Object.defineProperty(ActionManager, "OnPickTrigger", {
  37883. get: function () {
  37884. return ActionManager._OnPickTrigger;
  37885. },
  37886. enumerable: true,
  37887. configurable: true
  37888. });
  37889. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  37890. get: function () {
  37891. return ActionManager._OnLeftPickTrigger;
  37892. },
  37893. enumerable: true,
  37894. configurable: true
  37895. });
  37896. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  37897. get: function () {
  37898. return ActionManager._OnRightPickTrigger;
  37899. },
  37900. enumerable: true,
  37901. configurable: true
  37902. });
  37903. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  37904. get: function () {
  37905. return ActionManager._OnCenterPickTrigger;
  37906. },
  37907. enumerable: true,
  37908. configurable: true
  37909. });
  37910. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  37911. get: function () {
  37912. return ActionManager._OnPickDownTrigger;
  37913. },
  37914. enumerable: true,
  37915. configurable: true
  37916. });
  37917. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  37918. get: function () {
  37919. return ActionManager._OnDoublePickTrigger;
  37920. },
  37921. enumerable: true,
  37922. configurable: true
  37923. });
  37924. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  37925. get: function () {
  37926. return ActionManager._OnPickUpTrigger;
  37927. },
  37928. enumerable: true,
  37929. configurable: true
  37930. });
  37931. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  37932. /// This trigger will only be raised if you also declared a OnPickDown
  37933. get: function () {
  37934. return ActionManager._OnPickOutTrigger;
  37935. },
  37936. enumerable: true,
  37937. configurable: true
  37938. });
  37939. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  37940. get: function () {
  37941. return ActionManager._OnLongPressTrigger;
  37942. },
  37943. enumerable: true,
  37944. configurable: true
  37945. });
  37946. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  37947. get: function () {
  37948. return ActionManager._OnPointerOverTrigger;
  37949. },
  37950. enumerable: true,
  37951. configurable: true
  37952. });
  37953. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  37954. get: function () {
  37955. return ActionManager._OnPointerOutTrigger;
  37956. },
  37957. enumerable: true,
  37958. configurable: true
  37959. });
  37960. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  37961. get: function () {
  37962. return ActionManager._OnEveryFrameTrigger;
  37963. },
  37964. enumerable: true,
  37965. configurable: true
  37966. });
  37967. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  37968. get: function () {
  37969. return ActionManager._OnIntersectionEnterTrigger;
  37970. },
  37971. enumerable: true,
  37972. configurable: true
  37973. });
  37974. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  37975. get: function () {
  37976. return ActionManager._OnIntersectionExitTrigger;
  37977. },
  37978. enumerable: true,
  37979. configurable: true
  37980. });
  37981. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  37982. get: function () {
  37983. return ActionManager._OnKeyDownTrigger;
  37984. },
  37985. enumerable: true,
  37986. configurable: true
  37987. });
  37988. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  37989. get: function () {
  37990. return ActionManager._OnKeyUpTrigger;
  37991. },
  37992. enumerable: true,
  37993. configurable: true
  37994. });
  37995. // Methods
  37996. ActionManager.prototype.dispose = function () {
  37997. var index = this._scene._actionManagers.indexOf(this);
  37998. for (var i = 0; i < this.actions.length; i++) {
  37999. var action = this.actions[i];
  38000. ActionManager.Triggers[action.trigger]--;
  38001. if (ActionManager.Triggers[action.trigger] === 0) {
  38002. delete ActionManager.Triggers[action.trigger];
  38003. }
  38004. }
  38005. if (index > -1) {
  38006. this._scene._actionManagers.splice(index, 1);
  38007. }
  38008. };
  38009. ActionManager.prototype.getScene = function () {
  38010. return this._scene;
  38011. };
  38012. /**
  38013. * Does this action manager handles actions of any of the given triggers
  38014. * @param {number[]} triggers - the triggers to be tested
  38015. * @return {boolean} whether one (or more) of the triggers is handeled
  38016. */
  38017. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  38018. for (var index = 0; index < this.actions.length; index++) {
  38019. var action = this.actions[index];
  38020. if (triggers.indexOf(action.trigger) > -1) {
  38021. return true;
  38022. }
  38023. }
  38024. return false;
  38025. };
  38026. /**
  38027. * Does this action manager handles actions of a given trigger
  38028. * @param {number} trigger - the trigger to be tested
  38029. * @return {boolean} whether the trigger is handeled
  38030. */
  38031. ActionManager.prototype.hasSpecificTrigger = function (trigger) {
  38032. for (var index = 0; index < this.actions.length; index++) {
  38033. var action = this.actions[index];
  38034. if (action.trigger === trigger) {
  38035. return true;
  38036. }
  38037. }
  38038. return false;
  38039. };
  38040. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  38041. /**
  38042. * Does this action manager has pointer triggers
  38043. * @return {boolean} whether or not it has pointer triggers
  38044. */
  38045. get: function () {
  38046. for (var index = 0; index < this.actions.length; index++) {
  38047. var action = this.actions[index];
  38048. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  38049. return true;
  38050. }
  38051. }
  38052. return false;
  38053. },
  38054. enumerable: true,
  38055. configurable: true
  38056. });
  38057. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  38058. /**
  38059. * Does this action manager has pick triggers
  38060. * @return {boolean} whether or not it has pick triggers
  38061. */
  38062. get: function () {
  38063. for (var index = 0; index < this.actions.length; index++) {
  38064. var action = this.actions[index];
  38065. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  38066. return true;
  38067. }
  38068. }
  38069. return false;
  38070. },
  38071. enumerable: true,
  38072. configurable: true
  38073. });
  38074. Object.defineProperty(ActionManager, "HasTriggers", {
  38075. /**
  38076. * Does exist one action manager with at least one trigger
  38077. * @return {boolean} whether or not it exists one action manager with one trigger
  38078. **/
  38079. get: function () {
  38080. for (var t in ActionManager.Triggers) {
  38081. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38082. return true;
  38083. }
  38084. }
  38085. return false;
  38086. },
  38087. enumerable: true,
  38088. configurable: true
  38089. });
  38090. Object.defineProperty(ActionManager, "HasPickTriggers", {
  38091. /**
  38092. * Does exist one action manager with at least one pick trigger
  38093. * @return {boolean} whether or not it exists one action manager with one pick trigger
  38094. **/
  38095. get: function () {
  38096. for (var t in ActionManager.Triggers) {
  38097. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38098. var t_int = parseInt(t);
  38099. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  38100. return true;
  38101. }
  38102. }
  38103. }
  38104. return false;
  38105. },
  38106. enumerable: true,
  38107. configurable: true
  38108. });
  38109. /**
  38110. * Does exist one action manager that handles actions of a given trigger
  38111. * @param {number} trigger - the trigger to be tested
  38112. * @return {boolean} whether the trigger is handeled by at least one action manager
  38113. **/
  38114. ActionManager.HasSpecificTrigger = function (trigger) {
  38115. for (var t in ActionManager.Triggers) {
  38116. if (ActionManager.Triggers.hasOwnProperty(t)) {
  38117. var t_int = parseInt(t);
  38118. if (t_int === trigger) {
  38119. return true;
  38120. }
  38121. }
  38122. }
  38123. return false;
  38124. };
  38125. /**
  38126. * Registers an action to this action manager
  38127. * @param {BABYLON.Action} action - the action to be registered
  38128. * @return {BABYLON.Action} the action amended (prepared) after registration
  38129. */
  38130. ActionManager.prototype.registerAction = function (action) {
  38131. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  38132. if (this.getScene().actionManager !== this) {
  38133. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  38134. return null;
  38135. }
  38136. }
  38137. this.actions.push(action);
  38138. if (ActionManager.Triggers[action.trigger]) {
  38139. ActionManager.Triggers[action.trigger]++;
  38140. }
  38141. else {
  38142. ActionManager.Triggers[action.trigger] = 1;
  38143. }
  38144. action._actionManager = this;
  38145. action._prepare();
  38146. return action;
  38147. };
  38148. /**
  38149. * Process a specific trigger
  38150. * @param {number} trigger - the trigger to process
  38151. * @param evt {BABYLON.ActionEvent} the event details to be processed
  38152. */
  38153. ActionManager.prototype.processTrigger = function (trigger, evt) {
  38154. for (var index = 0; index < this.actions.length; index++) {
  38155. var action = this.actions[index];
  38156. if (action.trigger === trigger) {
  38157. if (trigger === ActionManager.OnKeyUpTrigger
  38158. || trigger === ActionManager.OnKeyDownTrigger) {
  38159. var parameter = action.getTriggerParameter();
  38160. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  38161. if (!parameter.toLowerCase) {
  38162. continue;
  38163. }
  38164. var lowerCase = parameter.toLowerCase();
  38165. if (lowerCase !== evt.sourceEvent.key) {
  38166. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  38167. var actualkey = String.fromCharCode(unicode).toLowerCase();
  38168. if (actualkey !== lowerCase) {
  38169. continue;
  38170. }
  38171. }
  38172. }
  38173. }
  38174. action._executeCurrent(evt);
  38175. }
  38176. }
  38177. };
  38178. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  38179. var properties = propertyPath.split(".");
  38180. for (var index = 0; index < properties.length - 1; index++) {
  38181. target = target[properties[index]];
  38182. }
  38183. return target;
  38184. };
  38185. ActionManager.prototype._getProperty = function (propertyPath) {
  38186. var properties = propertyPath.split(".");
  38187. return properties[properties.length - 1];
  38188. };
  38189. ActionManager.prototype.serialize = function (name) {
  38190. var root = {
  38191. children: [],
  38192. name: name,
  38193. type: 3,
  38194. properties: [] // Empty for root but required
  38195. };
  38196. for (var i = 0; i < this.actions.length; i++) {
  38197. var triggerObject = {
  38198. type: 0,
  38199. children: [],
  38200. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  38201. properties: []
  38202. };
  38203. var triggerOptions = this.actions[i].triggerOptions;
  38204. if (triggerOptions && typeof triggerOptions !== "number") {
  38205. if (triggerOptions.parameter instanceof BABYLON.Node) {
  38206. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  38207. }
  38208. else {
  38209. var parameter = {};
  38210. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  38211. if (triggerOptions.parameter.mesh) {
  38212. parameter._meshId = triggerOptions.parameter.mesh.id;
  38213. }
  38214. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  38215. }
  38216. }
  38217. // Serialize child action, recursively
  38218. this.actions[i].serialize(triggerObject);
  38219. // Add serialized trigger
  38220. root.children.push(triggerObject);
  38221. }
  38222. return root;
  38223. };
  38224. ActionManager.Parse = function (parsedActions, object, scene) {
  38225. var actionManager = new BABYLON.ActionManager(scene);
  38226. if (object === null)
  38227. scene.actionManager = actionManager;
  38228. else
  38229. object.actionManager = actionManager;
  38230. // instanciate a new object
  38231. var instanciate = function (name, params) {
  38232. var newInstance = Object.create(BABYLON[name].prototype);
  38233. newInstance.constructor.apply(newInstance, params);
  38234. return newInstance;
  38235. };
  38236. var parseParameter = function (name, value, target, propertyPath) {
  38237. if (propertyPath === null) {
  38238. // String, boolean or float
  38239. var floatValue = parseFloat(value);
  38240. if (value === "true" || value === "false")
  38241. return value === "true";
  38242. else
  38243. return isNaN(floatValue) ? value : floatValue;
  38244. }
  38245. var effectiveTarget = propertyPath.split(".");
  38246. var values = value.split(",");
  38247. // Get effective Target
  38248. for (var i = 0; i < effectiveTarget.length; i++) {
  38249. target = target[effectiveTarget[i]];
  38250. }
  38251. // Return appropriate value with its type
  38252. if (typeof (target) === "boolean")
  38253. return values[0] === "true";
  38254. if (typeof (target) === "string")
  38255. return values[0];
  38256. // Parameters with multiple values such as Vector3 etc.
  38257. var split = new Array();
  38258. for (var i = 0; i < values.length; i++)
  38259. split.push(parseFloat(values[i]));
  38260. if (target instanceof BABYLON.Vector3)
  38261. return BABYLON.Vector3.FromArray(split);
  38262. if (target instanceof BABYLON.Vector4)
  38263. return BABYLON.Vector4.FromArray(split);
  38264. if (target instanceof BABYLON.Color3)
  38265. return BABYLON.Color3.FromArray(split);
  38266. if (target instanceof BABYLON.Color4)
  38267. return BABYLON.Color4.FromArray(split);
  38268. return parseFloat(values[0]);
  38269. };
  38270. // traverse graph per trigger
  38271. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  38272. if (combineArray === void 0) { combineArray = null; }
  38273. if (parsedAction.detached)
  38274. return;
  38275. var parameters = new Array();
  38276. var target = null;
  38277. var propertyPath = null;
  38278. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  38279. // Parameters
  38280. if (parsedAction.type === 2)
  38281. parameters.push(actionManager);
  38282. else
  38283. parameters.push(trigger);
  38284. if (combine) {
  38285. var actions = new Array();
  38286. for (var j = 0; j < parsedAction.combine.length; j++) {
  38287. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  38288. }
  38289. parameters.push(actions);
  38290. }
  38291. else {
  38292. for (var i = 0; i < parsedAction.properties.length; i++) {
  38293. var value = parsedAction.properties[i].value;
  38294. var name = parsedAction.properties[i].name;
  38295. var targetType = parsedAction.properties[i].targetType;
  38296. if (name === "target")
  38297. if (targetType !== null && targetType === "SceneProperties")
  38298. value = target = scene;
  38299. else
  38300. value = target = scene.getNodeByName(value);
  38301. else if (name === "parent")
  38302. value = scene.getNodeByName(value);
  38303. else if (name === "sound")
  38304. value = scene.getSoundByName(value);
  38305. else if (name !== "propertyPath") {
  38306. if (parsedAction.type === 2 && name === "operator")
  38307. value = BABYLON.ValueCondition[value];
  38308. else
  38309. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  38310. }
  38311. else {
  38312. propertyPath = value;
  38313. }
  38314. parameters.push(value);
  38315. }
  38316. }
  38317. if (combineArray === null) {
  38318. parameters.push(condition);
  38319. }
  38320. else {
  38321. parameters.push(null);
  38322. }
  38323. // If interpolate value action
  38324. if (parsedAction.name === "InterpolateValueAction") {
  38325. var param = parameters[parameters.length - 2];
  38326. parameters[parameters.length - 1] = param;
  38327. parameters[parameters.length - 2] = condition;
  38328. }
  38329. // Action or condition(s) and not CombineAction
  38330. var newAction = instanciate(parsedAction.name, parameters);
  38331. if (newAction instanceof BABYLON.Condition && condition !== null) {
  38332. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  38333. if (action)
  38334. action.then(nothing);
  38335. else
  38336. actionManager.registerAction(nothing);
  38337. action = nothing;
  38338. }
  38339. if (combineArray === null) {
  38340. if (newAction instanceof BABYLON.Condition) {
  38341. condition = newAction;
  38342. newAction = action;
  38343. }
  38344. else {
  38345. condition = null;
  38346. if (action)
  38347. action.then(newAction);
  38348. else
  38349. actionManager.registerAction(newAction);
  38350. }
  38351. }
  38352. else {
  38353. combineArray.push(newAction);
  38354. }
  38355. for (var i = 0; i < parsedAction.children.length; i++)
  38356. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  38357. };
  38358. // triggers
  38359. for (var i = 0; i < parsedActions.children.length; i++) {
  38360. var triggerParams;
  38361. var trigger = parsedActions.children[i];
  38362. if (trigger.properties.length > 0) {
  38363. var param = trigger.properties[0].value;
  38364. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  38365. if (value._meshId) {
  38366. value.mesh = scene.getMeshByID(value._meshId);
  38367. }
  38368. triggerParams = { trigger: BABYLON.ActionManager[trigger.name], parameter: value };
  38369. }
  38370. else
  38371. triggerParams = BABYLON.ActionManager[trigger.name];
  38372. for (var j = 0; j < trigger.children.length; j++) {
  38373. if (!trigger.detached)
  38374. traverse(trigger.children[j], triggerParams, null, null);
  38375. }
  38376. }
  38377. };
  38378. ActionManager.GetTriggerName = function (trigger) {
  38379. switch (trigger) {
  38380. case 0: return "NothingTrigger";
  38381. case 1: return "OnPickTrigger";
  38382. case 2: return "OnLeftPickTrigger";
  38383. case 3: return "OnRightPickTrigger";
  38384. case 4: return "OnCenterPickTrigger";
  38385. case 5: return "OnPickDownTrigger";
  38386. case 6: return "OnPickUpTrigger";
  38387. case 7: return "OnLongPressTrigger";
  38388. case 8: return "OnPointerOverTrigger";
  38389. case 9: return "OnPointerOutTrigger";
  38390. case 10: return "OnEveryFrameTrigger";
  38391. case 11: return "OnIntersectionEnterTrigger";
  38392. case 12: return "OnIntersectionExitTrigger";
  38393. case 13: return "OnKeyDownTrigger";
  38394. case 14: return "OnKeyUpTrigger";
  38395. case 15: return "OnPickOutTrigger";
  38396. default: return "";
  38397. }
  38398. };
  38399. // Statics
  38400. ActionManager._NothingTrigger = 0;
  38401. ActionManager._OnPickTrigger = 1;
  38402. ActionManager._OnLeftPickTrigger = 2;
  38403. ActionManager._OnRightPickTrigger = 3;
  38404. ActionManager._OnCenterPickTrigger = 4;
  38405. ActionManager._OnPickDownTrigger = 5;
  38406. ActionManager._OnDoublePickTrigger = 6;
  38407. ActionManager._OnPickUpTrigger = 7;
  38408. ActionManager._OnLongPressTrigger = 8;
  38409. ActionManager._OnPointerOverTrigger = 9;
  38410. ActionManager._OnPointerOutTrigger = 10;
  38411. ActionManager._OnEveryFrameTrigger = 11;
  38412. ActionManager._OnIntersectionEnterTrigger = 12;
  38413. ActionManager._OnIntersectionExitTrigger = 13;
  38414. ActionManager._OnKeyDownTrigger = 14;
  38415. ActionManager._OnKeyUpTrigger = 15;
  38416. ActionManager._OnPickOutTrigger = 16;
  38417. ActionManager.Triggers = {};
  38418. return ActionManager;
  38419. }());
  38420. BABYLON.ActionManager = ActionManager;
  38421. })(BABYLON || (BABYLON = {}));
  38422. //# sourceMappingURL=babylon.actionManager.js.map
  38423. var BABYLON;
  38424. (function (BABYLON) {
  38425. var InterpolateValueAction = (function (_super) {
  38426. __extends(InterpolateValueAction, _super);
  38427. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  38428. if (duration === void 0) { duration = 1000; }
  38429. var _this = _super.call(this, triggerOptions, condition) || this;
  38430. _this.propertyPath = propertyPath;
  38431. _this.value = value;
  38432. _this.duration = duration;
  38433. _this.stopOtherAnimations = stopOtherAnimations;
  38434. _this.onInterpolationDone = onInterpolationDone;
  38435. _this._target = _this._effectiveTarget = target;
  38436. return _this;
  38437. }
  38438. InterpolateValueAction.prototype._prepare = function () {
  38439. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38440. this._property = this._getProperty(this.propertyPath);
  38441. };
  38442. InterpolateValueAction.prototype.execute = function () {
  38443. var scene = this._actionManager.getScene();
  38444. var keys = [
  38445. {
  38446. frame: 0,
  38447. value: this._effectiveTarget[this._property]
  38448. }, {
  38449. frame: 100,
  38450. value: this.value
  38451. }
  38452. ];
  38453. var dataType;
  38454. if (typeof this.value === "number") {
  38455. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  38456. }
  38457. else if (this.value instanceof BABYLON.Color3) {
  38458. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  38459. }
  38460. else if (this.value instanceof BABYLON.Vector3) {
  38461. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  38462. }
  38463. else if (this.value instanceof BABYLON.Matrix) {
  38464. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  38465. }
  38466. else if (this.value instanceof BABYLON.Quaternion) {
  38467. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  38468. }
  38469. else {
  38470. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  38471. return;
  38472. }
  38473. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  38474. animation.setKeys(keys);
  38475. if (this.stopOtherAnimations) {
  38476. scene.stopAnimation(this._effectiveTarget);
  38477. }
  38478. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, this.onInterpolationDone);
  38479. };
  38480. InterpolateValueAction.prototype.serialize = function (parent) {
  38481. return _super.prototype._serialize.call(this, {
  38482. name: "InterpolateValueAction",
  38483. properties: [
  38484. BABYLON.Action._GetTargetProperty(this._target),
  38485. { name: "propertyPath", value: this.propertyPath },
  38486. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  38487. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  38488. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  38489. ]
  38490. }, parent);
  38491. };
  38492. return InterpolateValueAction;
  38493. }(BABYLON.Action));
  38494. BABYLON.InterpolateValueAction = InterpolateValueAction;
  38495. })(BABYLON || (BABYLON = {}));
  38496. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  38497. var BABYLON;
  38498. (function (BABYLON) {
  38499. var SwitchBooleanAction = (function (_super) {
  38500. __extends(SwitchBooleanAction, _super);
  38501. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  38502. var _this = _super.call(this, triggerOptions, condition) || this;
  38503. _this.propertyPath = propertyPath;
  38504. _this._target = _this._effectiveTarget = target;
  38505. return _this;
  38506. }
  38507. SwitchBooleanAction.prototype._prepare = function () {
  38508. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38509. this._property = this._getProperty(this.propertyPath);
  38510. };
  38511. SwitchBooleanAction.prototype.execute = function () {
  38512. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  38513. };
  38514. SwitchBooleanAction.prototype.serialize = function (parent) {
  38515. return _super.prototype._serialize.call(this, {
  38516. name: "SwitchBooleanAction",
  38517. properties: [
  38518. BABYLON.Action._GetTargetProperty(this._target),
  38519. { name: "propertyPath", value: this.propertyPath }
  38520. ]
  38521. }, parent);
  38522. };
  38523. return SwitchBooleanAction;
  38524. }(BABYLON.Action));
  38525. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  38526. var SetStateAction = (function (_super) {
  38527. __extends(SetStateAction, _super);
  38528. function SetStateAction(triggerOptions, target, value, condition) {
  38529. var _this = _super.call(this, triggerOptions, condition) || this;
  38530. _this.value = value;
  38531. _this._target = target;
  38532. return _this;
  38533. }
  38534. SetStateAction.prototype.execute = function () {
  38535. this._target.state = this.value;
  38536. };
  38537. SetStateAction.prototype.serialize = function (parent) {
  38538. return _super.prototype._serialize.call(this, {
  38539. name: "SetStateAction",
  38540. properties: [
  38541. BABYLON.Action._GetTargetProperty(this._target),
  38542. { name: "value", value: this.value }
  38543. ]
  38544. }, parent);
  38545. };
  38546. return SetStateAction;
  38547. }(BABYLON.Action));
  38548. BABYLON.SetStateAction = SetStateAction;
  38549. var SetValueAction = (function (_super) {
  38550. __extends(SetValueAction, _super);
  38551. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  38552. var _this = _super.call(this, triggerOptions, condition) || this;
  38553. _this.propertyPath = propertyPath;
  38554. _this.value = value;
  38555. _this._target = _this._effectiveTarget = target;
  38556. return _this;
  38557. }
  38558. SetValueAction.prototype._prepare = function () {
  38559. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38560. this._property = this._getProperty(this.propertyPath);
  38561. };
  38562. SetValueAction.prototype.execute = function () {
  38563. this._effectiveTarget[this._property] = this.value;
  38564. if (this._target.markAsDirty) {
  38565. this._target.markAsDirty(this._property);
  38566. }
  38567. };
  38568. SetValueAction.prototype.serialize = function (parent) {
  38569. return _super.prototype._serialize.call(this, {
  38570. name: "SetValueAction",
  38571. properties: [
  38572. BABYLON.Action._GetTargetProperty(this._target),
  38573. { name: "propertyPath", value: this.propertyPath },
  38574. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38575. ]
  38576. }, parent);
  38577. };
  38578. return SetValueAction;
  38579. }(BABYLON.Action));
  38580. BABYLON.SetValueAction = SetValueAction;
  38581. var IncrementValueAction = (function (_super) {
  38582. __extends(IncrementValueAction, _super);
  38583. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  38584. var _this = _super.call(this, triggerOptions, condition) || this;
  38585. _this.propertyPath = propertyPath;
  38586. _this.value = value;
  38587. _this._target = _this._effectiveTarget = target;
  38588. return _this;
  38589. }
  38590. IncrementValueAction.prototype._prepare = function () {
  38591. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  38592. this._property = this._getProperty(this.propertyPath);
  38593. if (typeof this._effectiveTarget[this._property] !== "number") {
  38594. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  38595. }
  38596. };
  38597. IncrementValueAction.prototype.execute = function () {
  38598. this._effectiveTarget[this._property] += this.value;
  38599. if (this._target.markAsDirty) {
  38600. this._target.markAsDirty(this._property);
  38601. }
  38602. };
  38603. IncrementValueAction.prototype.serialize = function (parent) {
  38604. return _super.prototype._serialize.call(this, {
  38605. name: "IncrementValueAction",
  38606. properties: [
  38607. BABYLON.Action._GetTargetProperty(this._target),
  38608. { name: "propertyPath", value: this.propertyPath },
  38609. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  38610. ]
  38611. }, parent);
  38612. };
  38613. return IncrementValueAction;
  38614. }(BABYLON.Action));
  38615. BABYLON.IncrementValueAction = IncrementValueAction;
  38616. var PlayAnimationAction = (function (_super) {
  38617. __extends(PlayAnimationAction, _super);
  38618. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  38619. var _this = _super.call(this, triggerOptions, condition) || this;
  38620. _this.from = from;
  38621. _this.to = to;
  38622. _this.loop = loop;
  38623. _this._target = target;
  38624. return _this;
  38625. }
  38626. PlayAnimationAction.prototype._prepare = function () {
  38627. };
  38628. PlayAnimationAction.prototype.execute = function () {
  38629. var scene = this._actionManager.getScene();
  38630. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  38631. };
  38632. PlayAnimationAction.prototype.serialize = function (parent) {
  38633. return _super.prototype._serialize.call(this, {
  38634. name: "PlayAnimationAction",
  38635. properties: [
  38636. BABYLON.Action._GetTargetProperty(this._target),
  38637. { name: "from", value: String(this.from) },
  38638. { name: "to", value: String(this.to) },
  38639. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  38640. ]
  38641. }, parent);
  38642. };
  38643. return PlayAnimationAction;
  38644. }(BABYLON.Action));
  38645. BABYLON.PlayAnimationAction = PlayAnimationAction;
  38646. var StopAnimationAction = (function (_super) {
  38647. __extends(StopAnimationAction, _super);
  38648. function StopAnimationAction(triggerOptions, target, condition) {
  38649. var _this = _super.call(this, triggerOptions, condition) || this;
  38650. _this._target = target;
  38651. return _this;
  38652. }
  38653. StopAnimationAction.prototype._prepare = function () {
  38654. };
  38655. StopAnimationAction.prototype.execute = function () {
  38656. var scene = this._actionManager.getScene();
  38657. scene.stopAnimation(this._target);
  38658. };
  38659. StopAnimationAction.prototype.serialize = function (parent) {
  38660. return _super.prototype._serialize.call(this, {
  38661. name: "StopAnimationAction",
  38662. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  38663. }, parent);
  38664. };
  38665. return StopAnimationAction;
  38666. }(BABYLON.Action));
  38667. BABYLON.StopAnimationAction = StopAnimationAction;
  38668. var DoNothingAction = (function (_super) {
  38669. __extends(DoNothingAction, _super);
  38670. function DoNothingAction(triggerOptions, condition) {
  38671. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  38672. return _super.call(this, triggerOptions, condition) || this;
  38673. }
  38674. DoNothingAction.prototype.execute = function () {
  38675. };
  38676. DoNothingAction.prototype.serialize = function (parent) {
  38677. return _super.prototype._serialize.call(this, {
  38678. name: "DoNothingAction",
  38679. properties: []
  38680. }, parent);
  38681. };
  38682. return DoNothingAction;
  38683. }(BABYLON.Action));
  38684. BABYLON.DoNothingAction = DoNothingAction;
  38685. var CombineAction = (function (_super) {
  38686. __extends(CombineAction, _super);
  38687. function CombineAction(triggerOptions, children, condition) {
  38688. var _this = _super.call(this, triggerOptions, condition) || this;
  38689. _this.children = children;
  38690. return _this;
  38691. }
  38692. CombineAction.prototype._prepare = function () {
  38693. for (var index = 0; index < this.children.length; index++) {
  38694. this.children[index]._actionManager = this._actionManager;
  38695. this.children[index]._prepare();
  38696. }
  38697. };
  38698. CombineAction.prototype.execute = function (evt) {
  38699. for (var index = 0; index < this.children.length; index++) {
  38700. this.children[index].execute(evt);
  38701. }
  38702. };
  38703. CombineAction.prototype.serialize = function (parent) {
  38704. var serializationObject = _super.prototype._serialize.call(this, {
  38705. name: "CombineAction",
  38706. properties: [],
  38707. combine: []
  38708. }, parent);
  38709. for (var i = 0; i < this.children.length; i++) {
  38710. serializationObject.combine.push(this.children[i].serialize(null));
  38711. }
  38712. return serializationObject;
  38713. };
  38714. return CombineAction;
  38715. }(BABYLON.Action));
  38716. BABYLON.CombineAction = CombineAction;
  38717. var ExecuteCodeAction = (function (_super) {
  38718. __extends(ExecuteCodeAction, _super);
  38719. function ExecuteCodeAction(triggerOptions, func, condition) {
  38720. var _this = _super.call(this, triggerOptions, condition) || this;
  38721. _this.func = func;
  38722. return _this;
  38723. }
  38724. ExecuteCodeAction.prototype.execute = function (evt) {
  38725. this.func(evt);
  38726. };
  38727. return ExecuteCodeAction;
  38728. }(BABYLON.Action));
  38729. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  38730. var SetParentAction = (function (_super) {
  38731. __extends(SetParentAction, _super);
  38732. function SetParentAction(triggerOptions, target, parent, condition) {
  38733. var _this = _super.call(this, triggerOptions, condition) || this;
  38734. _this._target = target;
  38735. _this._parent = parent;
  38736. return _this;
  38737. }
  38738. SetParentAction.prototype._prepare = function () {
  38739. };
  38740. SetParentAction.prototype.execute = function () {
  38741. if (this._target.parent === this._parent) {
  38742. return;
  38743. }
  38744. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  38745. invertParentWorldMatrix.invert();
  38746. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  38747. this._target.parent = this._parent;
  38748. };
  38749. SetParentAction.prototype.serialize = function (parent) {
  38750. return _super.prototype._serialize.call(this, {
  38751. name: "SetParentAction",
  38752. properties: [
  38753. BABYLON.Action._GetTargetProperty(this._target),
  38754. BABYLON.Action._GetTargetProperty(this._parent),
  38755. ]
  38756. }, parent);
  38757. };
  38758. return SetParentAction;
  38759. }(BABYLON.Action));
  38760. BABYLON.SetParentAction = SetParentAction;
  38761. var PlaySoundAction = (function (_super) {
  38762. __extends(PlaySoundAction, _super);
  38763. function PlaySoundAction(triggerOptions, sound, condition) {
  38764. var _this = _super.call(this, triggerOptions, condition) || this;
  38765. _this._sound = sound;
  38766. return _this;
  38767. }
  38768. PlaySoundAction.prototype._prepare = function () {
  38769. };
  38770. PlaySoundAction.prototype.execute = function () {
  38771. if (this._sound !== undefined)
  38772. this._sound.play();
  38773. };
  38774. PlaySoundAction.prototype.serialize = function (parent) {
  38775. return _super.prototype._serialize.call(this, {
  38776. name: "PlaySoundAction",
  38777. properties: [{ name: "sound", value: this._sound.name }]
  38778. }, parent);
  38779. };
  38780. return PlaySoundAction;
  38781. }(BABYLON.Action));
  38782. BABYLON.PlaySoundAction = PlaySoundAction;
  38783. var StopSoundAction = (function (_super) {
  38784. __extends(StopSoundAction, _super);
  38785. function StopSoundAction(triggerOptions, sound, condition) {
  38786. var _this = _super.call(this, triggerOptions, condition) || this;
  38787. _this._sound = sound;
  38788. return _this;
  38789. }
  38790. StopSoundAction.prototype._prepare = function () {
  38791. };
  38792. StopSoundAction.prototype.execute = function () {
  38793. if (this._sound !== undefined)
  38794. this._sound.stop();
  38795. };
  38796. StopSoundAction.prototype.serialize = function (parent) {
  38797. return _super.prototype._serialize.call(this, {
  38798. name: "StopSoundAction",
  38799. properties: [{ name: "sound", value: this._sound.name }]
  38800. }, parent);
  38801. };
  38802. return StopSoundAction;
  38803. }(BABYLON.Action));
  38804. BABYLON.StopSoundAction = StopSoundAction;
  38805. })(BABYLON || (BABYLON = {}));
  38806. //# sourceMappingURL=babylon.directActions.js.map
  38807. var BABYLON;
  38808. (function (BABYLON) {
  38809. var SpriteManager = (function () {
  38810. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  38811. if (epsilon === void 0) { epsilon = 0.01; }
  38812. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  38813. this.name = name;
  38814. this.sprites = new Array();
  38815. this.renderingGroupId = 0;
  38816. this.layerMask = 0x0FFFFFFF;
  38817. this.fogEnabled = true;
  38818. this.isPickable = false;
  38819. /**
  38820. * An event triggered when the manager is disposed.
  38821. * @type {BABYLON.Observable}
  38822. */
  38823. this.onDisposeObservable = new BABYLON.Observable();
  38824. this._vertexBuffers = {};
  38825. this._capacity = capacity;
  38826. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  38827. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38828. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  38829. if (cellSize.width && cellSize.height) {
  38830. this.cellWidth = cellSize.width;
  38831. this.cellHeight = cellSize.height;
  38832. }
  38833. else if (cellSize !== undefined) {
  38834. this.cellWidth = cellSize;
  38835. this.cellHeight = cellSize;
  38836. }
  38837. else {
  38838. return;
  38839. }
  38840. this._epsilon = epsilon;
  38841. this._scene = scene;
  38842. this._scene.spriteManagers.push(this);
  38843. var indices = [];
  38844. var index = 0;
  38845. for (var count = 0; count < capacity; count++) {
  38846. indices.push(index);
  38847. indices.push(index + 1);
  38848. indices.push(index + 2);
  38849. indices.push(index);
  38850. indices.push(index + 2);
  38851. indices.push(index + 3);
  38852. index += 4;
  38853. }
  38854. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  38855. // VBO
  38856. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  38857. this._vertexData = new Float32Array(capacity * 16 * 4);
  38858. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  38859. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  38860. var options = this._buffer.createVertexBuffer("options", 4, 4);
  38861. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  38862. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  38863. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  38864. this._vertexBuffers["options"] = options;
  38865. this._vertexBuffers["cellInfo"] = cellInfo;
  38866. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  38867. // Effects
  38868. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  38869. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  38870. }
  38871. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  38872. set: function (callback) {
  38873. if (this._onDisposeObserver) {
  38874. this.onDisposeObservable.remove(this._onDisposeObserver);
  38875. }
  38876. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  38877. },
  38878. enumerable: true,
  38879. configurable: true
  38880. });
  38881. Object.defineProperty(SpriteManager.prototype, "texture", {
  38882. get: function () {
  38883. return this._spriteTexture;
  38884. },
  38885. set: function (value) {
  38886. this._spriteTexture = value;
  38887. },
  38888. enumerable: true,
  38889. configurable: true
  38890. });
  38891. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  38892. var arrayOffset = index * 16;
  38893. if (offsetX === 0)
  38894. offsetX = this._epsilon;
  38895. else if (offsetX === 1)
  38896. offsetX = 1 - this._epsilon;
  38897. if (offsetY === 0)
  38898. offsetY = this._epsilon;
  38899. else if (offsetY === 1)
  38900. offsetY = 1 - this._epsilon;
  38901. this._vertexData[arrayOffset] = sprite.position.x;
  38902. this._vertexData[arrayOffset + 1] = sprite.position.y;
  38903. this._vertexData[arrayOffset + 2] = sprite.position.z;
  38904. this._vertexData[arrayOffset + 3] = sprite.angle;
  38905. this._vertexData[arrayOffset + 4] = sprite.width;
  38906. this._vertexData[arrayOffset + 5] = sprite.height;
  38907. this._vertexData[arrayOffset + 6] = offsetX;
  38908. this._vertexData[arrayOffset + 7] = offsetY;
  38909. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  38910. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  38911. var offset = (sprite.cellIndex / rowSize) >> 0;
  38912. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  38913. this._vertexData[arrayOffset + 11] = offset;
  38914. // Color
  38915. this._vertexData[arrayOffset + 12] = sprite.color.r;
  38916. this._vertexData[arrayOffset + 13] = sprite.color.g;
  38917. this._vertexData[arrayOffset + 14] = sprite.color.b;
  38918. this._vertexData[arrayOffset + 15] = sprite.color.a;
  38919. };
  38920. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  38921. var count = Math.min(this._capacity, this.sprites.length);
  38922. var min = BABYLON.Vector3.Zero();
  38923. var max = BABYLON.Vector3.Zero();
  38924. var distance = Number.MAX_VALUE;
  38925. var currentSprite;
  38926. var cameraSpacePosition = BABYLON.Vector3.Zero();
  38927. var cameraView = camera.getViewMatrix();
  38928. for (var index = 0; index < count; index++) {
  38929. var sprite = this.sprites[index];
  38930. if (!sprite) {
  38931. continue;
  38932. }
  38933. if (predicate) {
  38934. if (!predicate(sprite)) {
  38935. continue;
  38936. }
  38937. }
  38938. else if (!sprite.isPickable) {
  38939. continue;
  38940. }
  38941. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  38942. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  38943. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  38944. if (ray.intersectsBoxMinMax(min, max)) {
  38945. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  38946. if (distance > currentDistance) {
  38947. distance = currentDistance;
  38948. currentSprite = sprite;
  38949. if (fastCheck) {
  38950. break;
  38951. }
  38952. }
  38953. }
  38954. }
  38955. if (currentSprite) {
  38956. var result = new BABYLON.PickingInfo();
  38957. result.hit = true;
  38958. result.pickedSprite = currentSprite;
  38959. result.distance = distance;
  38960. return result;
  38961. }
  38962. return null;
  38963. };
  38964. SpriteManager.prototype.render = function () {
  38965. // Check
  38966. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  38967. return;
  38968. var engine = this._scene.getEngine();
  38969. var baseSize = this._spriteTexture.getBaseSize();
  38970. // Sprites
  38971. var deltaTime = engine.getDeltaTime();
  38972. var max = Math.min(this._capacity, this.sprites.length);
  38973. var rowSize = baseSize.width / this.cellWidth;
  38974. var offset = 0;
  38975. for (var index = 0; index < max; index++) {
  38976. var sprite = this.sprites[index];
  38977. if (!sprite) {
  38978. continue;
  38979. }
  38980. sprite._animate(deltaTime);
  38981. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  38982. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  38983. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  38984. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  38985. }
  38986. this._buffer.update(this._vertexData);
  38987. // Render
  38988. var effect = this._effectBase;
  38989. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  38990. effect = this._effectFog;
  38991. }
  38992. engine.enableEffect(effect);
  38993. var viewMatrix = this._scene.getViewMatrix();
  38994. effect.setTexture("diffuseSampler", this._spriteTexture);
  38995. effect.setMatrix("view", viewMatrix);
  38996. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  38997. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  38998. // Fog
  38999. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  39000. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  39001. effect.setColor3("vFogColor", this._scene.fogColor);
  39002. }
  39003. // VBOs
  39004. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  39005. // Draw order
  39006. engine.setDepthFunctionToLessOrEqual();
  39007. effect.setBool("alphaTest", true);
  39008. engine.setColorWrite(false);
  39009. engine.draw(true, 0, max * 6);
  39010. engine.setColorWrite(true);
  39011. effect.setBool("alphaTest", false);
  39012. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  39013. engine.draw(true, 0, max * 6);
  39014. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  39015. };
  39016. SpriteManager.prototype.dispose = function () {
  39017. if (this._buffer) {
  39018. this._buffer.dispose();
  39019. this._buffer = null;
  39020. }
  39021. if (this._indexBuffer) {
  39022. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  39023. this._indexBuffer = null;
  39024. }
  39025. if (this._spriteTexture) {
  39026. this._spriteTexture.dispose();
  39027. this._spriteTexture = null;
  39028. }
  39029. // Remove from scene
  39030. var index = this._scene.spriteManagers.indexOf(this);
  39031. this._scene.spriteManagers.splice(index, 1);
  39032. // Callback
  39033. this.onDisposeObservable.notifyObservers(this);
  39034. this.onDisposeObservable.clear();
  39035. };
  39036. return SpriteManager;
  39037. }());
  39038. BABYLON.SpriteManager = SpriteManager;
  39039. })(BABYLON || (BABYLON = {}));
  39040. //# sourceMappingURL=babylon.spriteManager.js.map
  39041. var BABYLON;
  39042. (function (BABYLON) {
  39043. var Sprite = (function () {
  39044. function Sprite(name, manager) {
  39045. this.name = name;
  39046. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  39047. this.width = 1.0;
  39048. this.height = 1.0;
  39049. this.angle = 0;
  39050. this.cellIndex = 0;
  39051. this.invertU = 0;
  39052. this.invertV = 0;
  39053. this.animations = new Array();
  39054. this.isPickable = false;
  39055. this._animationStarted = false;
  39056. this._loopAnimation = false;
  39057. this._fromIndex = 0;
  39058. this._toIndex = 0;
  39059. this._delay = 0;
  39060. this._direction = 1;
  39061. this._frameCount = 0;
  39062. this._time = 0;
  39063. this._manager = manager;
  39064. this._manager.sprites.push(this);
  39065. this.position = BABYLON.Vector3.Zero();
  39066. }
  39067. Object.defineProperty(Sprite.prototype, "size", {
  39068. get: function () {
  39069. return this.width;
  39070. },
  39071. set: function (value) {
  39072. this.width = value;
  39073. this.height = value;
  39074. },
  39075. enumerable: true,
  39076. configurable: true
  39077. });
  39078. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  39079. this._fromIndex = from;
  39080. this._toIndex = to;
  39081. this._loopAnimation = loop;
  39082. this._delay = delay;
  39083. this._animationStarted = true;
  39084. this._direction = from < to ? 1 : -1;
  39085. this.cellIndex = from;
  39086. this._time = 0;
  39087. this._onAnimationEnd = onAnimationEnd;
  39088. };
  39089. Sprite.prototype.stopAnimation = function () {
  39090. this._animationStarted = false;
  39091. };
  39092. Sprite.prototype._animate = function (deltaTime) {
  39093. if (!this._animationStarted)
  39094. return;
  39095. this._time += deltaTime;
  39096. if (this._time > this._delay) {
  39097. this._time = this._time % this._delay;
  39098. this.cellIndex += this._direction;
  39099. if (this.cellIndex === this._toIndex) {
  39100. if (this._loopAnimation) {
  39101. this.cellIndex = this._fromIndex;
  39102. }
  39103. else {
  39104. this._animationStarted = false;
  39105. if (this._onAnimationEnd) {
  39106. this._onAnimationEnd();
  39107. }
  39108. if (this.disposeWhenFinishedAnimating) {
  39109. this.dispose();
  39110. }
  39111. }
  39112. }
  39113. }
  39114. };
  39115. Sprite.prototype.dispose = function () {
  39116. for (var i = 0; i < this._manager.sprites.length; i++) {
  39117. if (this._manager.sprites[i] == this) {
  39118. this._manager.sprites.splice(i, 1);
  39119. }
  39120. }
  39121. };
  39122. return Sprite;
  39123. }());
  39124. BABYLON.Sprite = Sprite;
  39125. })(BABYLON || (BABYLON = {}));
  39126. //# sourceMappingURL=babylon.sprite.js.map
  39127. var BABYLON;
  39128. (function (BABYLON) {
  39129. var IntersectionInfo = (function () {
  39130. function IntersectionInfo(bu, bv, distance) {
  39131. this.bu = bu;
  39132. this.bv = bv;
  39133. this.distance = distance;
  39134. this.faceId = 0;
  39135. this.subMeshId = 0;
  39136. }
  39137. return IntersectionInfo;
  39138. }());
  39139. BABYLON.IntersectionInfo = IntersectionInfo;
  39140. var PickingInfo = (function () {
  39141. function PickingInfo() {
  39142. this.hit = false;
  39143. this.distance = 0;
  39144. this.pickedPoint = null;
  39145. this.pickedMesh = null;
  39146. this.bu = 0;
  39147. this.bv = 0;
  39148. this.faceId = -1;
  39149. this.subMeshId = 0;
  39150. this.pickedSprite = null;
  39151. }
  39152. // Methods
  39153. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  39154. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  39155. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  39156. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39157. return null;
  39158. }
  39159. var indices = this.pickedMesh.getIndices();
  39160. var result;
  39161. if (useVerticesNormals) {
  39162. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  39163. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  39164. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  39165. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  39166. normal0 = normal0.scale(this.bu);
  39167. normal1 = normal1.scale(this.bv);
  39168. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  39169. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  39170. }
  39171. else {
  39172. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39173. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  39174. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  39175. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  39176. var p1p2 = vertex1.subtract(vertex2);
  39177. var p3p2 = vertex3.subtract(vertex2);
  39178. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  39179. }
  39180. if (useWorldCoordinates) {
  39181. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  39182. }
  39183. return BABYLON.Vector3.Normalize(result);
  39184. };
  39185. PickingInfo.prototype.getTextureCoordinates = function () {
  39186. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39187. return null;
  39188. }
  39189. var indices = this.pickedMesh.getIndices();
  39190. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  39191. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  39192. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  39193. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  39194. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  39195. uv1 = uv1.scale(this.bu);
  39196. uv2 = uv2.scale(this.bv);
  39197. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  39198. };
  39199. return PickingInfo;
  39200. }());
  39201. BABYLON.PickingInfo = PickingInfo;
  39202. })(BABYLON || (BABYLON = {}));
  39203. //# sourceMappingURL=babylon.pickingInfo.js.map
  39204. var BABYLON;
  39205. (function (BABYLON) {
  39206. var Ray = (function () {
  39207. function Ray(origin, direction, length) {
  39208. if (length === void 0) { length = Number.MAX_VALUE; }
  39209. this.origin = origin;
  39210. this.direction = direction;
  39211. this.length = length;
  39212. }
  39213. // Methods
  39214. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  39215. var d = 0.0;
  39216. var maxValue = Number.MAX_VALUE;
  39217. var inv;
  39218. var min;
  39219. var max;
  39220. var temp;
  39221. if (Math.abs(this.direction.x) < 0.0000001) {
  39222. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  39223. return false;
  39224. }
  39225. }
  39226. else {
  39227. inv = 1.0 / this.direction.x;
  39228. min = (minimum.x - this.origin.x) * inv;
  39229. max = (maximum.x - this.origin.x) * inv;
  39230. if (max === -Infinity) {
  39231. max = Infinity;
  39232. }
  39233. if (min > max) {
  39234. temp = min;
  39235. min = max;
  39236. max = temp;
  39237. }
  39238. d = Math.max(min, d);
  39239. maxValue = Math.min(max, maxValue);
  39240. if (d > maxValue) {
  39241. return false;
  39242. }
  39243. }
  39244. if (Math.abs(this.direction.y) < 0.0000001) {
  39245. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  39246. return false;
  39247. }
  39248. }
  39249. else {
  39250. inv = 1.0 / this.direction.y;
  39251. min = (minimum.y - this.origin.y) * inv;
  39252. max = (maximum.y - this.origin.y) * inv;
  39253. if (max === -Infinity) {
  39254. max = Infinity;
  39255. }
  39256. if (min > max) {
  39257. temp = min;
  39258. min = max;
  39259. max = temp;
  39260. }
  39261. d = Math.max(min, d);
  39262. maxValue = Math.min(max, maxValue);
  39263. if (d > maxValue) {
  39264. return false;
  39265. }
  39266. }
  39267. if (Math.abs(this.direction.z) < 0.0000001) {
  39268. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  39269. return false;
  39270. }
  39271. }
  39272. else {
  39273. inv = 1.0 / this.direction.z;
  39274. min = (minimum.z - this.origin.z) * inv;
  39275. max = (maximum.z - this.origin.z) * inv;
  39276. if (max === -Infinity) {
  39277. max = Infinity;
  39278. }
  39279. if (min > max) {
  39280. temp = min;
  39281. min = max;
  39282. max = temp;
  39283. }
  39284. d = Math.max(min, d);
  39285. maxValue = Math.min(max, maxValue);
  39286. if (d > maxValue) {
  39287. return false;
  39288. }
  39289. }
  39290. return true;
  39291. };
  39292. Ray.prototype.intersectsBox = function (box) {
  39293. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  39294. };
  39295. Ray.prototype.intersectsSphere = function (sphere) {
  39296. var x = sphere.center.x - this.origin.x;
  39297. var y = sphere.center.y - this.origin.y;
  39298. var z = sphere.center.z - this.origin.z;
  39299. var pyth = (x * x) + (y * y) + (z * z);
  39300. var rr = sphere.radius * sphere.radius;
  39301. if (pyth <= rr) {
  39302. return true;
  39303. }
  39304. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  39305. if (dot < 0.0) {
  39306. return false;
  39307. }
  39308. var temp = pyth - (dot * dot);
  39309. return temp <= rr;
  39310. };
  39311. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  39312. if (!this._edge1) {
  39313. this._edge1 = BABYLON.Vector3.Zero();
  39314. this._edge2 = BABYLON.Vector3.Zero();
  39315. this._pvec = BABYLON.Vector3.Zero();
  39316. this._tvec = BABYLON.Vector3.Zero();
  39317. this._qvec = BABYLON.Vector3.Zero();
  39318. }
  39319. vertex1.subtractToRef(vertex0, this._edge1);
  39320. vertex2.subtractToRef(vertex0, this._edge2);
  39321. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  39322. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  39323. if (det === 0) {
  39324. return null;
  39325. }
  39326. var invdet = 1 / det;
  39327. this.origin.subtractToRef(vertex0, this._tvec);
  39328. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  39329. if (bu < 0 || bu > 1.0) {
  39330. return null;
  39331. }
  39332. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  39333. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  39334. if (bv < 0 || bu + bv > 1.0) {
  39335. return null;
  39336. }
  39337. //check if the distance is longer than the predefined length.
  39338. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  39339. if (distance > this.length) {
  39340. return null;
  39341. }
  39342. return new BABYLON.IntersectionInfo(bu, bv, distance);
  39343. };
  39344. Ray.prototype.intersectsPlane = function (plane) {
  39345. var distance;
  39346. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  39347. if (Math.abs(result1) < 9.99999997475243E-07) {
  39348. return null;
  39349. }
  39350. else {
  39351. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  39352. distance = (-plane.d - result2) / result1;
  39353. if (distance < 0.0) {
  39354. if (distance < -9.99999997475243E-07) {
  39355. return null;
  39356. }
  39357. else {
  39358. return 0;
  39359. }
  39360. }
  39361. return distance;
  39362. }
  39363. };
  39364. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  39365. var tm = BABYLON.Tmp.Matrix[0];
  39366. mesh.getWorldMatrix().invertToRef(tm);
  39367. if (this._tmpRay) {
  39368. Ray.TransformToRef(this, tm, this._tmpRay);
  39369. }
  39370. else {
  39371. this._tmpRay = Ray.Transform(this, tm);
  39372. }
  39373. return mesh.intersects(this._tmpRay, fastCheck);
  39374. };
  39375. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  39376. if (results) {
  39377. results.length = 0;
  39378. }
  39379. else {
  39380. results = [];
  39381. }
  39382. for (var i = 0; i < meshes.length; i++) {
  39383. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  39384. if (pickInfo.hit) {
  39385. results.push(pickInfo);
  39386. }
  39387. }
  39388. results.sort(this._comparePickingInfo);
  39389. return results;
  39390. };
  39391. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  39392. if (pickingInfoA.distance < pickingInfoB.distance) {
  39393. return -1;
  39394. }
  39395. else if (pickingInfoA.distance > pickingInfoB.distance) {
  39396. return 1;
  39397. }
  39398. else {
  39399. return 0;
  39400. }
  39401. };
  39402. /**
  39403. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  39404. * @param sega the first point of the segment to test the intersection against
  39405. * @param segb the second point of the segment to test the intersection against
  39406. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  39407. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  39408. */
  39409. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  39410. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  39411. var u = segb.subtract(sega);
  39412. var v = rsegb.subtract(this.origin);
  39413. var w = sega.subtract(this.origin);
  39414. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  39415. var b = BABYLON.Vector3.Dot(u, v);
  39416. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  39417. var d = BABYLON.Vector3.Dot(u, w);
  39418. var e = BABYLON.Vector3.Dot(v, w);
  39419. var D = a * c - b * b; // always >= 0
  39420. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  39421. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  39422. // compute the line parameters of the two closest points
  39423. if (D < Ray.smallnum) {
  39424. sN = 0.0; // force using point P0 on segment S1
  39425. sD = 1.0; // to prevent possible division by 0.0 later
  39426. tN = e;
  39427. tD = c;
  39428. }
  39429. else {
  39430. sN = (b * e - c * d);
  39431. tN = (a * e - b * d);
  39432. if (sN < 0.0) {
  39433. sN = 0.0;
  39434. tN = e;
  39435. tD = c;
  39436. }
  39437. else if (sN > sD) {
  39438. sN = sD;
  39439. tN = e + b;
  39440. tD = c;
  39441. }
  39442. }
  39443. if (tN < 0.0) {
  39444. tN = 0.0;
  39445. // recompute sc for this edge
  39446. if (-d < 0.0) {
  39447. sN = 0.0;
  39448. }
  39449. else if (-d > a)
  39450. sN = sD;
  39451. else {
  39452. sN = -d;
  39453. sD = a;
  39454. }
  39455. }
  39456. else if (tN > tD) {
  39457. tN = tD;
  39458. // recompute sc for this edge
  39459. if ((-d + b) < 0.0) {
  39460. sN = 0;
  39461. }
  39462. else if ((-d + b) > a) {
  39463. sN = sD;
  39464. }
  39465. else {
  39466. sN = (-d + b);
  39467. sD = a;
  39468. }
  39469. }
  39470. // finally do the division to get sc and tc
  39471. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  39472. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  39473. // get the difference of the two closest points
  39474. var qtc = v.multiplyByFloats(tc, tc, tc);
  39475. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  39476. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  39477. if (isIntersected) {
  39478. return qtc.length();
  39479. }
  39480. return -1;
  39481. };
  39482. // Statics
  39483. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  39484. var start = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 0), viewportWidth, viewportHeight, world, view, projection);
  39485. var end = BABYLON.Vector3.Unproject(new BABYLON.Vector3(x, y, 1), viewportWidth, viewportHeight, world, view, projection);
  39486. var direction = end.subtract(start);
  39487. direction.normalize();
  39488. return new Ray(start, direction);
  39489. };
  39490. /**
  39491. * 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
  39492. * transformed to the given world matrix.
  39493. * @param origin The origin point
  39494. * @param end The end point
  39495. * @param world a matrix to transform the ray to. Default is the identity matrix.
  39496. */
  39497. Ray.CreateNewFromTo = function (origin, end, world) {
  39498. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  39499. var direction = end.subtract(origin);
  39500. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  39501. direction.normalize();
  39502. return Ray.Transform(new Ray(origin, direction, length), world);
  39503. };
  39504. Ray.Transform = function (ray, matrix) {
  39505. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  39506. Ray.TransformToRef(ray, matrix, result);
  39507. return result;
  39508. };
  39509. Ray.TransformToRef = function (ray, matrix, result) {
  39510. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  39511. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  39512. result.length = ray.length;
  39513. var dir = result.direction;
  39514. var len = dir.length();
  39515. if (!(len === 0 || len === 1)) {
  39516. var num = 1.0 / len;
  39517. dir.x *= num;
  39518. dir.y *= num;
  39519. dir.z *= num;
  39520. result.length *= len;
  39521. }
  39522. };
  39523. Ray.smallnum = 0.00000001;
  39524. Ray.rayl = 10e8;
  39525. return Ray;
  39526. }());
  39527. BABYLON.Ray = Ray;
  39528. })(BABYLON || (BABYLON = {}));
  39529. //# sourceMappingURL=babylon.ray.js.map
  39530. var BABYLON;
  39531. (function (BABYLON) {
  39532. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  39533. if (boxMin.x > sphereCenter.x + sphereRadius)
  39534. return false;
  39535. if (sphereCenter.x - sphereRadius > boxMax.x)
  39536. return false;
  39537. if (boxMin.y > sphereCenter.y + sphereRadius)
  39538. return false;
  39539. if (sphereCenter.y - sphereRadius > boxMax.y)
  39540. return false;
  39541. if (boxMin.z > sphereCenter.z + sphereRadius)
  39542. return false;
  39543. if (sphereCenter.z - sphereRadius > boxMax.z)
  39544. return false;
  39545. return true;
  39546. };
  39547. var getLowestRoot = (function () {
  39548. var result = { root: 0, found: false };
  39549. return function (a, b, c, maxR) {
  39550. result.root = 0;
  39551. result.found = false;
  39552. var determinant = b * b - 4.0 * a * c;
  39553. if (determinant < 0)
  39554. return result;
  39555. var sqrtD = Math.sqrt(determinant);
  39556. var r1 = (-b - sqrtD) / (2.0 * a);
  39557. var r2 = (-b + sqrtD) / (2.0 * a);
  39558. if (r1 > r2) {
  39559. var temp = r2;
  39560. r2 = r1;
  39561. r1 = temp;
  39562. }
  39563. if (r1 > 0 && r1 < maxR) {
  39564. result.root = r1;
  39565. result.found = true;
  39566. return result;
  39567. }
  39568. if (r2 > 0 && r2 < maxR) {
  39569. result.root = r2;
  39570. result.found = true;
  39571. return result;
  39572. }
  39573. return result;
  39574. };
  39575. })();
  39576. var Collider = (function () {
  39577. function Collider() {
  39578. this.radius = BABYLON.Vector3.One();
  39579. this.retry = 0;
  39580. this.basePointWorld = BABYLON.Vector3.Zero();
  39581. this.velocityWorld = BABYLON.Vector3.Zero();
  39582. this.normalizedVelocity = BABYLON.Vector3.Zero();
  39583. this._collisionPoint = BABYLON.Vector3.Zero();
  39584. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  39585. this._tempVector = BABYLON.Vector3.Zero();
  39586. this._tempVector2 = BABYLON.Vector3.Zero();
  39587. this._tempVector3 = BABYLON.Vector3.Zero();
  39588. this._tempVector4 = BABYLON.Vector3.Zero();
  39589. this._edge = BABYLON.Vector3.Zero();
  39590. this._baseToVertex = BABYLON.Vector3.Zero();
  39591. this._destinationPoint = BABYLON.Vector3.Zero();
  39592. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  39593. this._displacementVector = BABYLON.Vector3.Zero();
  39594. this._collisionMask = -1;
  39595. }
  39596. Object.defineProperty(Collider.prototype, "collisionMask", {
  39597. get: function () {
  39598. return this._collisionMask;
  39599. },
  39600. set: function (mask) {
  39601. this._collisionMask = !isNaN(mask) ? mask : -1;
  39602. },
  39603. enumerable: true,
  39604. configurable: true
  39605. });
  39606. // Methods
  39607. Collider.prototype._initialize = function (source, dir, e) {
  39608. this.velocity = dir;
  39609. BABYLON.Vector3.NormalizeToRef(dir, this.normalizedVelocity);
  39610. this.basePoint = source;
  39611. source.multiplyToRef(this.radius, this.basePointWorld);
  39612. dir.multiplyToRef(this.radius, this.velocityWorld);
  39613. this.velocityWorldLength = this.velocityWorld.length();
  39614. this.epsilon = e;
  39615. this.collisionFound = false;
  39616. };
  39617. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  39618. pa.subtractToRef(point, this._tempVector);
  39619. pb.subtractToRef(point, this._tempVector2);
  39620. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  39621. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39622. if (d < 0)
  39623. return false;
  39624. pc.subtractToRef(point, this._tempVector3);
  39625. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  39626. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39627. if (d < 0)
  39628. return false;
  39629. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  39630. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  39631. return d >= 0;
  39632. };
  39633. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  39634. var distance = BABYLON.Vector3.Distance(this.basePointWorld, sphereCenter);
  39635. var max = Math.max(this.radius.x, this.radius.y, this.radius.z);
  39636. if (distance > this.velocityWorldLength + max + sphereRadius) {
  39637. return false;
  39638. }
  39639. if (!intersectBoxAASphere(vecMin, vecMax, this.basePointWorld, this.velocityWorldLength + max))
  39640. return false;
  39641. return true;
  39642. };
  39643. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  39644. var t0;
  39645. var embeddedInPlane = false;
  39646. //defensive programming, actually not needed.
  39647. if (!trianglePlaneArray) {
  39648. trianglePlaneArray = [];
  39649. }
  39650. if (!trianglePlaneArray[faceIndex]) {
  39651. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  39652. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  39653. }
  39654. var trianglePlane = trianglePlaneArray[faceIndex];
  39655. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this.normalizedVelocity, 0))
  39656. return;
  39657. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this.basePoint);
  39658. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this.velocity);
  39659. if (normalDotVelocity == 0) {
  39660. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  39661. return;
  39662. embeddedInPlane = true;
  39663. t0 = 0;
  39664. }
  39665. else {
  39666. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39667. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  39668. if (t0 > t1) {
  39669. var temp = t1;
  39670. t1 = t0;
  39671. t0 = temp;
  39672. }
  39673. if (t0 > 1.0 || t1 < 0.0)
  39674. return;
  39675. if (t0 < 0)
  39676. t0 = 0;
  39677. if (t0 > 1.0)
  39678. t0 = 1.0;
  39679. }
  39680. this._collisionPoint.copyFromFloats(0, 0, 0);
  39681. var found = false;
  39682. var t = 1.0;
  39683. if (!embeddedInPlane) {
  39684. this.basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  39685. this.velocity.scaleToRef(t0, this._tempVector);
  39686. this._planeIntersectionPoint.addInPlace(this._tempVector);
  39687. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  39688. found = true;
  39689. t = t0;
  39690. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  39691. }
  39692. }
  39693. if (!found) {
  39694. var velocitySquaredLength = this.velocity.lengthSquared();
  39695. var a = velocitySquaredLength;
  39696. this.basePoint.subtractToRef(p1, this._tempVector);
  39697. var b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39698. var c = this._tempVector.lengthSquared() - 1.0;
  39699. var lowestRoot = getLowestRoot(a, b, c, t);
  39700. if (lowestRoot.found) {
  39701. t = lowestRoot.root;
  39702. found = true;
  39703. this._collisionPoint.copyFrom(p1);
  39704. }
  39705. this.basePoint.subtractToRef(p2, this._tempVector);
  39706. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39707. c = this._tempVector.lengthSquared() - 1.0;
  39708. lowestRoot = getLowestRoot(a, b, c, t);
  39709. if (lowestRoot.found) {
  39710. t = lowestRoot.root;
  39711. found = true;
  39712. this._collisionPoint.copyFrom(p2);
  39713. }
  39714. this.basePoint.subtractToRef(p3, this._tempVector);
  39715. b = 2.0 * (BABYLON.Vector3.Dot(this.velocity, this._tempVector));
  39716. c = this._tempVector.lengthSquared() - 1.0;
  39717. lowestRoot = getLowestRoot(a, b, c, t);
  39718. if (lowestRoot.found) {
  39719. t = lowestRoot.root;
  39720. found = true;
  39721. this._collisionPoint.copyFrom(p3);
  39722. }
  39723. p2.subtractToRef(p1, this._edge);
  39724. p1.subtractToRef(this.basePoint, this._baseToVertex);
  39725. var edgeSquaredLength = this._edge.lengthSquared();
  39726. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39727. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39728. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39729. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39730. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39731. lowestRoot = getLowestRoot(a, b, c, t);
  39732. if (lowestRoot.found) {
  39733. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39734. if (f >= 0.0 && f <= 1.0) {
  39735. t = lowestRoot.root;
  39736. found = true;
  39737. this._edge.scaleInPlace(f);
  39738. p1.addToRef(this._edge, this._collisionPoint);
  39739. }
  39740. }
  39741. p3.subtractToRef(p2, this._edge);
  39742. p2.subtractToRef(this.basePoint, this._baseToVertex);
  39743. edgeSquaredLength = this._edge.lengthSquared();
  39744. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39745. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39746. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39747. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39748. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39749. lowestRoot = getLowestRoot(a, b, c, t);
  39750. if (lowestRoot.found) {
  39751. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39752. if (f >= 0.0 && f <= 1.0) {
  39753. t = lowestRoot.root;
  39754. found = true;
  39755. this._edge.scaleInPlace(f);
  39756. p2.addToRef(this._edge, this._collisionPoint);
  39757. }
  39758. }
  39759. p1.subtractToRef(p3, this._edge);
  39760. p3.subtractToRef(this.basePoint, this._baseToVertex);
  39761. edgeSquaredLength = this._edge.lengthSquared();
  39762. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this.velocity);
  39763. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  39764. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  39765. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this.velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  39766. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  39767. lowestRoot = getLowestRoot(a, b, c, t);
  39768. if (lowestRoot.found) {
  39769. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  39770. if (f >= 0.0 && f <= 1.0) {
  39771. t = lowestRoot.root;
  39772. found = true;
  39773. this._edge.scaleInPlace(f);
  39774. p3.addToRef(this._edge, this._collisionPoint);
  39775. }
  39776. }
  39777. }
  39778. if (found) {
  39779. var distToCollision = t * this.velocity.length();
  39780. if (!this.collisionFound || distToCollision < this.nearestDistance) {
  39781. if (!this.intersectionPoint) {
  39782. this.intersectionPoint = this._collisionPoint.clone();
  39783. }
  39784. else {
  39785. this.intersectionPoint.copyFrom(this._collisionPoint);
  39786. }
  39787. this.nearestDistance = distToCollision;
  39788. this.collisionFound = true;
  39789. }
  39790. }
  39791. };
  39792. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  39793. for (var i = indexStart; i < indexEnd; i += 3) {
  39794. var p1 = pts[indices[i] - decal];
  39795. var p2 = pts[indices[i + 1] - decal];
  39796. var p3 = pts[indices[i + 2] - decal];
  39797. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  39798. }
  39799. };
  39800. Collider.prototype._getResponse = function (pos, vel) {
  39801. pos.addToRef(vel, this._destinationPoint);
  39802. vel.scaleInPlace((this.nearestDistance / vel.length()));
  39803. this.basePoint.addToRef(vel, pos);
  39804. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  39805. this._slidePlaneNormal.normalize();
  39806. this._slidePlaneNormal.scaleToRef(this.epsilon, this._displacementVector);
  39807. pos.addInPlace(this._displacementVector);
  39808. this.intersectionPoint.addInPlace(this._displacementVector);
  39809. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  39810. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  39811. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  39812. };
  39813. return Collider;
  39814. }());
  39815. BABYLON.Collider = Collider;
  39816. })(BABYLON || (BABYLON = {}));
  39817. //# sourceMappingURL=babylon.collider.js.map
  39818. var BABYLON;
  39819. (function (BABYLON) {
  39820. //WebWorker code will be inserted to this variable.
  39821. BABYLON.CollisionWorker = "";
  39822. var WorkerTaskType;
  39823. (function (WorkerTaskType) {
  39824. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  39825. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  39826. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  39827. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  39828. var WorkerReplyType;
  39829. (function (WorkerReplyType) {
  39830. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  39831. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  39832. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  39833. var CollisionCoordinatorWorker = (function () {
  39834. function CollisionCoordinatorWorker() {
  39835. var _this = this;
  39836. this._scaledPosition = BABYLON.Vector3.Zero();
  39837. this._scaledVelocity = BABYLON.Vector3.Zero();
  39838. this.onMeshUpdated = function (mesh) {
  39839. _this._addUpdateMeshesList[mesh.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(mesh);
  39840. };
  39841. this.onGeometryUpdated = function (geometry) {
  39842. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  39843. };
  39844. this._afterRender = function () {
  39845. if (!_this._init)
  39846. return;
  39847. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  39848. return;
  39849. }
  39850. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  39851. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  39852. if (_this._runningUpdated > 4) {
  39853. return;
  39854. }
  39855. ++_this._runningUpdated;
  39856. var payload = {
  39857. updatedMeshes: _this._addUpdateMeshesList,
  39858. updatedGeometries: _this._addUpdateGeometriesList,
  39859. removedGeometries: _this._toRemoveGeometryArray,
  39860. removedMeshes: _this._toRemoveMeshesArray
  39861. };
  39862. var message = {
  39863. payload: payload,
  39864. taskType: WorkerTaskType.UPDATE
  39865. };
  39866. var serializable = [];
  39867. for (var id in payload.updatedGeometries) {
  39868. if (payload.updatedGeometries.hasOwnProperty(id)) {
  39869. //prepare transferables
  39870. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  39871. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  39872. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  39873. }
  39874. }
  39875. _this._worker.postMessage(message, serializable);
  39876. _this._addUpdateMeshesList = {};
  39877. _this._addUpdateGeometriesList = {};
  39878. _this._toRemoveGeometryArray = [];
  39879. _this._toRemoveMeshesArray = [];
  39880. };
  39881. this._onMessageFromWorker = function (e) {
  39882. var returnData = e.data;
  39883. if (returnData.error != WorkerReplyType.SUCCESS) {
  39884. //TODO what errors can be returned from the worker?
  39885. BABYLON.Tools.Warn("error returned from worker!");
  39886. return;
  39887. }
  39888. switch (returnData.taskType) {
  39889. case WorkerTaskType.INIT:
  39890. _this._init = true;
  39891. //Update the worked with ALL of the scene's current state
  39892. _this._scene.meshes.forEach(function (mesh) {
  39893. _this.onMeshAdded(mesh);
  39894. });
  39895. _this._scene.getGeometries().forEach(function (geometry) {
  39896. _this.onGeometryAdded(geometry);
  39897. });
  39898. break;
  39899. case WorkerTaskType.UPDATE:
  39900. _this._runningUpdated--;
  39901. break;
  39902. case WorkerTaskType.COLLIDE:
  39903. _this._runningCollisionTask = false;
  39904. var returnPayload = returnData.payload;
  39905. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  39906. return;
  39907. _this._collisionsCallbackArray[returnPayload.collisionId](returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId));
  39908. //cleanup
  39909. _this._collisionsCallbackArray[returnPayload.collisionId] = undefined;
  39910. break;
  39911. }
  39912. };
  39913. this._collisionsCallbackArray = [];
  39914. this._init = false;
  39915. this._runningUpdated = 0;
  39916. this._runningCollisionTask = false;
  39917. this._addUpdateMeshesList = {};
  39918. this._addUpdateGeometriesList = {};
  39919. this._toRemoveGeometryArray = [];
  39920. this._toRemoveMeshesArray = [];
  39921. }
  39922. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  39923. if (!this._init)
  39924. return;
  39925. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  39926. return;
  39927. position.divideToRef(collider.radius, this._scaledPosition);
  39928. velocity.divideToRef(collider.radius, this._scaledVelocity);
  39929. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  39930. var payload = {
  39931. collider: {
  39932. position: this._scaledPosition.asArray(),
  39933. velocity: this._scaledVelocity.asArray(),
  39934. radius: collider.radius.asArray()
  39935. },
  39936. collisionId: collisionIndex,
  39937. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  39938. maximumRetry: maximumRetry
  39939. };
  39940. var message = {
  39941. payload: payload,
  39942. taskType: WorkerTaskType.COLLIDE
  39943. };
  39944. this._worker.postMessage(message);
  39945. };
  39946. CollisionCoordinatorWorker.prototype.init = function (scene) {
  39947. this._scene = scene;
  39948. this._scene.registerAfterRender(this._afterRender);
  39949. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  39950. this._worker = new Worker(workerUrl);
  39951. this._worker.onmessage = this._onMessageFromWorker;
  39952. var message = {
  39953. payload: {},
  39954. taskType: WorkerTaskType.INIT
  39955. };
  39956. this._worker.postMessage(message);
  39957. };
  39958. CollisionCoordinatorWorker.prototype.destroy = function () {
  39959. this._scene.unregisterAfterRender(this._afterRender);
  39960. this._worker.terminate();
  39961. };
  39962. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  39963. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  39964. this.onMeshUpdated(mesh);
  39965. };
  39966. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  39967. this._toRemoveMeshesArray.push(mesh.uniqueId);
  39968. };
  39969. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  39970. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  39971. geometry.onGeometryUpdated = this.onGeometryUpdated;
  39972. this.onGeometryUpdated(geometry);
  39973. };
  39974. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  39975. this._toRemoveGeometryArray.push(geometry.id);
  39976. };
  39977. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  39978. var submeshes = [];
  39979. if (mesh.subMeshes) {
  39980. submeshes = mesh.subMeshes.map(function (sm, idx) {
  39981. return {
  39982. position: idx,
  39983. verticesStart: sm.verticesStart,
  39984. verticesCount: sm.verticesCount,
  39985. indexStart: sm.indexStart,
  39986. indexCount: sm.indexCount,
  39987. hasMaterial: !!sm.getMaterial(),
  39988. sphereCenter: sm.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  39989. sphereRadius: sm.getBoundingInfo().boundingSphere.radiusWorld,
  39990. boxMinimum: sm.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  39991. boxMaximum: sm.getBoundingInfo().boundingBox.maximumWorld.asArray()
  39992. };
  39993. });
  39994. }
  39995. var geometryId = null;
  39996. if (mesh instanceof BABYLON.Mesh) {
  39997. geometryId = mesh.geometry ? mesh.geometry.id : null;
  39998. }
  39999. else if (mesh instanceof BABYLON.InstancedMesh) {
  40000. geometryId = (mesh.sourceMesh && mesh.sourceMesh.geometry) ? mesh.sourceMesh.geometry.id : null;
  40001. }
  40002. return {
  40003. uniqueId: mesh.uniqueId,
  40004. id: mesh.id,
  40005. name: mesh.name,
  40006. geometryId: geometryId,
  40007. sphereCenter: mesh.getBoundingInfo().boundingSphere.centerWorld.asArray(),
  40008. sphereRadius: mesh.getBoundingInfo().boundingSphere.radiusWorld,
  40009. boxMinimum: mesh.getBoundingInfo().boundingBox.minimumWorld.asArray(),
  40010. boxMaximum: mesh.getBoundingInfo().boundingBox.maximumWorld.asArray(),
  40011. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  40012. subMeshes: submeshes,
  40013. checkCollisions: mesh.checkCollisions
  40014. };
  40015. };
  40016. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  40017. return {
  40018. id: geometry.id,
  40019. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  40020. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  40021. indices: new Uint32Array(geometry.getIndices() || []),
  40022. };
  40023. };
  40024. return CollisionCoordinatorWorker;
  40025. }());
  40026. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  40027. var CollisionCoordinatorLegacy = (function () {
  40028. function CollisionCoordinatorLegacy() {
  40029. this._scaledPosition = BABYLON.Vector3.Zero();
  40030. this._scaledVelocity = BABYLON.Vector3.Zero();
  40031. this._finalPosition = BABYLON.Vector3.Zero();
  40032. }
  40033. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, velocity, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  40034. position.divideToRef(collider.radius, this._scaledPosition);
  40035. velocity.divideToRef(collider.radius, this._scaledVelocity);
  40036. collider.collidedMesh = null;
  40037. collider.retry = 0;
  40038. collider.initialVelocity = this._scaledVelocity;
  40039. collider.initialPosition = this._scaledPosition;
  40040. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  40041. this._finalPosition.multiplyInPlace(collider.radius);
  40042. //run the callback
  40043. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  40044. };
  40045. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  40046. this._scene = scene;
  40047. };
  40048. CollisionCoordinatorLegacy.prototype.destroy = function () {
  40049. //Legacy need no destruction method.
  40050. };
  40051. //No update in legacy mode
  40052. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  40053. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  40054. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  40055. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  40056. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  40057. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  40058. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  40059. if (excludedMesh === void 0) { excludedMesh = null; }
  40060. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  40061. if (collider.retry >= maximumRetry) {
  40062. finalPosition.copyFrom(position);
  40063. return;
  40064. }
  40065. // Check if this is a mesh else camera or -1
  40066. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  40067. collider._initialize(position, velocity, closeDistance);
  40068. // Check all meshes
  40069. for (var index = 0; index < this._scene.meshes.length; index++) {
  40070. var mesh = this._scene.meshes[index];
  40071. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  40072. mesh._checkCollision(collider);
  40073. }
  40074. }
  40075. if (!collider.collisionFound) {
  40076. position.addToRef(velocity, finalPosition);
  40077. return;
  40078. }
  40079. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  40080. collider._getResponse(position, velocity);
  40081. }
  40082. if (velocity.length() <= closeDistance) {
  40083. finalPosition.copyFrom(position);
  40084. return;
  40085. }
  40086. collider.retry++;
  40087. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  40088. };
  40089. return CollisionCoordinatorLegacy;
  40090. }());
  40091. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  40092. })(BABYLON || (BABYLON = {}));
  40093. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  40094. var BABYLON;
  40095. (function (BABYLON) {
  40096. var Particle = (function () {
  40097. function Particle() {
  40098. this.position = BABYLON.Vector3.Zero();
  40099. this.direction = BABYLON.Vector3.Zero();
  40100. this.color = new BABYLON.Color4(0, 0, 0, 0);
  40101. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  40102. this.lifeTime = 1.0;
  40103. this.age = 0;
  40104. this.size = 0;
  40105. this.angle = 0;
  40106. this.angularSpeed = 0;
  40107. }
  40108. Particle.prototype.copyTo = function (other) {
  40109. other.position.copyFrom(this.position);
  40110. other.direction.copyFrom(this.direction);
  40111. other.color.copyFrom(this.color);
  40112. other.colorStep.copyFrom(this.colorStep);
  40113. other.lifeTime = this.lifeTime;
  40114. other.age = this.age;
  40115. other.size = this.size;
  40116. other.angle = this.angle;
  40117. other.angularSpeed = this.angularSpeed;
  40118. };
  40119. return Particle;
  40120. }());
  40121. BABYLON.Particle = Particle;
  40122. })(BABYLON || (BABYLON = {}));
  40123. //# sourceMappingURL=babylon.particle.js.map
  40124. var BABYLON;
  40125. (function (BABYLON) {
  40126. var randomNumber = function (min, max) {
  40127. if (min === max) {
  40128. return (min);
  40129. }
  40130. var random = Math.random();
  40131. return ((random * (max - min)) + min);
  40132. };
  40133. var ParticleSystem = (function () {
  40134. function ParticleSystem(name, capacity, scene, customEffect) {
  40135. var _this = this;
  40136. this.name = name;
  40137. // Members
  40138. this.animations = [];
  40139. this.renderingGroupId = 0;
  40140. this.emitter = null;
  40141. this.emitRate = 10;
  40142. this.manualEmitCount = -1;
  40143. this.updateSpeed = 0.01;
  40144. this.targetStopDuration = 0;
  40145. this.disposeOnStop = false;
  40146. this.minEmitPower = 1;
  40147. this.maxEmitPower = 1;
  40148. this.minLifeTime = 1;
  40149. this.maxLifeTime = 1;
  40150. this.minSize = 1;
  40151. this.maxSize = 1;
  40152. this.minAngularSpeed = 0;
  40153. this.maxAngularSpeed = 0;
  40154. this.layerMask = 0x0FFFFFFF;
  40155. this.customShader = null;
  40156. this.preventAutoStart = false;
  40157. /**
  40158. * An event triggered when the system is disposed.
  40159. * @type {BABYLON.Observable}
  40160. */
  40161. this.onDisposeObservable = new BABYLON.Observable();
  40162. this.onAnimationEnd = null;
  40163. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  40164. this.forceDepthWrite = false;
  40165. this.gravity = BABYLON.Vector3.Zero();
  40166. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  40167. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  40168. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  40169. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  40170. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40171. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40172. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  40173. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  40174. this.particles = new Array();
  40175. this._stockParticles = new Array();
  40176. this._newPartsExcess = 0;
  40177. this._vertexBuffers = {};
  40178. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  40179. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  40180. this._scaledDirection = BABYLON.Vector3.Zero();
  40181. this._scaledGravity = BABYLON.Vector3.Zero();
  40182. this._currentRenderId = -1;
  40183. this._started = false;
  40184. this._stopped = false;
  40185. this._actualFrame = 0;
  40186. this.id = name;
  40187. this._capacity = capacity;
  40188. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40189. this._customEffect = customEffect;
  40190. scene.particleSystems.push(this);
  40191. var indices = [];
  40192. var index = 0;
  40193. for (var count = 0; count < capacity; count++) {
  40194. indices.push(index);
  40195. indices.push(index + 1);
  40196. indices.push(index + 2);
  40197. indices.push(index);
  40198. indices.push(index + 2);
  40199. indices.push(index + 3);
  40200. index += 4;
  40201. }
  40202. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  40203. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  40204. this._vertexData = new Float32Array(capacity * 11 * 4);
  40205. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 11);
  40206. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  40207. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  40208. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  40209. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  40210. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  40211. this._vertexBuffers["options"] = options;
  40212. // Default behaviors
  40213. this.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  40214. var randX = randomNumber(_this.direction1.x, _this.direction2.x);
  40215. var randY = randomNumber(_this.direction1.y, _this.direction2.y);
  40216. var randZ = randomNumber(_this.direction1.z, _this.direction2.z);
  40217. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  40218. };
  40219. this.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  40220. var randX = randomNumber(_this.minEmitBox.x, _this.maxEmitBox.x);
  40221. var randY = randomNumber(_this.minEmitBox.y, _this.maxEmitBox.y);
  40222. var randZ = randomNumber(_this.minEmitBox.z, _this.maxEmitBox.z);
  40223. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  40224. };
  40225. this.updateFunction = function (particles) {
  40226. for (var index = 0; index < particles.length; index++) {
  40227. var particle = particles[index];
  40228. particle.age += _this._scaledUpdateSpeed;
  40229. if (particle.age >= particle.lifeTime) {
  40230. _this.recycleParticle(particle);
  40231. index--;
  40232. continue;
  40233. }
  40234. else {
  40235. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  40236. particle.color.addInPlace(_this._scaledColorStep);
  40237. if (particle.color.a < 0)
  40238. particle.color.a = 0;
  40239. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  40240. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  40241. particle.position.addInPlace(_this._scaledDirection);
  40242. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  40243. particle.direction.addInPlace(_this._scaledGravity);
  40244. }
  40245. }
  40246. };
  40247. }
  40248. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  40249. set: function (callback) {
  40250. if (this._onDisposeObserver) {
  40251. this.onDisposeObservable.remove(this._onDisposeObserver);
  40252. }
  40253. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  40254. },
  40255. enumerable: true,
  40256. configurable: true
  40257. });
  40258. ParticleSystem.prototype.recycleParticle = function (particle) {
  40259. var lastParticle = this.particles.pop();
  40260. if (lastParticle !== particle) {
  40261. lastParticle.copyTo(particle);
  40262. this._stockParticles.push(lastParticle);
  40263. }
  40264. };
  40265. ParticleSystem.prototype.getCapacity = function () {
  40266. return this._capacity;
  40267. };
  40268. ParticleSystem.prototype.isAlive = function () {
  40269. return this._alive;
  40270. };
  40271. ParticleSystem.prototype.isStarted = function () {
  40272. return this._started;
  40273. };
  40274. ParticleSystem.prototype.start = function () {
  40275. this._started = true;
  40276. this._stopped = false;
  40277. this._actualFrame = 0;
  40278. };
  40279. ParticleSystem.prototype.stop = function () {
  40280. this._stopped = true;
  40281. };
  40282. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  40283. var offset = index * 11;
  40284. this._vertexData[offset] = particle.position.x;
  40285. this._vertexData[offset + 1] = particle.position.y;
  40286. this._vertexData[offset + 2] = particle.position.z;
  40287. this._vertexData[offset + 3] = particle.color.r;
  40288. this._vertexData[offset + 4] = particle.color.g;
  40289. this._vertexData[offset + 5] = particle.color.b;
  40290. this._vertexData[offset + 6] = particle.color.a;
  40291. this._vertexData[offset + 7] = particle.angle;
  40292. this._vertexData[offset + 8] = particle.size;
  40293. this._vertexData[offset + 9] = offsetX;
  40294. this._vertexData[offset + 10] = offsetY;
  40295. };
  40296. ParticleSystem.prototype._update = function (newParticles) {
  40297. // Update current
  40298. this._alive = this.particles.length > 0;
  40299. this.updateFunction(this.particles);
  40300. // Add new ones
  40301. var worldMatrix;
  40302. if (this.emitter.position) {
  40303. var emitterMesh = this.emitter;
  40304. worldMatrix = emitterMesh.getWorldMatrix();
  40305. }
  40306. else {
  40307. var emitterPosition = this.emitter;
  40308. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  40309. }
  40310. var particle;
  40311. for (var index = 0; index < newParticles; index++) {
  40312. if (this.particles.length === this._capacity) {
  40313. break;
  40314. }
  40315. if (this._stockParticles.length !== 0) {
  40316. particle = this._stockParticles.pop();
  40317. particle.age = 0;
  40318. }
  40319. else {
  40320. particle = new BABYLON.Particle();
  40321. }
  40322. this.particles.push(particle);
  40323. var emitPower = randomNumber(this.minEmitPower, this.maxEmitPower);
  40324. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  40325. particle.lifeTime = randomNumber(this.minLifeTime, this.maxLifeTime);
  40326. particle.size = randomNumber(this.minSize, this.maxSize);
  40327. particle.angularSpeed = randomNumber(this.minAngularSpeed, this.maxAngularSpeed);
  40328. this.startPositionFunction(worldMatrix, particle.position, particle);
  40329. var step = randomNumber(0, 1.0);
  40330. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  40331. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  40332. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  40333. }
  40334. };
  40335. ParticleSystem.prototype._getEffect = function () {
  40336. if (this._customEffect) {
  40337. return this._customEffect;
  40338. }
  40339. ;
  40340. var defines = [];
  40341. if (this._scene.clipPlane) {
  40342. defines.push("#define CLIPPLANE");
  40343. }
  40344. // Effect
  40345. var join = defines.join("\n");
  40346. if (this._cachedDefines !== join) {
  40347. this._cachedDefines = join;
  40348. this._effect = this._scene.getEngine().createEffect("particles", [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"], ["invView", "view", "projection", "vClipPlane", "textureMask"], ["diffuseSampler"], join);
  40349. }
  40350. return this._effect;
  40351. };
  40352. ParticleSystem.prototype.animate = function () {
  40353. if (!this._started)
  40354. return;
  40355. var effect = this._getEffect();
  40356. // Check
  40357. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  40358. return;
  40359. if (this._currentRenderId === this._scene.getRenderId()) {
  40360. return;
  40361. }
  40362. this._currentRenderId = this._scene.getRenderId();
  40363. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  40364. // determine the number of particles we need to create
  40365. var newParticles;
  40366. if (this.manualEmitCount > -1) {
  40367. newParticles = this.manualEmitCount;
  40368. this._newPartsExcess = 0;
  40369. this.manualEmitCount = 0;
  40370. }
  40371. else {
  40372. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  40373. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  40374. }
  40375. if (this._newPartsExcess > 1.0) {
  40376. newParticles += this._newPartsExcess >> 0;
  40377. this._newPartsExcess -= this._newPartsExcess >> 0;
  40378. }
  40379. this._alive = false;
  40380. if (!this._stopped) {
  40381. this._actualFrame += this._scaledUpdateSpeed;
  40382. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  40383. this.stop();
  40384. }
  40385. else {
  40386. newParticles = 0;
  40387. }
  40388. this._update(newParticles);
  40389. // Stopped?
  40390. if (this._stopped) {
  40391. if (!this._alive) {
  40392. this._started = false;
  40393. if (this.onAnimationEnd) {
  40394. this.onAnimationEnd();
  40395. }
  40396. if (this.disposeOnStop) {
  40397. this._scene._toBeDisposed.push(this);
  40398. }
  40399. }
  40400. }
  40401. // Update VBO
  40402. var offset = 0;
  40403. for (var index = 0; index < this.particles.length; index++) {
  40404. var particle = this.particles[index];
  40405. this._appendParticleVertex(offset++, particle, 0, 0);
  40406. this._appendParticleVertex(offset++, particle, 1, 0);
  40407. this._appendParticleVertex(offset++, particle, 1, 1);
  40408. this._appendParticleVertex(offset++, particle, 0, 1);
  40409. }
  40410. this._vertexBuffer.update(this._vertexData);
  40411. };
  40412. ParticleSystem.prototype.render = function () {
  40413. var effect = this._getEffect();
  40414. // Check
  40415. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady() || !this.particles.length)
  40416. return 0;
  40417. var engine = this._scene.getEngine();
  40418. // Render
  40419. engine.enableEffect(effect);
  40420. engine.setState(false);
  40421. var viewMatrix = this._scene.getViewMatrix();
  40422. effect.setTexture("diffuseSampler", this.particleTexture);
  40423. effect.setMatrix("view", viewMatrix);
  40424. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  40425. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  40426. if (this._scene.clipPlane) {
  40427. var clipPlane = this._scene.clipPlane;
  40428. var invView = viewMatrix.clone();
  40429. invView.invert();
  40430. effect.setMatrix("invView", invView);
  40431. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  40432. }
  40433. // VBOs
  40434. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40435. // Draw order
  40436. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  40437. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  40438. }
  40439. else {
  40440. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  40441. }
  40442. if (this.forceDepthWrite) {
  40443. engine.setDepthWrite(true);
  40444. }
  40445. engine.draw(true, 0, this.particles.length * 6);
  40446. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40447. return this.particles.length;
  40448. };
  40449. ParticleSystem.prototype.dispose = function () {
  40450. if (this._vertexBuffer) {
  40451. this._vertexBuffer.dispose();
  40452. this._vertexBuffer = null;
  40453. }
  40454. if (this._indexBuffer) {
  40455. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40456. this._indexBuffer = null;
  40457. }
  40458. if (this.particleTexture) {
  40459. this.particleTexture.dispose();
  40460. this.particleTexture = null;
  40461. }
  40462. // Remove from scene
  40463. var index = this._scene.particleSystems.indexOf(this);
  40464. if (index > -1) {
  40465. this._scene.particleSystems.splice(index, 1);
  40466. }
  40467. // Callback
  40468. this.onDisposeObservable.notifyObservers(this);
  40469. this.onDisposeObservable.clear();
  40470. };
  40471. // Clone
  40472. ParticleSystem.prototype.clone = function (name, newEmitter) {
  40473. var custom = null;
  40474. var program = null;
  40475. if (this.customShader != null) {
  40476. program = this.customShader;
  40477. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40478. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40479. }
  40480. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  40481. result.customShader = program;
  40482. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  40483. if (newEmitter === undefined) {
  40484. newEmitter = this.emitter;
  40485. }
  40486. result.emitter = newEmitter;
  40487. if (this.particleTexture) {
  40488. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  40489. }
  40490. if (!this.preventAutoStart) {
  40491. result.start();
  40492. }
  40493. return result;
  40494. };
  40495. ParticleSystem.prototype.serialize = function () {
  40496. var serializationObject = {};
  40497. serializationObject.name = this.name;
  40498. serializationObject.id = this.id;
  40499. // Emitter
  40500. if (this.emitter.position) {
  40501. var emitterMesh = this.emitter;
  40502. serializationObject.emitterId = emitterMesh.id;
  40503. }
  40504. else {
  40505. var emitterPosition = this.emitter;
  40506. serializationObject.emitter = emitterPosition.asArray();
  40507. }
  40508. serializationObject.capacity = this.getCapacity();
  40509. if (this.particleTexture) {
  40510. serializationObject.textureName = this.particleTexture.name;
  40511. }
  40512. // Animations
  40513. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  40514. // Particle system
  40515. serializationObject.minAngularSpeed = this.minAngularSpeed;
  40516. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  40517. serializationObject.minSize = this.minSize;
  40518. serializationObject.maxSize = this.maxSize;
  40519. serializationObject.minEmitPower = this.minEmitPower;
  40520. serializationObject.maxEmitPower = this.maxEmitPower;
  40521. serializationObject.minLifeTime = this.minLifeTime;
  40522. serializationObject.maxLifeTime = this.maxLifeTime;
  40523. serializationObject.emitRate = this.emitRate;
  40524. serializationObject.minEmitBox = this.minEmitBox.asArray();
  40525. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  40526. serializationObject.gravity = this.gravity.asArray();
  40527. serializationObject.direction1 = this.direction1.asArray();
  40528. serializationObject.direction2 = this.direction2.asArray();
  40529. serializationObject.color1 = this.color1.asArray();
  40530. serializationObject.color2 = this.color2.asArray();
  40531. serializationObject.colorDead = this.colorDead.asArray();
  40532. serializationObject.updateSpeed = this.updateSpeed;
  40533. serializationObject.targetStopDuration = this.targetStopDuration;
  40534. serializationObject.textureMask = this.textureMask.asArray();
  40535. serializationObject.blendMode = this.blendMode;
  40536. serializationObject.customShader = this.customShader;
  40537. serializationObject.preventAutoStart = this.preventAutoStart;
  40538. return serializationObject;
  40539. };
  40540. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  40541. var name = parsedParticleSystem.name;
  40542. var custom = null;
  40543. var program = null;
  40544. if (parsedParticleSystem.customShader) {
  40545. program = parsedParticleSystem.customShader;
  40546. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  40547. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  40548. }
  40549. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom);
  40550. particleSystem.customShader = program;
  40551. if (parsedParticleSystem.id) {
  40552. particleSystem.id = parsedParticleSystem.id;
  40553. }
  40554. // Auto start
  40555. if (parsedParticleSystem.preventAutoStart) {
  40556. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  40557. }
  40558. // Texture
  40559. if (parsedParticleSystem.textureName) {
  40560. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  40561. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  40562. }
  40563. // Emitter
  40564. if (parsedParticleSystem.emitterId) {
  40565. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  40566. }
  40567. else {
  40568. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  40569. }
  40570. // Animations
  40571. if (parsedParticleSystem.animations) {
  40572. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  40573. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  40574. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  40575. }
  40576. }
  40577. if (parsedParticleSystem.autoAnimate) {
  40578. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  40579. }
  40580. // Particle system
  40581. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  40582. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  40583. particleSystem.minSize = parsedParticleSystem.minSize;
  40584. particleSystem.maxSize = parsedParticleSystem.maxSize;
  40585. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  40586. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  40587. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  40588. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  40589. particleSystem.emitRate = parsedParticleSystem.emitRate;
  40590. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  40591. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  40592. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  40593. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  40594. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  40595. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  40596. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  40597. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  40598. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  40599. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  40600. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  40601. particleSystem.blendMode = parsedParticleSystem.blendMode;
  40602. if (!particleSystem.preventAutoStart) {
  40603. particleSystem.start();
  40604. }
  40605. return particleSystem;
  40606. };
  40607. // Statics
  40608. ParticleSystem.BLENDMODE_ONEONE = 0;
  40609. ParticleSystem.BLENDMODE_STANDARD = 1;
  40610. return ParticleSystem;
  40611. }());
  40612. BABYLON.ParticleSystem = ParticleSystem;
  40613. })(BABYLON || (BABYLON = {}));
  40614. //# sourceMappingURL=babylon.particleSystem.js.map
  40615. var BABYLON;
  40616. (function (BABYLON) {
  40617. var SolidParticle = (function () {
  40618. /**
  40619. * Creates a Solid Particle object.
  40620. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  40621. * `particleIndex` (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  40622. * `positionIndex` (integer) is the starting index of the particle vertices in the SPS "positions" array.
  40623. * `model` (ModelShape) is a reference to the model shape on what the particle is designed.
  40624. * `shapeId` (integer) is the model shape identifier in the SPS.
  40625. * `idxInShape` (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  40626. * `modelBoundingInfo` is the reference to the model BoundingInfo used for intersection computations.
  40627. */
  40628. function SolidParticle(particleIndex, positionIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  40629. this.idx = 0; // particle global index
  40630. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0); // color
  40631. this.position = BABYLON.Vector3.Zero(); // position
  40632. this.rotation = BABYLON.Vector3.Zero(); // rotation
  40633. this.scaling = BABYLON.Vector3.One(); // scaling
  40634. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0); // uvs
  40635. this.velocity = BABYLON.Vector3.Zero(); // velocity
  40636. this.alive = true; // alive
  40637. this.isVisible = true; // visibility
  40638. this._pos = 0; // index of this particle in the global "positions" array
  40639. this.shapeId = 0; // model shape id
  40640. this.idxInShape = 0; // index of the particle in its shape id
  40641. this._stillInvisible = false; // still set as invisible in order to skip useless computations
  40642. this.idx = particleIndex;
  40643. this._pos = positionIndex;
  40644. this._model = model;
  40645. this.shapeId = shapeId;
  40646. this.idxInShape = idxInShape;
  40647. this._sps = sps;
  40648. if (modelBoundingInfo) {
  40649. this._modelBoundingInfo = modelBoundingInfo;
  40650. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  40651. }
  40652. }
  40653. Object.defineProperty(SolidParticle.prototype, "scale", {
  40654. /**
  40655. * legacy support, changed scale to scaling
  40656. */
  40657. get: function () {
  40658. return this.scaling;
  40659. },
  40660. set: function (scale) {
  40661. this.scaling = scale;
  40662. },
  40663. enumerable: true,
  40664. configurable: true
  40665. });
  40666. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  40667. /**
  40668. * legacy support, changed quaternion to rotationQuaternion
  40669. */
  40670. get: function () {
  40671. return this.rotationQuaternion;
  40672. },
  40673. set: function (q) {
  40674. this.rotationQuaternion = q;
  40675. },
  40676. enumerable: true,
  40677. configurable: true
  40678. });
  40679. /**
  40680. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  40681. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  40682. * `target` is the object (solid particle or mesh) what the intersection is computed against.
  40683. */
  40684. SolidParticle.prototype.intersectsMesh = function (target) {
  40685. if (!this._boundingInfo || !target._boundingInfo) {
  40686. return false;
  40687. }
  40688. if (this._sps._bSphereOnly) {
  40689. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  40690. }
  40691. return this._boundingInfo.intersects(target._boundingInfo, false);
  40692. };
  40693. return SolidParticle;
  40694. }());
  40695. BABYLON.SolidParticle = SolidParticle;
  40696. var ModelShape = (function () {
  40697. /**
  40698. * 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.
  40699. * SPS internal tool, don't use it manually.
  40700. */
  40701. function ModelShape(id, shape, shapeUV, posFunction, vtxFunction) {
  40702. this.shapeID = id;
  40703. this._shape = shape;
  40704. this._shapeUV = shapeUV;
  40705. this._positionFunction = posFunction;
  40706. this._vertexFunction = vtxFunction;
  40707. }
  40708. return ModelShape;
  40709. }());
  40710. BABYLON.ModelShape = ModelShape;
  40711. })(BABYLON || (BABYLON = {}));
  40712. //# sourceMappingURL=babylon.solidParticle.js.map
  40713. var BABYLON;
  40714. (function (BABYLON) {
  40715. /**
  40716. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  40717. */
  40718. var SolidParticleSystem = (function () {
  40719. /**
  40720. * Creates a SPS (Solid Particle System) object.
  40721. * `name` (String) is the SPS name, this will be the underlying mesh name.
  40722. * `scene` (Scene) is the scene in which the SPS is added.
  40723. * `updatable` (optional boolean, default true) : if the SPS must be updatable or immutable.
  40724. * `isPickable` (optional boolean, default false) : if the solid particles must be pickable.
  40725. * `particleIntersection` (optional boolean, default false) : if the solid particle intersections must be computed.
  40726. * `boundingSphereOnly` (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  40727. * `bSphereRadiusFactor` (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  40728. * Example : bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  40729. */
  40730. function SolidParticleSystem(name, scene, options) {
  40731. // public members
  40732. /**
  40733. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  40734. * Example : var p = SPS.particles[i];
  40735. */
  40736. this.particles = new Array();
  40737. /**
  40738. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  40739. */
  40740. this.nbParticles = 0;
  40741. /**
  40742. * If the particles must ever face the camera (default false). Useful for planar particles.
  40743. */
  40744. this.billboard = false;
  40745. /**
  40746. * Recompute normals when adding a shape
  40747. */
  40748. this.recomputeNormals = true;
  40749. /**
  40750. * This a counter ofr your own usage. It's not set by any SPS functions.
  40751. */
  40752. this.counter = 0;
  40753. /**
  40754. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  40755. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  40756. */
  40757. this.vars = {};
  40758. this._positions = new Array();
  40759. this._indices = new Array();
  40760. this._normals = new Array();
  40761. this._colors = new Array();
  40762. this._uvs = new Array();
  40763. this._index = 0; // indices index
  40764. this._updatable = true;
  40765. this._pickable = false;
  40766. this._isVisibilityBoxLocked = false;
  40767. this._alwaysVisible = false;
  40768. this._shapeCounter = 0;
  40769. this._copy = new BABYLON.SolidParticle(null, null, null, null, null, null);
  40770. this._color = new BABYLON.Color4(0, 0, 0, 0);
  40771. this._computeParticleColor = true;
  40772. this._computeParticleTexture = true;
  40773. this._computeParticleRotation = true;
  40774. this._computeParticleVertex = false;
  40775. this._computeBoundingBox = false;
  40776. this._cam_axisZ = BABYLON.Vector3.Zero();
  40777. this._cam_axisY = BABYLON.Vector3.Zero();
  40778. this._cam_axisX = BABYLON.Vector3.Zero();
  40779. this._axisX = BABYLON.Axis.X;
  40780. this._axisY = BABYLON.Axis.Y;
  40781. this._axisZ = BABYLON.Axis.Z;
  40782. this._camDir = BABYLON.Vector3.Zero();
  40783. this._rotMatrix = new BABYLON.Matrix();
  40784. this._invertMatrix = new BABYLON.Matrix();
  40785. this._rotated = BABYLON.Vector3.Zero();
  40786. this._quaternion = new BABYLON.Quaternion();
  40787. this._vertex = BABYLON.Vector3.Zero();
  40788. this._normal = BABYLON.Vector3.Zero();
  40789. this._yaw = 0.0;
  40790. this._pitch = 0.0;
  40791. this._roll = 0.0;
  40792. this._halfroll = 0.0;
  40793. this._halfpitch = 0.0;
  40794. this._halfyaw = 0.0;
  40795. this._sinRoll = 0.0;
  40796. this._cosRoll = 0.0;
  40797. this._sinPitch = 0.0;
  40798. this._cosPitch = 0.0;
  40799. this._sinYaw = 0.0;
  40800. this._cosYaw = 0.0;
  40801. this._w = 0.0;
  40802. this._mustUnrotateFixedNormals = false;
  40803. this._minimum = BABYLON.Tmp.Vector3[0];
  40804. this._maximum = BABYLON.Tmp.Vector3[1];
  40805. this._scale = BABYLON.Tmp.Vector3[2];
  40806. this._translation = BABYLON.Tmp.Vector3[3];
  40807. this._minBbox = BABYLON.Tmp.Vector3[4];
  40808. this._maxBbox = BABYLON.Tmp.Vector3[5];
  40809. this._particlesIntersect = false;
  40810. this._bSphereOnly = false;
  40811. this._bSphereRadiusFactor = 1.0;
  40812. this.name = name;
  40813. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  40814. this._camera = scene.activeCamera;
  40815. this._pickable = options ? options.isPickable : false;
  40816. this._particlesIntersect = options ? options.particleIntersection : false;
  40817. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  40818. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  40819. if (options && options.updatable) {
  40820. this._updatable = options.updatable;
  40821. }
  40822. else {
  40823. this._updatable = true;
  40824. }
  40825. if (this._pickable) {
  40826. this.pickedParticles = [];
  40827. }
  40828. }
  40829. /**
  40830. * Builds the SPS underlying mesh. Returns a standard Mesh.
  40831. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  40832. */
  40833. SolidParticleSystem.prototype.buildMesh = function () {
  40834. if (this.nbParticles === 0) {
  40835. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  40836. this.addShape(triangle, 1);
  40837. triangle.dispose();
  40838. }
  40839. this._positions32 = new Float32Array(this._positions);
  40840. this._uvs32 = new Float32Array(this._uvs);
  40841. this._colors32 = new Float32Array(this._colors);
  40842. if (this.recomputeNormals) {
  40843. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals);
  40844. }
  40845. this._normals32 = new Float32Array(this._normals);
  40846. this._fixedNormal32 = new Float32Array(this._normals);
  40847. if (this._mustUnrotateFixedNormals) {
  40848. this._unrotateFixedNormals();
  40849. }
  40850. var vertexData = new BABYLON.VertexData();
  40851. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  40852. vertexData.indices = this._indices;
  40853. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  40854. if (this._uvs32) {
  40855. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  40856. ;
  40857. }
  40858. if (this._colors32) {
  40859. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  40860. }
  40861. var mesh = new BABYLON.Mesh(this.name, this._scene);
  40862. vertexData.applyToMesh(mesh, this._updatable);
  40863. this.mesh = mesh;
  40864. this.mesh.isPickable = this._pickable;
  40865. // free memory
  40866. this._positions = null;
  40867. this._normals = null;
  40868. this._uvs = null;
  40869. this._colors = null;
  40870. if (!this._updatable) {
  40871. this.particles.length = 0;
  40872. }
  40873. return mesh;
  40874. };
  40875. /**
  40876. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  40877. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  40878. * Thus the particles generated from `digest()` have their property `position` set yet.
  40879. * `mesh` ( Mesh ) is the mesh to be digested
  40880. * `facetNb` (optional integer, default 1) is the number of mesh facets per particle, this parameter is overriden by the parameter `number` if any
  40881. * `delta` (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  40882. * `number` (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  40883. */
  40884. SolidParticleSystem.prototype.digest = function (mesh, options) {
  40885. var size = (options && options.facetNb) || 1;
  40886. var number = (options && options.number);
  40887. var delta = (options && options.delta) || 0;
  40888. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  40889. var meshInd = mesh.getIndices();
  40890. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  40891. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  40892. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  40893. var f = 0; // facet counter
  40894. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  40895. // compute size from number
  40896. if (number) {
  40897. number = (number > totalFacets) ? totalFacets : number;
  40898. size = Math.round(totalFacets / number);
  40899. delta = 0;
  40900. }
  40901. else {
  40902. size = (size > totalFacets) ? totalFacets : size;
  40903. }
  40904. var facetPos = []; // submesh positions
  40905. var facetInd = []; // submesh indices
  40906. var facetUV = []; // submesh UV
  40907. var facetCol = []; // submesh colors
  40908. var barycenter = BABYLON.Tmp.Vector3[0];
  40909. var rand;
  40910. var sizeO = size;
  40911. while (f < totalFacets) {
  40912. size = sizeO + Math.floor((1 + delta) * Math.random());
  40913. if (f > totalFacets - size) {
  40914. size = totalFacets - f;
  40915. }
  40916. // reset temp arrays
  40917. facetPos.length = 0;
  40918. facetInd.length = 0;
  40919. facetUV.length = 0;
  40920. facetCol.length = 0;
  40921. // iterate over "size" facets
  40922. var fi = 0;
  40923. for (var j = f * 3; j < (f + size) * 3; j++) {
  40924. facetInd.push(fi);
  40925. var i = meshInd[j];
  40926. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  40927. if (meshUV) {
  40928. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  40929. }
  40930. if (meshCol) {
  40931. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  40932. }
  40933. fi++;
  40934. }
  40935. // create a model shape for each single particle
  40936. var idx = this.nbParticles;
  40937. var shape = this._posToShape(facetPos);
  40938. var shapeUV = this._uvsToShapeUV(facetUV);
  40939. // compute the barycenter of the shape
  40940. var v;
  40941. for (v = 0; v < shape.length; v++) {
  40942. barycenter.addInPlace(shape[v]);
  40943. }
  40944. barycenter.scaleInPlace(1 / shape.length);
  40945. // shift the shape from its barycenter to the origin
  40946. for (v = 0; v < shape.length; v++) {
  40947. shape[v].subtractInPlace(barycenter);
  40948. }
  40949. var bInfo;
  40950. if (this._particlesIntersect) {
  40951. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  40952. }
  40953. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, null, null);
  40954. // add the particle in the SPS
  40955. var currentPos = this._positions.length;
  40956. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  40957. this._addParticle(idx, currentPos, modelShape, this._shapeCounter, 0, bInfo);
  40958. // initialize the particle position
  40959. this.particles[this.nbParticles].position.addInPlace(barycenter);
  40960. this._index += shape.length;
  40961. idx++;
  40962. this.nbParticles++;
  40963. this._shapeCounter++;
  40964. f += size;
  40965. }
  40966. return this;
  40967. };
  40968. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  40969. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  40970. var index = 0;
  40971. var idx = 0;
  40972. for (var p = 0; p < this.particles.length; p++) {
  40973. this._particle = this.particles[p];
  40974. this._shape = this._particle._model._shape;
  40975. if (this._particle.rotationQuaternion) {
  40976. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  40977. }
  40978. else {
  40979. this._yaw = this._particle.rotation.y;
  40980. this._pitch = this._particle.rotation.x;
  40981. this._roll = this._particle.rotation.z;
  40982. this._quaternionRotationYPR();
  40983. }
  40984. this._quaternionToRotationMatrix();
  40985. this._rotMatrix.invertToRef(this._invertMatrix);
  40986. for (var pt = 0; pt < this._shape.length; pt++) {
  40987. idx = index + pt * 3;
  40988. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  40989. this._fixedNormal32[idx] = this._normal.x;
  40990. this._fixedNormal32[idx + 1] = this._normal.y;
  40991. this._fixedNormal32[idx + 2] = this._normal.z;
  40992. }
  40993. index = idx + 3;
  40994. }
  40995. };
  40996. //reset copy
  40997. SolidParticleSystem.prototype._resetCopy = function () {
  40998. this._copy.position.x = 0;
  40999. this._copy.position.y = 0;
  41000. this._copy.position.z = 0;
  41001. this._copy.rotation.x = 0;
  41002. this._copy.rotation.y = 0;
  41003. this._copy.rotation.z = 0;
  41004. this._copy.rotationQuaternion = null;
  41005. this._copy.scaling.x = 1;
  41006. this._copy.scaling.y = 1;
  41007. this._copy.scaling.z = 1;
  41008. this._copy.uvs.x = 0;
  41009. this._copy.uvs.y = 0;
  41010. this._copy.uvs.z = 1;
  41011. this._copy.uvs.w = 1;
  41012. this._copy.color = null;
  41013. };
  41014. // _meshBuilder : inserts the shape model in the global SPS mesh
  41015. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  41016. var i;
  41017. var u = 0;
  41018. var c = 0;
  41019. var n = 0;
  41020. this._resetCopy();
  41021. if (options && options.positionFunction) {
  41022. options.positionFunction(this._copy, idx, idxInShape);
  41023. this._mustUnrotateFixedNormals = true;
  41024. }
  41025. if (this._copy.rotationQuaternion) {
  41026. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41027. }
  41028. else {
  41029. this._yaw = this._copy.rotation.y;
  41030. this._pitch = this._copy.rotation.x;
  41031. this._roll = this._copy.rotation.z;
  41032. this._quaternionRotationYPR();
  41033. }
  41034. this._quaternionToRotationMatrix();
  41035. for (i = 0; i < shape.length; i++) {
  41036. this._vertex.x = shape[i].x;
  41037. this._vertex.y = shape[i].y;
  41038. this._vertex.z = shape[i].z;
  41039. if (options && options.vertexFunction) {
  41040. options.vertexFunction(this._copy, this._vertex, i);
  41041. }
  41042. this._vertex.x *= this._copy.scaling.x;
  41043. this._vertex.y *= this._copy.scaling.y;
  41044. this._vertex.z *= this._copy.scaling.z;
  41045. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41046. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  41047. if (meshUV) {
  41048. 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);
  41049. u += 2;
  41050. }
  41051. if (this._copy.color) {
  41052. this._color = this._copy.color;
  41053. }
  41054. else if (meshCol && meshCol[c] !== undefined) {
  41055. this._color.r = meshCol[c];
  41056. this._color.g = meshCol[c + 1];
  41057. this._color.b = meshCol[c + 2];
  41058. this._color.a = meshCol[c + 3];
  41059. }
  41060. else {
  41061. this._color.r = 1;
  41062. this._color.g = 1;
  41063. this._color.b = 1;
  41064. this._color.a = 1;
  41065. }
  41066. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  41067. c += 4;
  41068. if (!this.recomputeNormals && meshNor) {
  41069. this._normal.x = meshNor[n];
  41070. this._normal.y = meshNor[n + 1];
  41071. this._normal.z = meshNor[n + 2];
  41072. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  41073. normals.push(this._normal.x, this._normal.y, this._normal.z);
  41074. n += 3;
  41075. }
  41076. }
  41077. for (i = 0; i < meshInd.length; i++) {
  41078. indices.push(p + meshInd[i]);
  41079. }
  41080. if (this._pickable) {
  41081. var nbfaces = meshInd.length / 3;
  41082. for (i = 0; i < nbfaces; i++) {
  41083. this.pickedParticles.push({ idx: idx, faceId: i });
  41084. }
  41085. }
  41086. return this._copy;
  41087. };
  41088. // returns a shape array from positions array
  41089. SolidParticleSystem.prototype._posToShape = function (positions) {
  41090. var shape = [];
  41091. for (var i = 0; i < positions.length; i += 3) {
  41092. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  41093. }
  41094. return shape;
  41095. };
  41096. // returns a shapeUV array from a Vector4 uvs
  41097. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  41098. var shapeUV = [];
  41099. if (uvs) {
  41100. for (var i = 0; i < uvs.length; i++)
  41101. shapeUV.push(uvs[i]);
  41102. }
  41103. return shapeUV;
  41104. };
  41105. // adds a new particle object in the particles array
  41106. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, model, shapeId, idxInShape, bInfo) {
  41107. var sp = new BABYLON.SolidParticle(idx, idxpos, model, shapeId, idxInShape, this, bInfo);
  41108. this.particles.push(sp);
  41109. return sp;
  41110. };
  41111. /**
  41112. * Adds some particles to the SPS from the model shape. Returns the shape id.
  41113. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  41114. * `mesh` is any Mesh object that will be used as a model for the solid particles.
  41115. * `nb` (positive integer) the number of particles to be created from this model
  41116. * `positionFunction` is an optional javascript function to called for each particle on SPS creation.
  41117. * `vertexFunction` is an optional javascript function to called for each vertex of each particle on SPS creation
  41118. */
  41119. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  41120. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41121. var meshInd = mesh.getIndices();
  41122. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  41123. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  41124. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  41125. var bbInfo;
  41126. if (this._particlesIntersect) {
  41127. bbInfo = mesh.getBoundingInfo();
  41128. }
  41129. var shape = this._posToShape(meshPos);
  41130. var shapeUV = this._uvsToShapeUV(meshUV);
  41131. var posfunc = options ? options.positionFunction : null;
  41132. var vtxfunc = options ? options.vertexFunction : null;
  41133. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, shapeUV, posfunc, vtxfunc);
  41134. // particles
  41135. var sp;
  41136. var currentCopy;
  41137. var idx = this.nbParticles;
  41138. for (var i = 0; i < nb; i++) {
  41139. var currentPos = this._positions.length;
  41140. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  41141. if (this._updatable) {
  41142. sp = this._addParticle(idx, currentPos, modelShape, this._shapeCounter, i, bbInfo);
  41143. sp.position.copyFrom(currentCopy.position);
  41144. sp.rotation.copyFrom(currentCopy.rotation);
  41145. if (currentCopy.rotationQuaternion) {
  41146. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  41147. }
  41148. if (currentCopy.color) {
  41149. sp.color.copyFrom(currentCopy.color);
  41150. }
  41151. sp.scaling.copyFrom(currentCopy.scaling);
  41152. sp.uvs.copyFrom(currentCopy.uvs);
  41153. }
  41154. this._index += shape.length;
  41155. idx++;
  41156. }
  41157. this.nbParticles += nb;
  41158. this._shapeCounter++;
  41159. return this._shapeCounter - 1;
  41160. };
  41161. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  41162. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  41163. this._resetCopy();
  41164. if (particle._model._positionFunction) {
  41165. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  41166. }
  41167. if (this._copy.rotationQuaternion) {
  41168. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  41169. }
  41170. else {
  41171. this._yaw = this._copy.rotation.y;
  41172. this._pitch = this._copy.rotation.x;
  41173. this._roll = this._copy.rotation.z;
  41174. this._quaternionRotationYPR();
  41175. }
  41176. this._quaternionToRotationMatrix();
  41177. this._shape = particle._model._shape;
  41178. for (var pt = 0; pt < this._shape.length; pt++) {
  41179. this._vertex.x = this._shape[pt].x;
  41180. this._vertex.y = this._shape[pt].y;
  41181. this._vertex.z = this._shape[pt].z;
  41182. if (particle._model._vertexFunction) {
  41183. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  41184. }
  41185. this._vertex.x *= this._copy.scaling.x;
  41186. this._vertex.y *= this._copy.scaling.y;
  41187. this._vertex.z *= this._copy.scaling.z;
  41188. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  41189. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  41190. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  41191. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  41192. }
  41193. particle.position.x = 0.0;
  41194. particle.position.y = 0.0;
  41195. particle.position.z = 0.0;
  41196. particle.rotation.x = 0.0;
  41197. particle.rotation.y = 0.0;
  41198. particle.rotation.z = 0.0;
  41199. particle.rotationQuaternion = null;
  41200. particle.scaling.x = 1.0;
  41201. particle.scaling.y = 1.0;
  41202. particle.scaling.z = 1.0;
  41203. };
  41204. /**
  41205. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  41206. * Returns the SPS.
  41207. */
  41208. SolidParticleSystem.prototype.rebuildMesh = function () {
  41209. for (var p = 0; p < this.particles.length; p++) {
  41210. this._rebuildParticle(this.particles[p]);
  41211. }
  41212. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41213. return this;
  41214. };
  41215. /**
  41216. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  41217. * This method calls `updateParticle()` for each particle of the SPS.
  41218. * For an animated SPS, it is usually called within the render loop.
  41219. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  41220. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  41221. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  41222. * Returns the SPS.
  41223. */
  41224. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  41225. if (start === void 0) { start = 0; }
  41226. if (end === void 0) { end = this.nbParticles - 1; }
  41227. if (update === void 0) { update = true; }
  41228. if (!this._updatable) {
  41229. return;
  41230. }
  41231. // custom beforeUpdate
  41232. this.beforeUpdateParticles(start, end, update);
  41233. this._cam_axisX.x = 1.0;
  41234. this._cam_axisX.y = 0.0;
  41235. this._cam_axisX.z = 0.0;
  41236. this._cam_axisY.x = 0.0;
  41237. this._cam_axisY.y = 1.0;
  41238. this._cam_axisY.z = 0.0;
  41239. this._cam_axisZ.x = 0.0;
  41240. this._cam_axisZ.y = 0.0;
  41241. this._cam_axisZ.z = 1.0;
  41242. // if the particles will always face the camera
  41243. if (this.billboard) {
  41244. this.mesh.computeWorldMatrix(true);
  41245. // compute the camera position and un-rotate it by the current mesh rotation
  41246. if (this.mesh._worldMatrix.decompose(this._scale, this._quaternion, this._translation)) {
  41247. this._quaternionToRotationMatrix();
  41248. this._rotMatrix.invertToRef(this._invertMatrix);
  41249. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  41250. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  41251. this._cam_axisZ.normalize();
  41252. // same for camera up vector extracted from the cam view matrix
  41253. var view = this._camera.getViewMatrix(true);
  41254. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  41255. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  41256. this._cam_axisY.normalize();
  41257. this._cam_axisX.normalize();
  41258. }
  41259. }
  41260. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  41261. var idx = 0; // current position index in the global array positions32
  41262. var index = 0; // position start index in the global array positions32 of the current particle
  41263. var colidx = 0; // current color index in the global array colors32
  41264. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  41265. var uvidx = 0; // current uv index in the global array uvs32
  41266. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  41267. var pt = 0; // current index in the particle model shape
  41268. if (this.mesh.isFacetDataEnabled) {
  41269. this._computeBoundingBox = true;
  41270. }
  41271. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  41272. if (this._computeBoundingBox) {
  41273. if (start == 0 && end == this.nbParticles - 1) {
  41274. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  41275. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  41276. }
  41277. else {
  41278. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  41279. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  41280. }
  41281. }
  41282. // particle loop
  41283. index = this.particles[start]._pos;
  41284. var vpos = (index / 3) | 0;
  41285. colorIndex = vpos * 4;
  41286. uvIndex = vpos * 2;
  41287. for (var p = start; p <= end; p++) {
  41288. this._particle = this.particles[p];
  41289. this._shape = this._particle._model._shape;
  41290. this._shapeUV = this._particle._model._shapeUV;
  41291. // call to custom user function to update the particle properties
  41292. this.updateParticle(this._particle);
  41293. // skip the computations for inactive or already invisible particles
  41294. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  41295. // increment indexes for the next particle
  41296. pt = this._shape.length;
  41297. index += pt * 3;
  41298. colorIndex += pt * 4;
  41299. uvIndex += pt * 2;
  41300. continue;
  41301. }
  41302. if (this._particle.isVisible) {
  41303. this._particle._stillInvisible = false; // un-mark permanent invisibility
  41304. // particle rotation matrix
  41305. if (this.billboard) {
  41306. this._particle.rotation.x = 0.0;
  41307. this._particle.rotation.y = 0.0;
  41308. }
  41309. if (this._computeParticleRotation || this.billboard) {
  41310. if (this._particle.rotationQuaternion) {
  41311. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  41312. }
  41313. else {
  41314. this._yaw = this._particle.rotation.y;
  41315. this._pitch = this._particle.rotation.x;
  41316. this._roll = this._particle.rotation.z;
  41317. this._quaternionRotationYPR();
  41318. }
  41319. this._quaternionToRotationMatrix();
  41320. }
  41321. // particle vertex loop
  41322. for (pt = 0; pt < this._shape.length; pt++) {
  41323. idx = index + pt * 3;
  41324. colidx = colorIndex + pt * 4;
  41325. uvidx = uvIndex + pt * 2;
  41326. this._vertex.x = this._shape[pt].x;
  41327. this._vertex.y = this._shape[pt].y;
  41328. this._vertex.z = this._shape[pt].z;
  41329. if (this._computeParticleVertex) {
  41330. this.updateParticleVertex(this._particle, this._vertex, pt);
  41331. }
  41332. // positions
  41333. this._vertex.x *= this._particle.scaling.x;
  41334. this._vertex.y *= this._particle.scaling.y;
  41335. this._vertex.z *= this._particle.scaling.z;
  41336. 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];
  41337. 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;
  41338. 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;
  41339. 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;
  41340. 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;
  41341. 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;
  41342. 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;
  41343. if (this._computeBoundingBox) {
  41344. if (this._positions32[idx] < this._minimum.x) {
  41345. this._minimum.x = this._positions32[idx];
  41346. }
  41347. if (this._positions32[idx] > this._maximum.x) {
  41348. this._maximum.x = this._positions32[idx];
  41349. }
  41350. if (this._positions32[idx + 1] < this._minimum.y) {
  41351. this._minimum.y = this._positions32[idx + 1];
  41352. }
  41353. if (this._positions32[idx + 1] > this._maximum.y) {
  41354. this._maximum.y = this._positions32[idx + 1];
  41355. }
  41356. if (this._positions32[idx + 2] < this._minimum.z) {
  41357. this._minimum.z = this._positions32[idx + 2];
  41358. }
  41359. if (this._positions32[idx + 2] > this._maximum.z) {
  41360. this._maximum.z = this._positions32[idx + 2];
  41361. }
  41362. }
  41363. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  41364. if (!this._computeParticleVertex) {
  41365. this._normal.x = this._fixedNormal32[idx];
  41366. this._normal.y = this._fixedNormal32[idx + 1];
  41367. this._normal.z = this._fixedNormal32[idx + 2];
  41368. 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]);
  41369. 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]);
  41370. 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]);
  41371. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  41372. 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;
  41373. 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;
  41374. }
  41375. if (this._computeParticleColor) {
  41376. this._colors32[colidx] = this._particle.color.r;
  41377. this._colors32[colidx + 1] = this._particle.color.g;
  41378. this._colors32[colidx + 2] = this._particle.color.b;
  41379. this._colors32[colidx + 3] = this._particle.color.a;
  41380. }
  41381. if (this._computeParticleTexture) {
  41382. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41383. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41384. }
  41385. }
  41386. }
  41387. else {
  41388. this._particle._stillInvisible = true; // mark the particle as invisible
  41389. for (pt = 0; pt < this._shape.length; pt++) {
  41390. idx = index + pt * 3;
  41391. colidx = colorIndex + pt * 4;
  41392. uvidx = uvIndex + pt * 2;
  41393. this._positions32[idx] = 0.0;
  41394. this._positions32[idx + 1] = 0.0;
  41395. this._positions32[idx + 2] = 0.0;
  41396. this._normals32[idx] = 0.0;
  41397. this._normals32[idx + 1] = 0.0;
  41398. this._normals32[idx + 2] = 0.0;
  41399. if (this._computeParticleColor) {
  41400. this._colors32[colidx] = this._particle.color.r;
  41401. this._colors32[colidx + 1] = this._particle.color.g;
  41402. this._colors32[colidx + 2] = this._particle.color.b;
  41403. this._colors32[colidx + 3] = this._particle.color.a;
  41404. }
  41405. if (this._computeParticleTexture) {
  41406. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  41407. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  41408. }
  41409. }
  41410. }
  41411. // if the particle intersections must be computed : update the bbInfo
  41412. if (this._particlesIntersect) {
  41413. var bInfo = this._particle._boundingInfo;
  41414. var bBox = bInfo.boundingBox;
  41415. var bSphere = bInfo.boundingSphere;
  41416. if (!this._bSphereOnly) {
  41417. // place, scale and rotate the particle bbox within the SPS local system, then update it
  41418. for (var b = 0; b < bBox.vectors.length; b++) {
  41419. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  41420. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  41421. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  41422. 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];
  41423. 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;
  41424. 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;
  41425. 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;
  41426. 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;
  41427. 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;
  41428. 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;
  41429. }
  41430. bBox._update(this.mesh._worldMatrix);
  41431. }
  41432. // place and scale the particle bouding sphere in the SPS local system, then update it
  41433. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  41434. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  41435. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  41436. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  41437. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  41438. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  41439. bSphere.center.x = this._particle.position.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  41440. bSphere.center.y = this._particle.position.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  41441. bSphere.center.z = this._particle.position.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  41442. 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));
  41443. bSphere._update(this.mesh._worldMatrix);
  41444. }
  41445. // increment indexes for the next particle
  41446. index = idx + 3;
  41447. colorIndex = colidx + 4;
  41448. uvIndex = uvidx + 2;
  41449. }
  41450. // if the VBO must be updated
  41451. if (update) {
  41452. if (this._computeParticleColor) {
  41453. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  41454. }
  41455. if (this._computeParticleTexture) {
  41456. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  41457. }
  41458. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  41459. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  41460. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  41461. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  41462. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  41463. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices, this._normals32, params);
  41464. for (var i = 0; i < this._normals32.length; i++) {
  41465. this._fixedNormal32[i] = this._normals32[i];
  41466. }
  41467. }
  41468. if (!this.mesh.areNormalsFrozen) {
  41469. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  41470. }
  41471. }
  41472. }
  41473. if (this._computeBoundingBox) {
  41474. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  41475. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  41476. }
  41477. this.afterUpdateParticles(start, end, update);
  41478. return this;
  41479. };
  41480. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  41481. this._halfroll = this._roll * 0.5;
  41482. this._halfpitch = this._pitch * 0.5;
  41483. this._halfyaw = this._yaw * 0.5;
  41484. this._sinRoll = Math.sin(this._halfroll);
  41485. this._cosRoll = Math.cos(this._halfroll);
  41486. this._sinPitch = Math.sin(this._halfpitch);
  41487. this._cosPitch = Math.cos(this._halfpitch);
  41488. this._sinYaw = Math.sin(this._halfyaw);
  41489. this._cosYaw = Math.cos(this._halfyaw);
  41490. this._quaternion.x = (this._cosYaw * this._sinPitch * this._cosRoll) + (this._sinYaw * this._cosPitch * this._sinRoll);
  41491. this._quaternion.y = (this._sinYaw * this._cosPitch * this._cosRoll) - (this._cosYaw * this._sinPitch * this._sinRoll);
  41492. this._quaternion.z = (this._cosYaw * this._cosPitch * this._sinRoll) - (this._sinYaw * this._sinPitch * this._cosRoll);
  41493. this._quaternion.w = (this._cosYaw * this._cosPitch * this._cosRoll) + (this._sinYaw * this._sinPitch * this._sinRoll);
  41494. };
  41495. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  41496. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  41497. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  41498. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  41499. this._rotMatrix.m[3] = 0;
  41500. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  41501. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  41502. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  41503. this._rotMatrix.m[7] = 0;
  41504. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  41505. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  41506. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  41507. this._rotMatrix.m[11] = 0;
  41508. this._rotMatrix.m[12] = 0;
  41509. this._rotMatrix.m[13] = 0;
  41510. this._rotMatrix.m[14] = 0;
  41511. this._rotMatrix.m[15] = 1.0;
  41512. };
  41513. /**
  41514. * Disposes the SPS.
  41515. * Returns nothing.
  41516. */
  41517. SolidParticleSystem.prototype.dispose = function () {
  41518. this.mesh.dispose();
  41519. this.vars = null;
  41520. // drop references to internal big arrays for the GC
  41521. this._positions = null;
  41522. this._indices = null;
  41523. this._normals = null;
  41524. this._uvs = null;
  41525. this._colors = null;
  41526. this._positions32 = null;
  41527. this._normals32 = null;
  41528. this._fixedNormal32 = null;
  41529. this._uvs32 = null;
  41530. this._colors32 = null;
  41531. this.pickedParticles = null;
  41532. };
  41533. /**
  41534. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  41535. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41536. * Returns the SPS.
  41537. */
  41538. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  41539. if (!this._isVisibilityBoxLocked) {
  41540. this.mesh.refreshBoundingInfo();
  41541. }
  41542. return this;
  41543. };
  41544. /**
  41545. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  41546. * @param size the size (float) of the visibility box
  41547. * note : this doesn't lock the SPS mesh bounding box.
  41548. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41549. */
  41550. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  41551. var vis = size / 2;
  41552. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  41553. };
  41554. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  41555. // getter and setter
  41556. get: function () {
  41557. return this._alwaysVisible;
  41558. },
  41559. /**
  41560. * Sets the SPS as always visible or not
  41561. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41562. */
  41563. set: function (val) {
  41564. this._alwaysVisible = val;
  41565. this.mesh.alwaysSelectAsActiveMesh = val;
  41566. },
  41567. enumerable: true,
  41568. configurable: true
  41569. });
  41570. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  41571. get: function () {
  41572. return this._isVisibilityBoxLocked;
  41573. },
  41574. /**
  41575. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  41576. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  41577. */
  41578. set: function (val) {
  41579. this._isVisibilityBoxLocked = val;
  41580. this.mesh.getBoundingInfo().isLocked = val;
  41581. },
  41582. enumerable: true,
  41583. configurable: true
  41584. });
  41585. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  41586. // getters
  41587. get: function () {
  41588. return this._computeParticleRotation;
  41589. },
  41590. // Optimizer setters
  41591. /**
  41592. * Tells to `setParticles()` to compute the particle rotations or not.
  41593. * Default value : true. The SPS is faster when it's set to false.
  41594. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  41595. */
  41596. set: function (val) {
  41597. this._computeParticleRotation = val;
  41598. },
  41599. enumerable: true,
  41600. configurable: true
  41601. });
  41602. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  41603. get: function () {
  41604. return this._computeParticleColor;
  41605. },
  41606. /**
  41607. * Tells to `setParticles()` to compute the particle colors or not.
  41608. * Default value : true. The SPS is faster when it's set to false.
  41609. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  41610. */
  41611. set: function (val) {
  41612. this._computeParticleColor = val;
  41613. },
  41614. enumerable: true,
  41615. configurable: true
  41616. });
  41617. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  41618. get: function () {
  41619. return this._computeParticleTexture;
  41620. },
  41621. /**
  41622. * Tells to `setParticles()` to compute the particle textures or not.
  41623. * Default value : true. The SPS is faster when it's set to false.
  41624. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  41625. */
  41626. set: function (val) {
  41627. this._computeParticleTexture = val;
  41628. },
  41629. enumerable: true,
  41630. configurable: true
  41631. });
  41632. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  41633. get: function () {
  41634. return this._computeParticleVertex;
  41635. },
  41636. /**
  41637. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  41638. * Default value : false. The SPS is faster when it's set to false.
  41639. * Note : the particle custom vertex positions aren't stored values.
  41640. */
  41641. set: function (val) {
  41642. this._computeParticleVertex = val;
  41643. },
  41644. enumerable: true,
  41645. configurable: true
  41646. });
  41647. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  41648. get: function () {
  41649. return this._computeBoundingBox;
  41650. },
  41651. /**
  41652. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  41653. */
  41654. set: function (val) {
  41655. this._computeBoundingBox = val;
  41656. },
  41657. enumerable: true,
  41658. configurable: true
  41659. });
  41660. // =======================================================================
  41661. // Particle behavior logic
  41662. // these following methods may be overwritten by the user to fit his needs
  41663. /**
  41664. * This function does nothing. It may be overwritten to set all the particle first values.
  41665. * The SPS doesn't call this function, you may have to call it by your own.
  41666. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41667. */
  41668. SolidParticleSystem.prototype.initParticles = function () {
  41669. };
  41670. /**
  41671. * This function does nothing. It may be overwritten to recycle a particle.
  41672. * The SPS doesn't call this function, you may have to call it by your own.
  41673. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41674. */
  41675. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  41676. return particle;
  41677. };
  41678. /**
  41679. * Updates a particle : this function should be overwritten by the user.
  41680. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  41681. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  41682. * ex : just set a particle position or velocity and recycle conditions
  41683. */
  41684. SolidParticleSystem.prototype.updateParticle = function (particle) {
  41685. return particle;
  41686. };
  41687. /**
  41688. * Updates a vertex of a particle : it can be overwritten by the user.
  41689. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  41690. * @param particle the current particle
  41691. * @param vertex the current index of the current particle
  41692. * @param pt the index of the current vertex in the particle shape
  41693. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  41694. * ex : just set a vertex particle position
  41695. */
  41696. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  41697. return vertex;
  41698. };
  41699. /**
  41700. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  41701. * This does nothing and may be overwritten by the user.
  41702. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41703. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41704. * @param update the boolean update value actually passed to setParticles()
  41705. */
  41706. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  41707. };
  41708. /**
  41709. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  41710. * This will be passed three parameters.
  41711. * This does nothing and may be overwritten by the user.
  41712. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41713. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  41714. * @param update the boolean update value actually passed to setParticles()
  41715. */
  41716. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  41717. };
  41718. return SolidParticleSystem;
  41719. }());
  41720. BABYLON.SolidParticleSystem = SolidParticleSystem;
  41721. })(BABYLON || (BABYLON = {}));
  41722. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  41723. /// <reference path="babylon.mesh.ts" />
  41724. var BABYLON;
  41725. (function (BABYLON) {
  41726. var GroundMesh = (function (_super) {
  41727. __extends(GroundMesh, _super);
  41728. function GroundMesh(name, scene) {
  41729. var _this = _super.call(this, name, scene) || this;
  41730. _this.generateOctree = false;
  41731. _this._worldInverse = new BABYLON.Matrix();
  41732. return _this;
  41733. }
  41734. GroundMesh.prototype.getClassName = function () {
  41735. return "GroundMesh";
  41736. };
  41737. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  41738. get: function () {
  41739. return Math.min(this._subdivisionsX, this._subdivisionsY);
  41740. },
  41741. enumerable: true,
  41742. configurable: true
  41743. });
  41744. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  41745. get: function () {
  41746. return this._subdivisionsX;
  41747. },
  41748. enumerable: true,
  41749. configurable: true
  41750. });
  41751. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  41752. get: function () {
  41753. return this._subdivisionsY;
  41754. },
  41755. enumerable: true,
  41756. configurable: true
  41757. });
  41758. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  41759. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  41760. this._subdivisionsX = chunksCount;
  41761. this._subdivisionsY = chunksCount;
  41762. this.subdivide(chunksCount);
  41763. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  41764. };
  41765. /**
  41766. * Returns a height (y) value in the Worl system :
  41767. * the ground altitude at the coordinates (x, z) expressed in the World system.
  41768. * Returns the ground y position if (x, z) are outside the ground surface.
  41769. */
  41770. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  41771. var world = this.getWorldMatrix();
  41772. var invMat = BABYLON.Tmp.Matrix[5];
  41773. world.invertToRef(invMat);
  41774. var tmpVect = BABYLON.Tmp.Vector3[8];
  41775. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  41776. x = tmpVect.x;
  41777. z = tmpVect.z;
  41778. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41779. return this.position.y;
  41780. }
  41781. if (!this._heightQuads || this._heightQuads.length == 0) {
  41782. this._initHeightQuads();
  41783. this._computeHeightQuads();
  41784. }
  41785. var facet = this._getFacetAt(x, z);
  41786. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  41787. // return y in the World system
  41788. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  41789. return tmpVect.y;
  41790. };
  41791. /**
  41792. * Returns a normalized vector (Vector3) orthogonal to the ground
  41793. * at the ground coordinates (x, z) expressed in the World system.
  41794. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  41795. */
  41796. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  41797. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  41798. this.getNormalAtCoordinatesToRef(x, z, normal);
  41799. return normal;
  41800. };
  41801. /**
  41802. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  41803. * at the ground coordinates (x, z) expressed in the World system.
  41804. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  41805. * Returns the GroundMesh.
  41806. */
  41807. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  41808. var world = this.getWorldMatrix();
  41809. var tmpMat = BABYLON.Tmp.Matrix[5];
  41810. world.invertToRef(tmpMat);
  41811. var tmpVect = BABYLON.Tmp.Vector3[8];
  41812. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  41813. x = tmpVect.x;
  41814. z = tmpVect.z;
  41815. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  41816. return this;
  41817. }
  41818. if (!this._heightQuads || this._heightQuads.length == 0) {
  41819. this._initHeightQuads();
  41820. this._computeHeightQuads();
  41821. }
  41822. var facet = this._getFacetAt(x, z);
  41823. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  41824. return this;
  41825. };
  41826. /**
  41827. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  41828. * if the ground has been updated.
  41829. * This can be used in the render loop.
  41830. * Returns the GroundMesh.
  41831. */
  41832. GroundMesh.prototype.updateCoordinateHeights = function () {
  41833. if (!this._heightQuads || this._heightQuads.length == 0) {
  41834. this._initHeightQuads();
  41835. }
  41836. this._computeHeightQuads();
  41837. return this;
  41838. };
  41839. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  41840. GroundMesh.prototype._getFacetAt = function (x, z) {
  41841. // retrieve col and row from x, z coordinates in the ground local system
  41842. var subdivisionsX = this._subdivisionsX;
  41843. var subdivisionsY = this._subdivisionsY;
  41844. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  41845. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  41846. var quad = this._heightQuads[row * this._subdivisionsX + col];
  41847. var facet;
  41848. if (z < quad.slope.x * x + quad.slope.y) {
  41849. facet = quad.facet1;
  41850. }
  41851. else {
  41852. facet = quad.facet2;
  41853. }
  41854. return facet;
  41855. };
  41856. // Creates and populates the heightMap array with "facet" elements :
  41857. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  41858. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41859. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41860. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41861. // Returns the GroundMesh.
  41862. GroundMesh.prototype._initHeightQuads = function () {
  41863. var subdivisionsX = this._subdivisionsX;
  41864. var subdivisionsY = this._subdivisionsY;
  41865. this._heightQuads = new Array();
  41866. for (var row = 0; row < subdivisionsY; row++) {
  41867. for (var col = 0; col < subdivisionsX; col++) {
  41868. var quad = { slope: BABYLON.Vector2.Zero(), facet1: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0), facet2: new BABYLON.Vector4(0.0, 0.0, 0.0, 0.0) };
  41869. this._heightQuads[row * subdivisionsX + col] = quad;
  41870. }
  41871. }
  41872. return this;
  41873. };
  41874. // Compute each quad element values and update the the heightMap array :
  41875. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  41876. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  41877. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  41878. // Returns the GroundMesh.
  41879. GroundMesh.prototype._computeHeightQuads = function () {
  41880. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  41881. var v1 = BABYLON.Tmp.Vector3[3];
  41882. var v2 = BABYLON.Tmp.Vector3[2];
  41883. var v3 = BABYLON.Tmp.Vector3[1];
  41884. var v4 = BABYLON.Tmp.Vector3[0];
  41885. var v1v2 = BABYLON.Tmp.Vector3[4];
  41886. var v1v3 = BABYLON.Tmp.Vector3[5];
  41887. var v1v4 = BABYLON.Tmp.Vector3[6];
  41888. var norm1 = BABYLON.Tmp.Vector3[7];
  41889. var norm2 = BABYLON.Tmp.Vector3[8];
  41890. var i = 0;
  41891. var j = 0;
  41892. var k = 0;
  41893. var cd = 0; // 2D slope coefficient : z = cd * x + h
  41894. var h = 0;
  41895. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  41896. var d2 = 0;
  41897. var subdivisionsX = this._subdivisionsX;
  41898. var subdivisionsY = this._subdivisionsY;
  41899. for (var row = 0; row < subdivisionsY; row++) {
  41900. for (var col = 0; col < subdivisionsX; col++) {
  41901. i = col * 3;
  41902. j = row * (subdivisionsX + 1) * 3;
  41903. k = (row + 1) * (subdivisionsX + 1) * 3;
  41904. v1.x = positions[j + i];
  41905. v1.y = positions[j + i + 1];
  41906. v1.z = positions[j + i + 2];
  41907. v2.x = positions[j + i + 3];
  41908. v2.y = positions[j + i + 4];
  41909. v2.z = positions[j + i + 5];
  41910. v3.x = positions[k + i];
  41911. v3.y = positions[k + i + 1];
  41912. v3.z = positions[k + i + 2];
  41913. v4.x = positions[k + i + 3];
  41914. v4.y = positions[k + i + 4];
  41915. v4.z = positions[k + i + 5];
  41916. // 2D slope V1V4
  41917. cd = (v4.z - v1.z) / (v4.x - v1.x);
  41918. h = v1.z - cd * v1.x; // v1 belongs to the slope
  41919. // facet equations :
  41920. // we compute each facet normal vector
  41921. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  41922. // we compute the value d by applying the equation to v1 which belongs to the plane
  41923. // then we store the facet equation in a Vector4
  41924. v2.subtractToRef(v1, v1v2);
  41925. v3.subtractToRef(v1, v1v3);
  41926. v4.subtractToRef(v1, v1v4);
  41927. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  41928. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  41929. norm1.normalize();
  41930. norm2.normalize();
  41931. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  41932. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  41933. var quad = this._heightQuads[row * subdivisionsX + col];
  41934. quad.slope.copyFromFloats(cd, h);
  41935. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  41936. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  41937. }
  41938. }
  41939. return this;
  41940. };
  41941. GroundMesh.prototype.serialize = function (serializationObject) {
  41942. _super.prototype.serialize.call(this, serializationObject);
  41943. serializationObject.subdivisionsX = this._subdivisionsX;
  41944. serializationObject.subdivisionsY = this._subdivisionsY;
  41945. serializationObject.minX = this._minX;
  41946. serializationObject.maxX = this._maxX;
  41947. serializationObject.minZ = this._minZ;
  41948. serializationObject.maxZ = this._maxZ;
  41949. serializationObject.width = this._width;
  41950. serializationObject.height = this._height;
  41951. };
  41952. GroundMesh.Parse = function (parsedMesh, scene) {
  41953. var result = new GroundMesh(parsedMesh.name, scene);
  41954. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  41955. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  41956. result._minX = parsedMesh.minX;
  41957. result._maxX = parsedMesh.maxX;
  41958. result._minZ = parsedMesh.minZ;
  41959. result._maxZ = parsedMesh.maxZ;
  41960. result._width = parsedMesh.width;
  41961. result._height = parsedMesh.height;
  41962. return result;
  41963. };
  41964. return GroundMesh;
  41965. }(BABYLON.Mesh));
  41966. BABYLON.GroundMesh = GroundMesh;
  41967. })(BABYLON || (BABYLON = {}));
  41968. //# sourceMappingURL=babylon.groundMesh.js.map
  41969. var BABYLON;
  41970. (function (BABYLON) {
  41971. /**
  41972. * Creates an instance based on a source mesh.
  41973. */
  41974. var InstancedMesh = (function (_super) {
  41975. __extends(InstancedMesh, _super);
  41976. function InstancedMesh(name, source) {
  41977. var _this = _super.call(this, name, source.getScene()) || this;
  41978. source.instances.push(_this);
  41979. _this._sourceMesh = source;
  41980. _this.position.copyFrom(source.position);
  41981. _this.rotation.copyFrom(source.rotation);
  41982. _this.scaling.copyFrom(source.scaling);
  41983. if (source.rotationQuaternion) {
  41984. _this.rotationQuaternion = source.rotationQuaternion.clone();
  41985. }
  41986. _this.infiniteDistance = source.infiniteDistance;
  41987. _this.setPivotMatrix(source.getPivotMatrix());
  41988. _this.refreshBoundingInfo();
  41989. _this._syncSubMeshes();
  41990. return _this;
  41991. }
  41992. /**
  41993. * Returns the string "InstancedMesh".
  41994. */
  41995. InstancedMesh.prototype.getClassName = function () {
  41996. return "InstancedMesh";
  41997. };
  41998. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  41999. // Methods
  42000. get: function () {
  42001. return this._sourceMesh.receiveShadows;
  42002. },
  42003. enumerable: true,
  42004. configurable: true
  42005. });
  42006. Object.defineProperty(InstancedMesh.prototype, "material", {
  42007. get: function () {
  42008. return this._sourceMesh.material;
  42009. },
  42010. enumerable: true,
  42011. configurable: true
  42012. });
  42013. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  42014. get: function () {
  42015. return this._sourceMesh.visibility;
  42016. },
  42017. enumerable: true,
  42018. configurable: true
  42019. });
  42020. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  42021. get: function () {
  42022. return this._sourceMesh.skeleton;
  42023. },
  42024. enumerable: true,
  42025. configurable: true
  42026. });
  42027. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  42028. get: function () {
  42029. return this._sourceMesh.renderingGroupId;
  42030. },
  42031. enumerable: true,
  42032. configurable: true
  42033. });
  42034. /**
  42035. * Returns the total number of vertices (integer).
  42036. */
  42037. InstancedMesh.prototype.getTotalVertices = function () {
  42038. return this._sourceMesh.getTotalVertices();
  42039. };
  42040. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  42041. get: function () {
  42042. return this._sourceMesh;
  42043. },
  42044. enumerable: true,
  42045. configurable: true
  42046. });
  42047. /**
  42048. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  42049. */
  42050. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  42051. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  42052. };
  42053. /**
  42054. * Sets the vertex data of the mesh geometry for the requested `kind`.
  42055. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  42056. * The `data` are either a numeric array either a Float32Array.
  42057. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  42058. * 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).
  42059. * Note that a new underlying VertexBuffer object is created each call.
  42060. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  42061. *
  42062. * Possible `kind` values :
  42063. * - BABYLON.VertexBuffer.PositionKind
  42064. * - BABYLON.VertexBuffer.UVKind
  42065. * - BABYLON.VertexBuffer.UV2Kind
  42066. * - BABYLON.VertexBuffer.UV3Kind
  42067. * - BABYLON.VertexBuffer.UV4Kind
  42068. * - BABYLON.VertexBuffer.UV5Kind
  42069. * - BABYLON.VertexBuffer.UV6Kind
  42070. * - BABYLON.VertexBuffer.ColorKind
  42071. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42072. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42073. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42074. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42075. *
  42076. * Returns the Mesh.
  42077. */
  42078. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  42079. if (this.sourceMesh) {
  42080. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  42081. }
  42082. return this.sourceMesh;
  42083. };
  42084. /**
  42085. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  42086. * If the mesh has no geometry, it is simply returned as it is.
  42087. * The `data` are either a numeric array either a Float32Array.
  42088. * No new underlying VertexBuffer object is created.
  42089. * 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.
  42090. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  42091. *
  42092. * Possible `kind` values :
  42093. * - BABYLON.VertexBuffer.PositionKind
  42094. * - BABYLON.VertexBuffer.UVKind
  42095. * - BABYLON.VertexBuffer.UV2Kind
  42096. * - BABYLON.VertexBuffer.UV3Kind
  42097. * - BABYLON.VertexBuffer.UV4Kind
  42098. * - BABYLON.VertexBuffer.UV5Kind
  42099. * - BABYLON.VertexBuffer.UV6Kind
  42100. * - BABYLON.VertexBuffer.ColorKind
  42101. * - BABYLON.VertexBuffer.MatricesIndicesKind
  42102. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  42103. * - BABYLON.VertexBuffer.MatricesWeightsKind
  42104. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  42105. *
  42106. * Returns the Mesh.
  42107. */
  42108. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  42109. if (this.sourceMesh) {
  42110. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  42111. }
  42112. return this.sourceMesh;
  42113. };
  42114. /**
  42115. * Sets the mesh indices.
  42116. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  42117. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  42118. * This method creates a new index buffer each call.
  42119. * Returns the Mesh.
  42120. */
  42121. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  42122. if (this.sourceMesh) {
  42123. this.sourceMesh.setIndices(indices, totalVertices);
  42124. }
  42125. return this.sourceMesh;
  42126. };
  42127. /**
  42128. * Boolean : True if the mesh owns the requested kind of data.
  42129. */
  42130. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  42131. return this._sourceMesh.isVerticesDataPresent(kind);
  42132. };
  42133. /**
  42134. * Returns an array of indices (IndicesArray).
  42135. */
  42136. InstancedMesh.prototype.getIndices = function () {
  42137. return this._sourceMesh.getIndices();
  42138. };
  42139. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  42140. get: function () {
  42141. return this._sourceMesh._positions;
  42142. },
  42143. enumerable: true,
  42144. configurable: true
  42145. });
  42146. /**
  42147. * Sets a new updated BoundingInfo to the mesh.
  42148. * Returns the mesh.
  42149. */
  42150. InstancedMesh.prototype.refreshBoundingInfo = function () {
  42151. var meshBB = this._sourceMesh.getBoundingInfo();
  42152. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  42153. this._updateBoundingInfo();
  42154. return this;
  42155. };
  42156. InstancedMesh.prototype._preActivate = function () {
  42157. if (this._currentLOD) {
  42158. this._currentLOD._preActivate();
  42159. }
  42160. return this;
  42161. };
  42162. InstancedMesh.prototype._activate = function (renderId) {
  42163. if (this._currentLOD) {
  42164. this._currentLOD._registerInstanceForRenderId(this, renderId);
  42165. }
  42166. return this;
  42167. };
  42168. /**
  42169. * Returns the current associated LOD AbstractMesh.
  42170. */
  42171. InstancedMesh.prototype.getLOD = function (camera) {
  42172. this._currentLOD = this.sourceMesh.getLOD(this.getScene().activeCamera, this.getBoundingInfo().boundingSphere);
  42173. if (this._currentLOD === this.sourceMesh) {
  42174. return this;
  42175. }
  42176. return this._currentLOD;
  42177. };
  42178. InstancedMesh.prototype._syncSubMeshes = function () {
  42179. this.releaseSubMeshes();
  42180. if (this._sourceMesh.subMeshes) {
  42181. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  42182. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  42183. }
  42184. }
  42185. return this;
  42186. };
  42187. InstancedMesh.prototype._generatePointsArray = function () {
  42188. return this._sourceMesh._generatePointsArray();
  42189. };
  42190. /**
  42191. * Creates a new InstancedMesh from the current mesh.
  42192. * - name (string) : the cloned mesh name
  42193. * - newParent (optional Node) : the optional Node to parent the clone to.
  42194. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  42195. *
  42196. * Returns the clone.
  42197. */
  42198. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42199. var result = this._sourceMesh.createInstance(name);
  42200. // Deep copy
  42201. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  42202. // Bounding info
  42203. this.refreshBoundingInfo();
  42204. // Parent
  42205. if (newParent) {
  42206. result.parent = newParent;
  42207. }
  42208. if (!doNotCloneChildren) {
  42209. // Children
  42210. for (var index = 0; index < this.getScene().meshes.length; index++) {
  42211. var mesh = this.getScene().meshes[index];
  42212. if (mesh.parent === this) {
  42213. mesh.clone(mesh.name, result);
  42214. }
  42215. }
  42216. }
  42217. result.computeWorldMatrix(true);
  42218. return result;
  42219. };
  42220. /**
  42221. * Disposes the InstancedMesh.
  42222. * Returns nothing.
  42223. */
  42224. InstancedMesh.prototype.dispose = function (doNotRecurse) {
  42225. // Remove from mesh
  42226. var index = this._sourceMesh.instances.indexOf(this);
  42227. this._sourceMesh.instances.splice(index, 1);
  42228. _super.prototype.dispose.call(this, doNotRecurse);
  42229. };
  42230. return InstancedMesh;
  42231. }(BABYLON.AbstractMesh));
  42232. BABYLON.InstancedMesh = InstancedMesh;
  42233. })(BABYLON || (BABYLON = {}));
  42234. //# sourceMappingURL=babylon.instancedMesh.js.map
  42235. /// <reference path="babylon.mesh.ts" />
  42236. var BABYLON;
  42237. (function (BABYLON) {
  42238. var LinesMesh = (function (_super) {
  42239. __extends(LinesMesh, _super);
  42240. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor) {
  42241. if (parent === void 0) { parent = null; }
  42242. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  42243. _this.useVertexColor = useVertexColor;
  42244. _this.color = new BABYLON.Color3(1, 1, 1);
  42245. _this.alpha = 1;
  42246. if (source) {
  42247. _this.color = source.color.clone();
  42248. _this.alpha = source.alpha;
  42249. _this.useVertexColor = source.useVertexColor;
  42250. }
  42251. _this._intersectionThreshold = 0.1;
  42252. var options = {
  42253. attributes: [BABYLON.VertexBuffer.PositionKind],
  42254. uniforms: ["world", "viewProjection"],
  42255. needAlphaBlending: false,
  42256. };
  42257. if (!useVertexColor) {
  42258. options.uniforms.push("color");
  42259. options.needAlphaBlending = true;
  42260. }
  42261. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", scene, "color", options);
  42262. return _this;
  42263. }
  42264. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  42265. /**
  42266. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42267. * This margin is expressed in world space coordinates, so its value may vary.
  42268. * Default value is 0.1
  42269. * @returns the intersection Threshold value.
  42270. */
  42271. get: function () {
  42272. return this._intersectionThreshold;
  42273. },
  42274. /**
  42275. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  42276. * This margin is expressed in world space coordinates, so its value may vary.
  42277. * @param value the new threshold to apply
  42278. */
  42279. set: function (value) {
  42280. if (this._intersectionThreshold === value) {
  42281. return;
  42282. }
  42283. this._intersectionThreshold = value;
  42284. if (this.geometry) {
  42285. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  42286. }
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. /**
  42292. * Returns the string "LineMesh"
  42293. */
  42294. LinesMesh.prototype.getClassName = function () {
  42295. return "LinesMesh";
  42296. };
  42297. Object.defineProperty(LinesMesh.prototype, "material", {
  42298. get: function () {
  42299. return this._colorShader;
  42300. },
  42301. enumerable: true,
  42302. configurable: true
  42303. });
  42304. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  42305. get: function () {
  42306. return false;
  42307. },
  42308. enumerable: true,
  42309. configurable: true
  42310. });
  42311. LinesMesh.prototype.createInstance = function (name) {
  42312. BABYLON.Tools.Log("LinesMeshes do not support createInstance.");
  42313. return null;
  42314. };
  42315. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  42316. // VBOs
  42317. this._geometry._bind(this._colorShader.getEffect());
  42318. // Color
  42319. if (!this.useVertexColor) {
  42320. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  42321. }
  42322. return this;
  42323. };
  42324. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  42325. if (!this._geometry || !this._geometry.getVertexBuffers() || !this._geometry.getIndexBuffer()) {
  42326. return this;
  42327. }
  42328. var engine = this.getScene().getEngine();
  42329. // Draw order
  42330. engine.draw(false, subMesh.indexStart, subMesh.indexCount);
  42331. return this;
  42332. };
  42333. LinesMesh.prototype.dispose = function (doNotRecurse) {
  42334. this._colorShader.dispose();
  42335. _super.prototype.dispose.call(this, doNotRecurse);
  42336. };
  42337. /**
  42338. * Returns a new LineMesh object cloned from the current one.
  42339. */
  42340. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  42341. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  42342. };
  42343. return LinesMesh;
  42344. }(BABYLON.Mesh));
  42345. BABYLON.LinesMesh = LinesMesh;
  42346. })(BABYLON || (BABYLON = {}));
  42347. //# sourceMappingURL=babylon.linesMesh.js.map
  42348. var BABYLON;
  42349. (function (BABYLON) {
  42350. var ShaderMaterial = (function (_super) {
  42351. __extends(ShaderMaterial, _super);
  42352. function ShaderMaterial(name, scene, shaderPath, options) {
  42353. var _this = _super.call(this, name, scene) || this;
  42354. _this._textures = {};
  42355. _this._textureArrays = {};
  42356. _this._floats = {};
  42357. _this._floatsArrays = {};
  42358. _this._colors3 = {};
  42359. _this._colors3Arrays = {};
  42360. _this._colors4 = {};
  42361. _this._vectors2 = {};
  42362. _this._vectors3 = {};
  42363. _this._vectors4 = {};
  42364. _this._matrices = {};
  42365. _this._matrices3x3 = {};
  42366. _this._matrices2x2 = {};
  42367. _this._vectors3Arrays = {};
  42368. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  42369. _this._shaderPath = shaderPath;
  42370. options.needAlphaBlending = options.needAlphaBlending || false;
  42371. options.needAlphaTesting = options.needAlphaTesting || false;
  42372. options.attributes = options.attributes || ["position", "normal", "uv"];
  42373. options.uniforms = options.uniforms || ["worldViewProjection"];
  42374. options.uniformBuffers = options.uniformBuffers || [];
  42375. options.samplers = options.samplers || [];
  42376. options.defines = options.defines || [];
  42377. _this._options = options;
  42378. return _this;
  42379. }
  42380. ShaderMaterial.prototype.getClassName = function () {
  42381. return "ShaderMaterial";
  42382. };
  42383. ShaderMaterial.prototype.needAlphaBlending = function () {
  42384. return this._options.needAlphaBlending;
  42385. };
  42386. ShaderMaterial.prototype.needAlphaTesting = function () {
  42387. return this._options.needAlphaTesting;
  42388. };
  42389. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  42390. if (this._options.uniforms.indexOf(uniformName) === -1) {
  42391. this._options.uniforms.push(uniformName);
  42392. }
  42393. };
  42394. ShaderMaterial.prototype.setTexture = function (name, texture) {
  42395. if (this._options.samplers.indexOf(name) === -1) {
  42396. this._options.samplers.push(name);
  42397. }
  42398. this._textures[name] = texture;
  42399. return this;
  42400. };
  42401. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  42402. if (this._options.samplers.indexOf(name) === -1) {
  42403. this._options.samplers.push(name);
  42404. }
  42405. this._checkUniform(name);
  42406. this._textureArrays[name] = textures;
  42407. return this;
  42408. };
  42409. ShaderMaterial.prototype.setFloat = function (name, value) {
  42410. this._checkUniform(name);
  42411. this._floats[name] = value;
  42412. return this;
  42413. };
  42414. ShaderMaterial.prototype.setFloats = function (name, value) {
  42415. this._checkUniform(name);
  42416. this._floatsArrays[name] = value;
  42417. return this;
  42418. };
  42419. ShaderMaterial.prototype.setColor3 = function (name, value) {
  42420. this._checkUniform(name);
  42421. this._colors3[name] = value;
  42422. return this;
  42423. };
  42424. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  42425. this._checkUniform(name);
  42426. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  42427. color.toArray(arr, arr.length);
  42428. return arr;
  42429. }, []);
  42430. return this;
  42431. };
  42432. ShaderMaterial.prototype.setColor4 = function (name, value) {
  42433. this._checkUniform(name);
  42434. this._colors4[name] = value;
  42435. return this;
  42436. };
  42437. ShaderMaterial.prototype.setVector2 = function (name, value) {
  42438. this._checkUniform(name);
  42439. this._vectors2[name] = value;
  42440. return this;
  42441. };
  42442. ShaderMaterial.prototype.setVector3 = function (name, value) {
  42443. this._checkUniform(name);
  42444. this._vectors3[name] = value;
  42445. return this;
  42446. };
  42447. ShaderMaterial.prototype.setVector4 = function (name, value) {
  42448. this._checkUniform(name);
  42449. this._vectors4[name] = value;
  42450. return this;
  42451. };
  42452. ShaderMaterial.prototype.setMatrix = function (name, value) {
  42453. this._checkUniform(name);
  42454. this._matrices[name] = value;
  42455. return this;
  42456. };
  42457. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  42458. this._checkUniform(name);
  42459. this._matrices3x3[name] = value;
  42460. return this;
  42461. };
  42462. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  42463. this._checkUniform(name);
  42464. this._matrices2x2[name] = value;
  42465. return this;
  42466. };
  42467. ShaderMaterial.prototype.setArray3 = function (name, value) {
  42468. this._checkUniform(name);
  42469. this._vectors3Arrays[name] = value;
  42470. return this;
  42471. };
  42472. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  42473. if (!mesh) {
  42474. return true;
  42475. }
  42476. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  42477. return false;
  42478. }
  42479. return false;
  42480. };
  42481. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  42482. var scene = this.getScene();
  42483. var engine = scene.getEngine();
  42484. if (!this.checkReadyOnEveryCall) {
  42485. if (this._renderId === scene.getRenderId()) {
  42486. if (this._checkCache(scene, mesh, useInstances)) {
  42487. return true;
  42488. }
  42489. }
  42490. }
  42491. // Instances
  42492. var defines = [];
  42493. var attribs = [];
  42494. var fallbacks = new BABYLON.EffectFallbacks();
  42495. if (useInstances) {
  42496. defines.push("#define INSTANCES");
  42497. }
  42498. for (var index = 0; index < this._options.defines.length; index++) {
  42499. defines.push(this._options.defines[index]);
  42500. }
  42501. for (var index = 0; index < this._options.attributes.length; index++) {
  42502. attribs.push(this._options.attributes[index]);
  42503. }
  42504. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  42505. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42506. defines.push("#define VERTEXCOLOR");
  42507. }
  42508. // Bones
  42509. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders) {
  42510. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42511. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42512. if (mesh.numBoneInfluencers > 4) {
  42513. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42514. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42515. }
  42516. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  42517. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  42518. fallbacks.addCPUSkinningFallback(0, mesh);
  42519. if (this._options.uniforms.indexOf("mBones") === -1) {
  42520. this._options.uniforms.push("mBones");
  42521. }
  42522. }
  42523. else {
  42524. defines.push("#define NUM_BONE_INFLUENCERS 0");
  42525. }
  42526. // Textures
  42527. for (var name in this._textures) {
  42528. if (!this._textures[name].isReady()) {
  42529. return false;
  42530. }
  42531. }
  42532. // Alpha test
  42533. if (engine.getAlphaTesting()) {
  42534. defines.push("#define ALPHATEST");
  42535. }
  42536. var previousEffect = this._effect;
  42537. var join = defines.join("\n");
  42538. this._effect = engine.createEffect(this._shaderPath, {
  42539. attributes: attribs,
  42540. uniformsNames: this._options.uniforms,
  42541. uniformBuffersNames: this._options.uniformBuffers,
  42542. samplers: this._options.samplers,
  42543. defines: join,
  42544. fallbacks: fallbacks,
  42545. onCompiled: this.onCompiled,
  42546. onError: this.onError
  42547. }, engine);
  42548. if (!this._effect.isReady()) {
  42549. return false;
  42550. }
  42551. if (previousEffect !== this._effect) {
  42552. scene.resetCachedMaterial();
  42553. }
  42554. this._renderId = scene.getRenderId();
  42555. return true;
  42556. };
  42557. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42558. var scene = this.getScene();
  42559. if (this._options.uniforms.indexOf("world") !== -1) {
  42560. this._effect.setMatrix("world", world);
  42561. }
  42562. if (this._options.uniforms.indexOf("worldView") !== -1) {
  42563. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  42564. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  42565. }
  42566. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  42567. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  42568. }
  42569. };
  42570. ShaderMaterial.prototype.bind = function (world, mesh) {
  42571. // Std values
  42572. this.bindOnlyWorldMatrix(world);
  42573. if (this.getScene().getCachedMaterial() !== this) {
  42574. if (this._options.uniforms.indexOf("view") !== -1) {
  42575. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  42576. }
  42577. if (this._options.uniforms.indexOf("projection") !== -1) {
  42578. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  42579. }
  42580. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  42581. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  42582. }
  42583. // Bones
  42584. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  42585. var name;
  42586. // Texture
  42587. for (name in this._textures) {
  42588. this._effect.setTexture(name, this._textures[name]);
  42589. }
  42590. // Texture arrays
  42591. for (name in this._textureArrays) {
  42592. this._effect.setTextureArray(name, this._textureArrays[name]);
  42593. }
  42594. // Float
  42595. for (name in this._floats) {
  42596. this._effect.setFloat(name, this._floats[name]);
  42597. }
  42598. // Float s
  42599. for (name in this._floatsArrays) {
  42600. this._effect.setArray(name, this._floatsArrays[name]);
  42601. }
  42602. // Color3
  42603. for (name in this._colors3) {
  42604. this._effect.setColor3(name, this._colors3[name]);
  42605. }
  42606. for (name in this._colors3Arrays) {
  42607. this._effect.setArray3(name, this._colors3Arrays[name]);
  42608. }
  42609. // Color4
  42610. for (name in this._colors4) {
  42611. var color = this._colors4[name];
  42612. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  42613. }
  42614. // Vector2
  42615. for (name in this._vectors2) {
  42616. this._effect.setVector2(name, this._vectors2[name]);
  42617. }
  42618. // Vector3
  42619. for (name in this._vectors3) {
  42620. this._effect.setVector3(name, this._vectors3[name]);
  42621. }
  42622. // Vector4
  42623. for (name in this._vectors4) {
  42624. this._effect.setVector4(name, this._vectors4[name]);
  42625. }
  42626. // Matrix
  42627. for (name in this._matrices) {
  42628. this._effect.setMatrix(name, this._matrices[name]);
  42629. }
  42630. // Matrix 3x3
  42631. for (name in this._matrices3x3) {
  42632. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  42633. }
  42634. // Matrix 2x2
  42635. for (name in this._matrices2x2) {
  42636. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  42637. }
  42638. // Vector3Array
  42639. for (name in this._vectors3Arrays) {
  42640. this._effect.setArray3(name, this._vectors3Arrays[name]);
  42641. }
  42642. }
  42643. this._afterBind(mesh);
  42644. };
  42645. ShaderMaterial.prototype.getActiveTextures = function () {
  42646. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42647. for (var name in this._textures) {
  42648. activeTextures.push(this._textures[name]);
  42649. }
  42650. for (var name in this._textureArrays) {
  42651. var array = this._textureArrays[name];
  42652. for (var index = 0; index < array.length; index++) {
  42653. activeTextures.push(array[index]);
  42654. }
  42655. }
  42656. return activeTextures;
  42657. };
  42658. ShaderMaterial.prototype.hasTexture = function (texture) {
  42659. if (_super.prototype.hasTexture.call(this, texture)) {
  42660. return true;
  42661. }
  42662. for (var name in this._textures) {
  42663. if (this._textures[name] === texture) {
  42664. return true;
  42665. }
  42666. }
  42667. for (var name in this._textureArrays) {
  42668. var array = this._textureArrays[name];
  42669. for (var index = 0; index < array.length; index++) {
  42670. if (array[index] === texture) {
  42671. return true;
  42672. }
  42673. }
  42674. }
  42675. return false;
  42676. };
  42677. ShaderMaterial.prototype.clone = function (name) {
  42678. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  42679. return newShaderMaterial;
  42680. };
  42681. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  42682. if (forceDisposeTextures) {
  42683. var name;
  42684. for (name in this._textures) {
  42685. this._textures[name].dispose();
  42686. }
  42687. for (name in this._textureArrays) {
  42688. var array = this._textureArrays[name];
  42689. for (var index = 0; index < array.length; index++) {
  42690. array[index].dispose();
  42691. }
  42692. }
  42693. }
  42694. this._textures = {};
  42695. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  42696. };
  42697. ShaderMaterial.prototype.serialize = function () {
  42698. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  42699. serializationObject.customType = "BABYLON.ShaderMaterial";
  42700. serializationObject.options = this._options;
  42701. serializationObject.shaderPath = this._shaderPath;
  42702. var name;
  42703. // Texture
  42704. serializationObject.textures = {};
  42705. for (name in this._textures) {
  42706. serializationObject.textures[name] = this._textures[name].serialize();
  42707. }
  42708. // Texture arrays
  42709. serializationObject.textureArrays = {};
  42710. for (name in this._textureArrays) {
  42711. serializationObject.textureArrays[name] = [];
  42712. var array = this._textureArrays[name];
  42713. for (var index = 0; index < array.length; index++) {
  42714. serializationObject.textureArrays[name].push(array[index].serialize());
  42715. }
  42716. }
  42717. // Float
  42718. serializationObject.floats = {};
  42719. for (name in this._floats) {
  42720. serializationObject.floats[name] = this._floats[name];
  42721. }
  42722. // Float s
  42723. serializationObject.floatArrays = {};
  42724. for (name in this._floatsArrays) {
  42725. serializationObject.floatArrays[name] = this._floatsArrays[name];
  42726. }
  42727. // Color3
  42728. serializationObject.colors3 = {};
  42729. for (name in this._colors3) {
  42730. serializationObject.colors3[name] = this._colors3[name].asArray();
  42731. }
  42732. // Color3 array
  42733. serializationObject.colors3Arrays = {};
  42734. for (name in this._colors3Arrays) {
  42735. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  42736. }
  42737. // Color4
  42738. serializationObject.colors4 = {};
  42739. for (name in this._colors4) {
  42740. serializationObject.colors4[name] = this._colors4[name].asArray();
  42741. }
  42742. // Vector2
  42743. serializationObject.vectors2 = {};
  42744. for (name in this._vectors2) {
  42745. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  42746. }
  42747. // Vector3
  42748. serializationObject.vectors3 = {};
  42749. for (name in this._vectors3) {
  42750. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  42751. }
  42752. // Vector4
  42753. serializationObject.vectors4 = {};
  42754. for (name in this._vectors4) {
  42755. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  42756. }
  42757. // Matrix
  42758. serializationObject.matrices = {};
  42759. for (name in this._matrices) {
  42760. serializationObject.matrices[name] = this._matrices[name].asArray();
  42761. }
  42762. // Matrix 3x3
  42763. serializationObject.matrices3x3 = {};
  42764. for (name in this._matrices3x3) {
  42765. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  42766. }
  42767. // Matrix 2x2
  42768. serializationObject.matrices2x2 = {};
  42769. for (name in this._matrices2x2) {
  42770. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  42771. }
  42772. // Vector3Array
  42773. serializationObject.vectors3Arrays = {};
  42774. for (name in this._vectors3Arrays) {
  42775. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  42776. }
  42777. return serializationObject;
  42778. };
  42779. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  42780. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  42781. var name;
  42782. // Texture
  42783. for (name in source.textures) {
  42784. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  42785. }
  42786. // Texture arrays
  42787. for (name in source.textureArrays) {
  42788. var array = source.textureArrays[name];
  42789. var textureArray = new Array();
  42790. for (var index = 0; index < array.length; index++) {
  42791. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  42792. }
  42793. material.setTextureArray(name, textureArray);
  42794. }
  42795. // Float
  42796. for (name in source.floats) {
  42797. material.setFloat(name, source.floats[name]);
  42798. }
  42799. // Float s
  42800. for (name in source.floatsArrays) {
  42801. material.setFloats(name, source.floatsArrays[name]);
  42802. }
  42803. // Color3
  42804. for (name in source.colors3) {
  42805. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  42806. }
  42807. // Color3 arrays
  42808. for (name in source.colors3Arrays) {
  42809. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  42810. if (i % 3 === 0) {
  42811. arr.push([num]);
  42812. }
  42813. else {
  42814. arr[arr.length - 1].push(num);
  42815. }
  42816. return arr;
  42817. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  42818. material.setColor3Array(name, colors);
  42819. }
  42820. // Color4
  42821. for (name in source.colors4) {
  42822. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  42823. }
  42824. // Vector2
  42825. for (name in source.vectors2) {
  42826. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  42827. }
  42828. // Vector3
  42829. for (name in source.vectors3) {
  42830. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  42831. }
  42832. // Vector4
  42833. for (name in source.vectors4) {
  42834. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  42835. }
  42836. // Matrix
  42837. for (name in source.matrices) {
  42838. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  42839. }
  42840. // Matrix 3x3
  42841. for (name in source.matrices3x3) {
  42842. material.setMatrix3x3(name, source.matrices3x3[name]);
  42843. }
  42844. // Matrix 2x2
  42845. for (name in source.matrices2x2) {
  42846. material.setMatrix2x2(name, source.matrices2x2[name]);
  42847. }
  42848. // Vector3Array
  42849. for (name in source.vectors3Arrays) {
  42850. material.setArray3(name, source.vectors3Arrays[name]);
  42851. }
  42852. return material;
  42853. };
  42854. return ShaderMaterial;
  42855. }(BABYLON.Material));
  42856. BABYLON.ShaderMaterial = ShaderMaterial;
  42857. })(BABYLON || (BABYLON = {}));
  42858. //# sourceMappingURL=babylon.shaderMaterial.js.map
  42859. var BABYLON;
  42860. (function (BABYLON) {
  42861. var MeshBuilder = (function () {
  42862. function MeshBuilder() {
  42863. }
  42864. MeshBuilder.updateSideOrientation = function (orientation, scene) {
  42865. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  42866. return BABYLON.Mesh.DOUBLESIDE;
  42867. }
  42868. if (orientation === undefined || orientation === null) {
  42869. return BABYLON.Mesh.FRONTSIDE;
  42870. }
  42871. return orientation;
  42872. };
  42873. /**
  42874. * Creates a box mesh.
  42875. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  42876. * The parameter `size` sets the size (float) of each box side (default 1).
  42877. * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`).
  42878. * 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).
  42879. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  42880. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42881. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42882. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42883. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42884. */
  42885. MeshBuilder.CreateBox = function (name, options, scene) {
  42886. var box = new BABYLON.Mesh(name, scene);
  42887. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42888. box.sideOrientation = options.sideOrientation;
  42889. var vertexData = BABYLON.VertexData.CreateBox(options);
  42890. vertexData.applyToMesh(box, options.updatable);
  42891. return box;
  42892. };
  42893. /**
  42894. * Creates a sphere mesh.
  42895. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  42896. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  42897. * 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`).
  42898. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  42899. * 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
  42900. * 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).
  42901. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42902. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42903. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42904. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42905. */
  42906. MeshBuilder.CreateSphere = function (name, options, scene) {
  42907. var sphere = new BABYLON.Mesh(name, scene);
  42908. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42909. sphere.sideOrientation = options.sideOrientation;
  42910. var vertexData = BABYLON.VertexData.CreateSphere(options);
  42911. vertexData.applyToMesh(sphere, options.updatable);
  42912. return sphere;
  42913. };
  42914. /**
  42915. * Creates a plane polygonal mesh. By default, this is a disc.
  42916. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#disc
  42917. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  42918. * 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.
  42919. * 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
  42920. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42921. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42922. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42924. */
  42925. MeshBuilder.CreateDisc = function (name, options, scene) {
  42926. var disc = new BABYLON.Mesh(name, scene);
  42927. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42928. disc.sideOrientation = options.sideOrientation;
  42929. var vertexData = BABYLON.VertexData.CreateDisc(options);
  42930. vertexData.applyToMesh(disc, options.updatable);
  42931. return disc;
  42932. };
  42933. /**
  42934. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  42935. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#icosphere
  42936. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  42937. * 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`).
  42938. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  42939. * 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.
  42940. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42941. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42942. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42943. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42944. */
  42945. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  42946. var sphere = new BABYLON.Mesh(name, scene);
  42947. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42948. sphere.sideOrientation = options.sideOrientation;
  42949. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  42950. vertexData.applyToMesh(sphere, options.updatable);
  42951. return sphere;
  42952. };
  42953. ;
  42954. /**
  42955. * Creates a ribbon mesh.
  42956. * 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.
  42957. *
  42958. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  42959. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  42960. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  42961. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  42962. * 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.
  42963. * 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.
  42964. * 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
  42965. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  42966. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  42967. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  42968. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  42969. * The parameter `uvs` is an optional flat array of `Vector2` to update/set each ribbon vertex with its own custom UV values instead of the computed ones.
  42970. * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values.
  42971. * Note that if you use the parameters `uvs` or `colors`, the passed arrays must be populated with the right number of elements, it is to say the number of ribbon vertices. Remember that
  42972. * if you set `closePath` to `true`, there's one extra vertex per path in the geometry.
  42973. * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time.
  42974. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  42975. */
  42976. MeshBuilder.CreateRibbon = function (name, options, scene) {
  42977. var pathArray = options.pathArray;
  42978. var closeArray = options.closeArray;
  42979. var closePath = options.closePath;
  42980. var offset = options.offset;
  42981. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  42982. var instance = options.instance;
  42983. var updatable = options.updatable;
  42984. if (instance) {
  42985. // positionFunction : ribbon case
  42986. // only pathArray and sideOrientation parameters are taken into account for positions update
  42987. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  42988. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  42989. var positionFunction = function (positions) {
  42990. var minlg = pathArray[0].length;
  42991. var i = 0;
  42992. var ns = (instance.sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  42993. for (var si = 1; si <= ns; si++) {
  42994. for (var p = 0; p < pathArray.length; p++) {
  42995. var path = pathArray[p];
  42996. var l = path.length;
  42997. minlg = (minlg < l) ? minlg : l;
  42998. var j = 0;
  42999. while (j < minlg) {
  43000. positions[i] = path[j].x;
  43001. positions[i + 1] = path[j].y;
  43002. positions[i + 2] = path[j].z;
  43003. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  43004. BABYLON.Tmp.Vector3[0].x = path[j].x;
  43005. }
  43006. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  43007. BABYLON.Tmp.Vector3[1].x = path[j].x;
  43008. }
  43009. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  43010. BABYLON.Tmp.Vector3[0].y = path[j].y;
  43011. }
  43012. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  43013. BABYLON.Tmp.Vector3[1].y = path[j].y;
  43014. }
  43015. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  43016. BABYLON.Tmp.Vector3[0].z = path[j].z;
  43017. }
  43018. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  43019. BABYLON.Tmp.Vector3[1].z = path[j].z;
  43020. }
  43021. j++;
  43022. i += 3;
  43023. }
  43024. if (instance._closePath) {
  43025. positions[i] = path[0].x;
  43026. positions[i + 1] = path[0].y;
  43027. positions[i + 2] = path[0].z;
  43028. i += 3;
  43029. }
  43030. }
  43031. }
  43032. };
  43033. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43034. positionFunction(positions);
  43035. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  43036. instance._boundingInfo.update(instance._worldMatrix);
  43037. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  43038. if (options.colors) {
  43039. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  43040. for (var c = 0; c < options.colors.length; c++) {
  43041. colors[c * 4] = options.colors[c].r;
  43042. colors[c * 4 + 1] = options.colors[c].g;
  43043. colors[c * 4 + 2] = options.colors[c].b;
  43044. colors[c * 4 + 3] = options.colors[c].a;
  43045. }
  43046. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  43047. }
  43048. if (options.uvs) {
  43049. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  43050. for (var i = 0; i < options.uvs.length; i++) {
  43051. uvs[i * 2] = options.uvs[i].x;
  43052. uvs[i * 2 + 1] = options.uvs[i].y;
  43053. }
  43054. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  43055. }
  43056. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  43057. var indices = instance.getIndices();
  43058. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43059. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  43060. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  43061. if (instance._closePath) {
  43062. var indexFirst = 0;
  43063. var indexLast = 0;
  43064. for (var p = 0; p < pathArray.length; p++) {
  43065. indexFirst = instance._idx[p] * 3;
  43066. if (p + 1 < pathArray.length) {
  43067. indexLast = (instance._idx[p + 1] - 1) * 3;
  43068. }
  43069. else {
  43070. indexLast = normals.length - 3;
  43071. }
  43072. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  43073. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  43074. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  43075. normals[indexLast] = normals[indexFirst];
  43076. normals[indexLast + 1] = normals[indexFirst + 1];
  43077. normals[indexLast + 2] = normals[indexFirst + 2];
  43078. }
  43079. }
  43080. if (!(instance.areNormalsFrozen)) {
  43081. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  43082. }
  43083. }
  43084. return instance;
  43085. }
  43086. else {
  43087. var ribbon = new BABYLON.Mesh(name, scene);
  43088. ribbon.sideOrientation = sideOrientation;
  43089. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  43090. if (closePath) {
  43091. ribbon._idx = vertexData._idx;
  43092. }
  43093. ribbon._closePath = closePath;
  43094. ribbon._closeArray = closeArray;
  43095. vertexData.applyToMesh(ribbon, updatable);
  43096. return ribbon;
  43097. }
  43098. };
  43099. /**
  43100. * Creates a cylinder or a cone mesh.
  43101. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  43102. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  43103. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  43104. * 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.
  43105. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  43106. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  43107. * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  43108. * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  43109. * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  43110. * 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).
  43111. * 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
  43112. * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  43113. * 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
  43114. * 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.
  43115. * If `enclose` is false, a ring surface is one element.
  43116. * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  43117. * 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
  43118. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43119. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43120. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43121. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43122. */
  43123. MeshBuilder.CreateCylinder = function (name, options, scene) {
  43124. var cylinder = new BABYLON.Mesh(name, scene);
  43125. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43126. cylinder.sideOrientation = options.sideOrientation;
  43127. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  43128. vertexData.applyToMesh(cylinder, options.updatable);
  43129. return cylinder;
  43130. };
  43131. /**
  43132. * Creates a torus mesh.
  43133. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  43134. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  43135. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  43136. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  43137. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43138. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43139. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43140. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43141. */
  43142. MeshBuilder.CreateTorus = function (name, options, scene) {
  43143. var torus = new BABYLON.Mesh(name, scene);
  43144. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43145. torus.sideOrientation = options.sideOrientation;
  43146. var vertexData = BABYLON.VertexData.CreateTorus(options);
  43147. vertexData.applyToMesh(torus, options.updatable);
  43148. return torus;
  43149. };
  43150. /**
  43151. * Creates a torus knot mesh.
  43152. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  43153. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  43154. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  43155. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  43156. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  43157. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43158. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43159. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43160. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43161. */
  43162. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  43163. var torusKnot = new BABYLON.Mesh(name, scene);
  43164. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43165. torusKnot.sideOrientation = options.sideOrientation;
  43166. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  43167. vertexData.applyToMesh(torusKnot, options.updatable);
  43168. return torusKnot;
  43169. };
  43170. /**
  43171. * Creates a line system mesh.
  43172. * A line system is a pool of many lines gathered in a single mesh.
  43173. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#linesystem
  43174. * 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.
  43175. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function.
  43176. * The parameter `lines` is an array of lines, each line being an array of successive Vector3.
  43177. * 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
  43178. * 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
  43179. * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines.
  43180. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43181. */
  43182. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  43183. var instance = options.instance;
  43184. var lines = options.lines;
  43185. if (instance) {
  43186. var positionFunction = function (positions) {
  43187. var i = 0;
  43188. for (var l = 0; l < lines.length; l++) {
  43189. var points = lines[l];
  43190. for (var p = 0; p < points.length; p++) {
  43191. positions[i] = points[p].x;
  43192. positions[i + 1] = points[p].y;
  43193. positions[i + 2] = points[p].z;
  43194. i += 3;
  43195. }
  43196. }
  43197. };
  43198. instance.updateMeshPositions(positionFunction, false);
  43199. return instance;
  43200. }
  43201. // line system creation
  43202. var lineSystem = new BABYLON.LinesMesh(name, scene);
  43203. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  43204. vertexData.applyToMesh(lineSystem, options.updatable);
  43205. return lineSystem;
  43206. };
  43207. /**
  43208. * Creates a line mesh.
  43209. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lines
  43210. * 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.
  43211. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43212. * The parameter `points` is an array successive Vector3.
  43213. * 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
  43214. * When updating an instance, remember that only point positions can change, not the number of points.
  43215. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43216. */
  43217. MeshBuilder.CreateLines = function (name, options, scene) {
  43218. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance }, scene);
  43219. return lines;
  43220. };
  43221. /**
  43222. * Creates a dashed line mesh.
  43223. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#dashed-lines
  43224. * 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.
  43225. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  43226. * The parameter `points` is an array successive Vector3.
  43227. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  43228. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  43229. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  43230. * 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
  43231. * When updating an instance, remember that only point positions can change, not the number of points.
  43232. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43233. */
  43234. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  43235. var points = options.points;
  43236. var instance = options.instance;
  43237. var gapSize = options.gapSize;
  43238. var dashNb = options.dashNb;
  43239. var dashSize = options.dashSize;
  43240. if (instance) {
  43241. var positionFunction = function (positions) {
  43242. var curvect = BABYLON.Vector3.Zero();
  43243. var nbSeg = positions.length / 6;
  43244. var lg = 0;
  43245. var nb = 0;
  43246. var shft = 0;
  43247. var dashshft = 0;
  43248. var curshft = 0;
  43249. var p = 0;
  43250. var i = 0;
  43251. var j = 0;
  43252. for (i = 0; i < points.length - 1; i++) {
  43253. points[i + 1].subtractToRef(points[i], curvect);
  43254. lg += curvect.length();
  43255. }
  43256. shft = lg / nbSeg;
  43257. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  43258. for (i = 0; i < points.length - 1; i++) {
  43259. points[i + 1].subtractToRef(points[i], curvect);
  43260. nb = Math.floor(curvect.length() / shft);
  43261. curvect.normalize();
  43262. j = 0;
  43263. while (j < nb && p < positions.length) {
  43264. curshft = shft * j;
  43265. positions[p] = points[i].x + curshft * curvect.x;
  43266. positions[p + 1] = points[i].y + curshft * curvect.y;
  43267. positions[p + 2] = points[i].z + curshft * curvect.z;
  43268. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  43269. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  43270. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  43271. p += 6;
  43272. j++;
  43273. }
  43274. }
  43275. while (p < positions.length) {
  43276. positions[p] = points[i].x;
  43277. positions[p + 1] = points[i].y;
  43278. positions[p + 2] = points[i].z;
  43279. p += 3;
  43280. }
  43281. };
  43282. instance.updateMeshPositions(positionFunction, false);
  43283. return instance;
  43284. }
  43285. // dashed lines creation
  43286. var dashedLines = new BABYLON.LinesMesh(name, scene);
  43287. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  43288. vertexData.applyToMesh(dashedLines, options.updatable);
  43289. dashedLines.dashSize = dashSize;
  43290. dashedLines.gapSize = gapSize;
  43291. return dashedLines;
  43292. };
  43293. /**
  43294. * Creates an extruded shape mesh.
  43295. * 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.
  43296. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#extruded-shapes
  43297. *
  43298. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43299. * 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
  43300. * extruded along the Z axis.
  43301. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43302. * 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.
  43303. * The parameter `scale` (float, default 1) is the value to scale the shape.
  43304. * 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
  43305. * 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
  43306. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43308. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43309. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43310. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43311. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43312. */
  43313. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  43314. var path = options.path;
  43315. var shape = options.shape;
  43316. var scale = options.scale || 1;
  43317. var rotation = options.rotation || 0;
  43318. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43319. var updatable = options.updatable;
  43320. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43321. var instance = options.instance;
  43322. var invertUV = options.invertUV || false;
  43323. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, scale, rotation, null, null, false, false, cap, false, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43324. };
  43325. /**
  43326. * Creates an custom extruded shape mesh.
  43327. * 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.
  43328. * tuto :http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#custom-extruded-shapes
  43329. *
  43330. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/tutorials/Parametric_Shapes#extrusion
  43331. * 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
  43332. * extruded along the Z axis.
  43333. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  43334. * 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
  43335. * and the distance of this point from the begining of the path :
  43336. * ```javascript
  43337. * var rotationFunction = function(i, distance) {
  43338. * // do things
  43339. * return rotationValue; }
  43340. * ```
  43341. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  43342. * 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
  43343. * and the distance of this point from the begining of the path :
  43344. * ```javascript
  43345. * var scaleFunction = function(i, distance) {
  43346. * // do things
  43347. * return scaleValue;}
  43348. * ```
  43349. * It must returns a float value that will be the scale value applied to the shape on each path point.
  43350. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  43351. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  43352. * 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
  43353. * 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
  43354. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  43355. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43356. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43357. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43358. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43359. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43360. */
  43361. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  43362. var path = options.path;
  43363. var shape = options.shape;
  43364. var scaleFunction = options.scaleFunction || (function () { return 1; });
  43365. var rotationFunction = options.rotationFunction || (function () { return 0; });
  43366. var ribbonCloseArray = options.ribbonCloseArray || false;
  43367. var ribbonClosePath = options.ribbonClosePath || false;
  43368. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  43369. var updatable = options.updatable;
  43370. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43371. var instance = options.instance;
  43372. var invertUV = options.invertUV || false;
  43373. return MeshBuilder._ExtrudeShapeGeneric(name, shape, path, null, null, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, true, scene, updatable, sideOrientation, instance, invertUV, options.frontUVs, options.backUVs);
  43374. };
  43375. /**
  43376. * Creates lathe mesh.
  43377. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  43378. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#lathe
  43379. *
  43380. * 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
  43381. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  43382. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  43383. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  43384. * 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.
  43385. * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc".
  43386. * 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
  43387. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43388. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43389. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43390. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43391. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43392. */
  43393. MeshBuilder.CreateLathe = function (name, options, scene) {
  43394. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  43395. var closed = (options.closed === undefined) ? true : options.closed;
  43396. var shape = options.shape;
  43397. var radius = options.radius || 1;
  43398. var tessellation = options.tessellation || 64;
  43399. var updatable = options.updatable;
  43400. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43401. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43402. var pi2 = Math.PI * 2;
  43403. var paths = new Array();
  43404. var invertUV = options.invertUV || false;
  43405. var i = 0;
  43406. var p = 0;
  43407. var step = pi2 / tessellation * arc;
  43408. var rotated;
  43409. var path = new Array();
  43410. ;
  43411. for (i = 0; i <= tessellation; i++) {
  43412. var path = [];
  43413. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  43414. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  43415. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  43416. }
  43417. for (p = 0; p < shape.length; p++) {
  43418. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  43419. path.push(rotated);
  43420. }
  43421. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  43422. 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));
  43423. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  43424. }
  43425. paths.push(path);
  43426. }
  43427. // lathe ribbon
  43428. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43429. return lathe;
  43430. };
  43431. /**
  43432. * Creates a plane mesh.
  43433. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43434. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  43435. * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`).
  43436. * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane.
  43437. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43438. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43439. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43440. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43441. */
  43442. MeshBuilder.CreatePlane = function (name, options, scene) {
  43443. var plane = new BABYLON.Mesh(name, scene);
  43444. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43445. plane.sideOrientation = options.sideOrientation;
  43446. var vertexData = BABYLON.VertexData.CreatePlane(options);
  43447. vertexData.applyToMesh(plane, options.updatable);
  43448. if (options.sourcePlane) {
  43449. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  43450. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  43451. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  43452. plane.rotate(vectorProduct, product);
  43453. }
  43454. return plane;
  43455. };
  43456. /**
  43457. * Creates a ground mesh.
  43458. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  43459. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  43460. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  43461. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43462. */
  43463. MeshBuilder.CreateGround = function (name, options, scene) {
  43464. var ground = new BABYLON.GroundMesh(name, scene);
  43465. ground._setReady(false);
  43466. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  43467. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  43468. ground._width = options.width || 1;
  43469. ground._height = options.height || 1;
  43470. ground._maxX = ground._width / 2;
  43471. ground._maxZ = ground._height / 2;
  43472. ground._minX = -ground._maxX;
  43473. ground._minZ = -ground._maxZ;
  43474. var vertexData = BABYLON.VertexData.CreateGround(options);
  43475. vertexData.applyToMesh(ground, options.updatable);
  43476. ground._setReady(true);
  43477. return ground;
  43478. };
  43479. /**
  43480. * Creates a tiled ground mesh.
  43481. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  43482. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  43483. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  43484. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  43485. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  43486. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  43487. * numbers of subdivisions on the ground width and height of each tile.
  43488. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43489. */
  43490. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  43491. var tiledGround = new BABYLON.Mesh(name, scene);
  43492. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  43493. vertexData.applyToMesh(tiledGround, options.updatable);
  43494. return tiledGround;
  43495. };
  43496. /**
  43497. * Creates a ground mesh from a height map.
  43498. * tuto : http://doc.babylonjs.com/tutorials/14._Height_Map
  43499. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  43500. * The parameter `url` sets the URL of the height map image resource.
  43501. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  43502. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  43503. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  43504. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  43505. * The parameter `colorFilter` (optional Color3, default (0.3, 0.59, 0.11) ) is the filter to apply to the image pixel colors to compute the height.
  43506. * 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).
  43507. * This function is passed the newly built mesh :
  43508. * ```javascript
  43509. * function(mesh) { // do things
  43510. * return; }
  43511. * ```
  43512. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43513. */
  43514. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  43515. var width = options.width || 10.0;
  43516. var height = options.height || 10.0;
  43517. var subdivisions = options.subdivisions || 1 | 0;
  43518. var minHeight = options.minHeight || 0.0;
  43519. var maxHeight = options.maxHeight || 10.0;
  43520. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  43521. var updatable = options.updatable;
  43522. var onReady = options.onReady;
  43523. var ground = new BABYLON.GroundMesh(name, scene);
  43524. ground._subdivisionsX = subdivisions;
  43525. ground._subdivisionsY = subdivisions;
  43526. ground._width = width;
  43527. ground._height = height;
  43528. ground._maxX = ground._width / 2.0;
  43529. ground._maxZ = ground._height / 2.0;
  43530. ground._minX = -ground._maxX;
  43531. ground._minZ = -ground._maxZ;
  43532. ground._setReady(false);
  43533. var onload = function (img) {
  43534. // Getting height map data
  43535. var canvas = document.createElement("canvas");
  43536. var context = canvas.getContext("2d");
  43537. var bufferWidth = img.width;
  43538. var bufferHeight = img.height;
  43539. canvas.width = bufferWidth;
  43540. canvas.height = bufferHeight;
  43541. context.drawImage(img, 0, 0);
  43542. // Create VertexData from map data
  43543. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  43544. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  43545. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  43546. width: width, height: height,
  43547. subdivisions: subdivisions,
  43548. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  43549. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  43550. });
  43551. vertexData.applyToMesh(ground, updatable);
  43552. ground._setReady(true);
  43553. //execute ready callback, if set
  43554. if (onReady) {
  43555. onReady(ground);
  43556. }
  43557. };
  43558. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  43559. return ground;
  43560. };
  43561. /**
  43562. * Creates a polygon mesh.
  43563. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  43564. * The parameter `shape` is a required array of successive Vector3 representing the corners of the polygon in th XoZ plane, that is y = 0 for all vectors.
  43565. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43566. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43567. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43568. * Remember you can only change the shape positions, not their number when updating a polygon.
  43569. */
  43570. MeshBuilder.CreatePolygon = function (name, options, scene) {
  43571. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43572. var shape = options.shape;
  43573. var holes = options.holes || [];
  43574. var depth = options.depth || 0;
  43575. var contours = [];
  43576. var hole = [];
  43577. for (var i = 0; i < shape.length; i++) {
  43578. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  43579. }
  43580. var epsilon = 0.00000001;
  43581. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  43582. contours.pop();
  43583. }
  43584. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  43585. for (var hNb = 0; hNb < holes.length; hNb++) {
  43586. hole = [];
  43587. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  43588. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  43589. }
  43590. polygonTriangulation.addHole(hole);
  43591. }
  43592. var polygon = polygonTriangulation.build(options.updatable, depth);
  43593. polygon.sideOrientation = options.sideOrientation;
  43594. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  43595. vertexData.applyToMesh(polygon, options.updatable);
  43596. return polygon;
  43597. };
  43598. ;
  43599. /**
  43600. * Creates an extruded polygon mesh, with depth in the Y direction.
  43601. * You can set different colors and different images to the top, bottom and extruded side by using the parameters `faceColors` (an array of 3 Color3 elements) and `faceUV` (an array of 3 Vector4 elements).
  43602. * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  43603. */
  43604. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  43605. return MeshBuilder.CreatePolygon(name, options, scene);
  43606. };
  43607. ;
  43608. /**
  43609. * Creates a tube mesh.
  43610. * 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.
  43611. *
  43612. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  43613. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  43614. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  43615. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  43616. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  43617. * 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.
  43618. * It must return a radius value (positive float) :
  43619. * ```javascript
  43620. * var radiusFunction = function(i, distance) {
  43621. * // do things
  43622. * return radius; }
  43623. * ```
  43624. * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc.
  43625. * 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
  43626. * 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
  43627. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43628. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43629. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43630. * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  43631. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43632. */
  43633. MeshBuilder.CreateTube = function (name, options, scene) {
  43634. var path = options.path;
  43635. var radius = options.radius || 1.0;
  43636. var tessellation = options.tessellation || 64 | 0;
  43637. var radiusFunction = options.radiusFunction;
  43638. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  43639. var invertUV = options.invertUV || false;
  43640. var updatable = options.updatable;
  43641. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43642. var instance = options.instance;
  43643. options.arc = (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  43644. // tube geometry
  43645. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  43646. var tangents = path3D.getTangents();
  43647. var normals = path3D.getNormals();
  43648. var distances = path3D.getDistances();
  43649. var pi2 = Math.PI * 2;
  43650. var step = pi2 / tessellation * arc;
  43651. var returnRadius = function () { return radius; };
  43652. var radiusFunctionFinal = radiusFunction || returnRadius;
  43653. var circlePath;
  43654. var rad;
  43655. var normal;
  43656. var rotated;
  43657. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43658. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43659. for (var i = 0; i < path.length; i++) {
  43660. rad = radiusFunctionFinal(i, distances[i]); // current radius
  43661. circlePath = Array(); // current circle array
  43662. normal = normals[i]; // current normal
  43663. for (var t = 0; t < tessellation; t++) {
  43664. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  43665. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  43666. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  43667. rotated.scaleInPlace(rad).addInPlace(path[i]);
  43668. circlePath[t] = rotated;
  43669. }
  43670. circlePaths[index] = circlePath;
  43671. index++;
  43672. }
  43673. // cap
  43674. var capPath = function (nbPoints, pathIndex) {
  43675. var pointCap = Array();
  43676. for (var i = 0; i < nbPoints; i++) {
  43677. pointCap.push(path[pathIndex]);
  43678. }
  43679. return pointCap;
  43680. };
  43681. switch (cap) {
  43682. case BABYLON.Mesh.NO_CAP:
  43683. break;
  43684. case BABYLON.Mesh.CAP_START:
  43685. circlePaths[0] = capPath(tessellation, 0);
  43686. circlePaths[1] = circlePaths[2].slice(0);
  43687. break;
  43688. case BABYLON.Mesh.CAP_END:
  43689. circlePaths[index] = circlePaths[index - 1].slice(0);
  43690. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43691. break;
  43692. case BABYLON.Mesh.CAP_ALL:
  43693. circlePaths[0] = capPath(tessellation, 0);
  43694. circlePaths[1] = circlePaths[2].slice(0);
  43695. circlePaths[index] = circlePaths[index - 1].slice(0);
  43696. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  43697. break;
  43698. default:
  43699. break;
  43700. }
  43701. return circlePaths;
  43702. };
  43703. var path3D;
  43704. var pathArray;
  43705. if (instance) {
  43706. var arc = options.arc || instance.arc;
  43707. path3D = (instance.path3D).update(path);
  43708. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  43709. instance = MeshBuilder.CreateRibbon(null, { pathArray: pathArray, instance: instance });
  43710. instance.path3D = path3D;
  43711. instance.pathArray = pathArray;
  43712. instance.arc = arc;
  43713. return instance;
  43714. }
  43715. // tube creation
  43716. path3D = new BABYLON.Path3D(path);
  43717. var newPathArray = new Array();
  43718. cap = (cap < 0 || cap > 3) ? 0 : cap;
  43719. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  43720. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  43721. tube.pathArray = pathArray;
  43722. tube.path3D = path3D;
  43723. tube.tessellation = tessellation;
  43724. tube.cap = cap;
  43725. tube.arc = options.arc;
  43726. return tube;
  43727. };
  43728. /**
  43729. * Creates a polyhedron mesh.
  43730. *
  43731. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#polyhedron
  43732. * 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
  43733. * to choose the wanted type.
  43734. * The parameter `size` (positive float, default 1) sets the polygon size.
  43735. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  43736. * 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`.
  43737. * 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
  43738. * 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)`).
  43739. * 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
  43740. * 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.
  43741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  43742. * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4).
  43743. * Detail here : http://doc.babylonjs.com/tutorials/02._Discover_Basic_Elements#side-orientation
  43744. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  43745. */
  43746. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  43747. var polyhedron = new BABYLON.Mesh(name, scene);
  43748. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation, scene);
  43749. polyhedron.sideOrientation = options.sideOrientation;
  43750. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  43751. vertexData.applyToMesh(polyhedron, options.updatable);
  43752. return polyhedron;
  43753. };
  43754. /**
  43755. * Creates a decal mesh.
  43756. * tuto : http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#decals
  43757. * 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.
  43758. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  43759. * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates.
  43760. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  43761. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  43762. */
  43763. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  43764. var indices = sourceMesh.getIndices();
  43765. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  43766. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  43767. var position = options.position || BABYLON.Vector3.Zero();
  43768. var normal = options.normal || BABYLON.Vector3.Up();
  43769. var size = options.size || BABYLON.Vector3.One();
  43770. var angle = options.angle || 0;
  43771. // Getting correct rotation
  43772. if (!normal) {
  43773. var target = new BABYLON.Vector3(0, 0, 1);
  43774. var camera = sourceMesh.getScene().activeCamera;
  43775. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  43776. normal = camera.globalPosition.subtract(cameraWorldTarget);
  43777. }
  43778. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  43779. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  43780. var pitch = Math.atan2(normal.y, len);
  43781. // Matrix
  43782. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  43783. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  43784. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  43785. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  43786. var vertexData = new BABYLON.VertexData();
  43787. vertexData.indices = [];
  43788. vertexData.positions = [];
  43789. vertexData.normals = [];
  43790. vertexData.uvs = [];
  43791. var currentVertexDataIndex = 0;
  43792. var extractDecalVector3 = function (indexId) {
  43793. var vertexId = indices[indexId];
  43794. var result = new BABYLON.PositionNormalVertex();
  43795. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  43796. // Send vector to decal local world
  43797. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  43798. // Get normal
  43799. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  43800. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  43801. return result;
  43802. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  43803. var clip = function (vertices, axis) {
  43804. if (vertices.length === 0) {
  43805. return vertices;
  43806. }
  43807. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  43808. var clipVertices = function (v0, v1) {
  43809. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  43810. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  43811. };
  43812. var result = new Array();
  43813. for (var index = 0; index < vertices.length; index += 3) {
  43814. var v1Out;
  43815. var v2Out;
  43816. var v3Out;
  43817. var total = 0;
  43818. var nV1, nV2, nV3, nV4;
  43819. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  43820. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  43821. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  43822. v1Out = d1 > 0;
  43823. v2Out = d2 > 0;
  43824. v3Out = d3 > 0;
  43825. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  43826. switch (total) {
  43827. case 0:
  43828. result.push(vertices[index]);
  43829. result.push(vertices[index + 1]);
  43830. result.push(vertices[index + 2]);
  43831. break;
  43832. case 1:
  43833. if (v1Out) {
  43834. nV1 = vertices[index + 1];
  43835. nV2 = vertices[index + 2];
  43836. nV3 = clipVertices(vertices[index], nV1);
  43837. nV4 = clipVertices(vertices[index], nV2);
  43838. }
  43839. if (v2Out) {
  43840. nV1 = vertices[index];
  43841. nV2 = vertices[index + 2];
  43842. nV3 = clipVertices(vertices[index + 1], nV1);
  43843. nV4 = clipVertices(vertices[index + 1], nV2);
  43844. result.push(nV3);
  43845. result.push(nV2.clone());
  43846. result.push(nV1.clone());
  43847. result.push(nV2.clone());
  43848. result.push(nV3.clone());
  43849. result.push(nV4);
  43850. break;
  43851. }
  43852. if (v3Out) {
  43853. nV1 = vertices[index];
  43854. nV2 = vertices[index + 1];
  43855. nV3 = clipVertices(vertices[index + 2], nV1);
  43856. nV4 = clipVertices(vertices[index + 2], nV2);
  43857. }
  43858. result.push(nV1.clone());
  43859. result.push(nV2.clone());
  43860. result.push(nV3);
  43861. result.push(nV4);
  43862. result.push(nV3.clone());
  43863. result.push(nV2.clone());
  43864. break;
  43865. case 2:
  43866. if (!v1Out) {
  43867. nV1 = vertices[index].clone();
  43868. nV2 = clipVertices(nV1, vertices[index + 1]);
  43869. nV3 = clipVertices(nV1, vertices[index + 2]);
  43870. result.push(nV1);
  43871. result.push(nV2);
  43872. result.push(nV3);
  43873. }
  43874. if (!v2Out) {
  43875. nV1 = vertices[index + 1].clone();
  43876. nV2 = clipVertices(nV1, vertices[index + 2]);
  43877. nV3 = clipVertices(nV1, vertices[index]);
  43878. result.push(nV1);
  43879. result.push(nV2);
  43880. result.push(nV3);
  43881. }
  43882. if (!v3Out) {
  43883. nV1 = vertices[index + 2].clone();
  43884. nV2 = clipVertices(nV1, vertices[index]);
  43885. nV3 = clipVertices(nV1, vertices[index + 1]);
  43886. result.push(nV1);
  43887. result.push(nV2);
  43888. result.push(nV3);
  43889. }
  43890. break;
  43891. case 3:
  43892. break;
  43893. }
  43894. }
  43895. return result;
  43896. };
  43897. for (var index = 0; index < indices.length; index += 3) {
  43898. var faceVertices = new Array();
  43899. faceVertices.push(extractDecalVector3(index));
  43900. faceVertices.push(extractDecalVector3(index + 1));
  43901. faceVertices.push(extractDecalVector3(index + 2));
  43902. // Clip
  43903. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  43904. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  43905. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  43906. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  43907. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  43908. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  43909. if (faceVertices.length === 0) {
  43910. continue;
  43911. }
  43912. // Add UVs and get back to world
  43913. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  43914. var vertex = faceVertices[vIndex];
  43915. //TODO check for Int32Array | Uint32Array | Uint16Array
  43916. vertexData.indices.push(currentVertexDataIndex);
  43917. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  43918. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  43919. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  43920. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  43921. currentVertexDataIndex++;
  43922. }
  43923. }
  43924. // Return mesh
  43925. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  43926. vertexData.applyToMesh(decal);
  43927. decal.position = position.clone();
  43928. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  43929. return decal;
  43930. };
  43931. // Privates
  43932. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  43933. // extrusion geometry
  43934. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  43935. var tangents = path3D.getTangents();
  43936. var normals = path3D.getNormals();
  43937. var binormals = path3D.getBinormals();
  43938. var distances = path3D.getDistances();
  43939. var angle = 0;
  43940. var returnScale = function () { return scale; };
  43941. var returnRotation = function () { return rotation; };
  43942. var rotate = custom ? rotateFunction : returnRotation;
  43943. var scl = custom ? scaleFunction : returnScale;
  43944. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  43945. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  43946. for (var i = 0; i < curve.length; i++) {
  43947. var shapePath = new Array();
  43948. var angleStep = rotate(i, distances[i]);
  43949. var scaleRatio = scl(i, distances[i]);
  43950. for (var p = 0; p < shape.length; p++) {
  43951. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  43952. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  43953. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  43954. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  43955. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  43956. shapePath[p] = rotated;
  43957. }
  43958. shapePaths[index] = shapePath;
  43959. angle += angleStep;
  43960. index++;
  43961. }
  43962. // cap
  43963. var capPath = function (shapePath) {
  43964. var pointCap = Array();
  43965. var barycenter = BABYLON.Vector3.Zero();
  43966. var i;
  43967. for (i = 0; i < shapePath.length; i++) {
  43968. barycenter.addInPlace(shapePath[i]);
  43969. }
  43970. barycenter.scaleInPlace(1.0 / shapePath.length);
  43971. for (i = 0; i < shapePath.length; i++) {
  43972. pointCap.push(barycenter);
  43973. }
  43974. return pointCap;
  43975. };
  43976. switch (cap) {
  43977. case BABYLON.Mesh.NO_CAP:
  43978. break;
  43979. case BABYLON.Mesh.CAP_START:
  43980. shapePaths[0] = capPath(shapePaths[2]);
  43981. shapePaths[1] = shapePaths[2];
  43982. break;
  43983. case BABYLON.Mesh.CAP_END:
  43984. shapePaths[index] = shapePaths[index - 1];
  43985. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43986. break;
  43987. case BABYLON.Mesh.CAP_ALL:
  43988. shapePaths[0] = capPath(shapePaths[2]);
  43989. shapePaths[1] = shapePaths[2];
  43990. shapePaths[index] = shapePaths[index - 1];
  43991. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  43992. break;
  43993. default:
  43994. break;
  43995. }
  43996. return shapePaths;
  43997. };
  43998. var path3D;
  43999. var pathArray;
  44000. if (instance) {
  44001. path3D = (instance.path3D).update(curve);
  44002. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  44003. instance = BABYLON.Mesh.CreateRibbon(null, pathArray, null, null, null, scene, null, null, instance);
  44004. return instance;
  44005. }
  44006. // extruded shape creation
  44007. path3D = new BABYLON.Path3D(curve);
  44008. var newShapePaths = new Array();
  44009. cap = (cap < 0 || cap > 3) ? 0 : cap;
  44010. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  44011. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs, backUVs: backUVs }, scene);
  44012. extrudedGeneric.pathArray = pathArray;
  44013. extrudedGeneric.path3D = path3D;
  44014. extrudedGeneric.cap = cap;
  44015. return extrudedGeneric;
  44016. };
  44017. return MeshBuilder;
  44018. }());
  44019. BABYLON.MeshBuilder = MeshBuilder;
  44020. })(BABYLON || (BABYLON = {}));
  44021. //# sourceMappingURL=babylon.meshBuilder.js.map
  44022. var BABYLON;
  44023. (function (BABYLON) {
  44024. var AudioEngine = (function () {
  44025. function AudioEngine() {
  44026. this._audioContext = null;
  44027. this._audioContextInitialized = false;
  44028. this.canUseWebAudio = false;
  44029. this.WarnedWebAudioUnsupported = false;
  44030. this.unlocked = false;
  44031. this.isMP3supported = false;
  44032. this.isOGGsupported = false;
  44033. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  44034. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  44035. this.canUseWebAudio = true;
  44036. }
  44037. var audioElem = document.createElement('audio');
  44038. try {
  44039. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  44040. this.isMP3supported = true;
  44041. }
  44042. }
  44043. catch (e) {
  44044. // protect error during capability check.
  44045. }
  44046. try {
  44047. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  44048. this.isOGGsupported = true;
  44049. }
  44050. }
  44051. catch (e) {
  44052. // protect error during capability check.
  44053. }
  44054. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  44055. this._unlockiOSaudio();
  44056. }
  44057. else {
  44058. this.unlocked = true;
  44059. }
  44060. }
  44061. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  44062. get: function () {
  44063. if (!this._audioContextInitialized) {
  44064. this._initializeAudioContext();
  44065. }
  44066. return this._audioContext;
  44067. },
  44068. enumerable: true,
  44069. configurable: true
  44070. });
  44071. AudioEngine.prototype._unlockiOSaudio = function () {
  44072. var _this = this;
  44073. var unlockaudio = function () {
  44074. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  44075. var source = _this.audioContext.createBufferSource();
  44076. source.buffer = buffer;
  44077. source.connect(_this.audioContext.destination);
  44078. source.start(0);
  44079. setTimeout(function () {
  44080. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  44081. _this.unlocked = true;
  44082. window.removeEventListener('touchend', unlockaudio, false);
  44083. if (_this.onAudioUnlocked) {
  44084. _this.onAudioUnlocked();
  44085. }
  44086. }
  44087. }, 0);
  44088. };
  44089. window.addEventListener('touchend', unlockaudio, false);
  44090. };
  44091. AudioEngine.prototype._initializeAudioContext = function () {
  44092. try {
  44093. if (this.canUseWebAudio) {
  44094. this._audioContext = new AudioContext();
  44095. // create a global volume gain node
  44096. this.masterGain = this._audioContext.createGain();
  44097. this.masterGain.gain.value = 1;
  44098. this.masterGain.connect(this._audioContext.destination);
  44099. this._audioContextInitialized = true;
  44100. }
  44101. }
  44102. catch (e) {
  44103. this.canUseWebAudio = false;
  44104. BABYLON.Tools.Error("Web Audio: " + e.message);
  44105. }
  44106. };
  44107. AudioEngine.prototype.dispose = function () {
  44108. if (this.canUseWebAudio && this._audioContextInitialized) {
  44109. if (this._connectedAnalyser) {
  44110. this._connectedAnalyser.stopDebugCanvas();
  44111. this._connectedAnalyser.dispose();
  44112. this.masterGain.disconnect();
  44113. this.masterGain.connect(this._audioContext.destination);
  44114. this._connectedAnalyser = null;
  44115. }
  44116. this.masterGain.gain.value = 1;
  44117. }
  44118. this.WarnedWebAudioUnsupported = false;
  44119. };
  44120. AudioEngine.prototype.getGlobalVolume = function () {
  44121. if (this.canUseWebAudio && this._audioContextInitialized) {
  44122. return this.masterGain.gain.value;
  44123. }
  44124. else {
  44125. return -1;
  44126. }
  44127. };
  44128. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  44129. if (this.canUseWebAudio && this._audioContextInitialized) {
  44130. this.masterGain.gain.value = newVolume;
  44131. }
  44132. };
  44133. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  44134. if (this._connectedAnalyser) {
  44135. this._connectedAnalyser.stopDebugCanvas();
  44136. }
  44137. if (this.canUseWebAudio && this._audioContextInitialized) {
  44138. this._connectedAnalyser = analyser;
  44139. this.masterGain.disconnect();
  44140. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  44141. }
  44142. };
  44143. return AudioEngine;
  44144. }());
  44145. BABYLON.AudioEngine = AudioEngine;
  44146. })(BABYLON || (BABYLON = {}));
  44147. //# sourceMappingURL=babylon.audioEngine.js.map
  44148. var BABYLON;
  44149. (function (BABYLON) {
  44150. var Sound = (function () {
  44151. /**
  44152. * Create a sound and attach it to a scene
  44153. * @param name Name of your sound
  44154. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  44155. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  44156. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  44157. */
  44158. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  44159. var _this = this;
  44160. this.autoplay = false;
  44161. this.loop = false;
  44162. this.useCustomAttenuation = false;
  44163. this.spatialSound = false;
  44164. this.refDistance = 1;
  44165. this.rolloffFactor = 1;
  44166. this.maxDistance = 100;
  44167. this.distanceModel = "linear";
  44168. this._panningModel = "equalpower";
  44169. this._playbackRate = 1;
  44170. this._streaming = false;
  44171. this._startTime = 0;
  44172. this._startOffset = 0;
  44173. this._position = BABYLON.Vector3.Zero();
  44174. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  44175. this._volume = 1;
  44176. this._isLoaded = false;
  44177. this._isReadyToPlay = false;
  44178. this.isPlaying = false;
  44179. this.isPaused = false;
  44180. this._isDirectional = false;
  44181. // Used if you'd like to create a directional sound.
  44182. // If not set, the sound will be omnidirectional
  44183. this._coneInnerAngle = 360;
  44184. this._coneOuterAngle = 360;
  44185. this._coneOuterGain = 0;
  44186. this._isOutputConnected = false;
  44187. this._urlType = "Unknown";
  44188. this.name = name;
  44189. this._scene = scene;
  44190. this._readyToPlayCallback = readyToPlayCallback;
  44191. // Default custom attenuation function is a linear attenuation
  44192. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  44193. if (currentDistance < maxDistance) {
  44194. return currentVolume * (1 - currentDistance / maxDistance);
  44195. }
  44196. else {
  44197. return 0;
  44198. }
  44199. };
  44200. if (options) {
  44201. this.autoplay = options.autoplay || false;
  44202. this.loop = options.loop || false;
  44203. // if volume === 0, we need another way to check this option
  44204. if (options.volume !== undefined) {
  44205. this._volume = options.volume;
  44206. }
  44207. this.spatialSound = options.spatialSound || false;
  44208. this.maxDistance = options.maxDistance || 100;
  44209. this.useCustomAttenuation = options.useCustomAttenuation || false;
  44210. this.rolloffFactor = options.rolloffFactor || 1;
  44211. this.refDistance = options.refDistance || 1;
  44212. this.distanceModel = options.distanceModel || "linear";
  44213. this._playbackRate = options.playbackRate || 1;
  44214. this._streaming = options.streaming || false;
  44215. }
  44216. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44217. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  44218. this._soundGain.gain.value = this._volume;
  44219. this._inputAudioNode = this._soundGain;
  44220. this._ouputAudioNode = this._soundGain;
  44221. if (this.spatialSound) {
  44222. this._createSpatialParameters();
  44223. }
  44224. this._scene.mainSoundTrack.AddSound(this);
  44225. var validParameter = true;
  44226. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  44227. if (urlOrArrayBuffer) {
  44228. if (typeof (urlOrArrayBuffer) === "string")
  44229. this._urlType = "String";
  44230. if (Array.isArray(urlOrArrayBuffer))
  44231. this._urlType = "Array";
  44232. if (urlOrArrayBuffer instanceof ArrayBuffer)
  44233. this._urlType = "ArrayBuffer";
  44234. var urls = [];
  44235. var codecSupportedFound = false;
  44236. switch (this._urlType) {
  44237. case "ArrayBuffer":
  44238. if (urlOrArrayBuffer.byteLength > 0) {
  44239. codecSupportedFound = true;
  44240. this._soundLoaded(urlOrArrayBuffer);
  44241. }
  44242. break;
  44243. case "String":
  44244. urls.push(urlOrArrayBuffer);
  44245. case "Array":
  44246. if (urls.length === 0)
  44247. urls = urlOrArrayBuffer;
  44248. // If we found a supported format, we load it immediately and stop the loop
  44249. for (var i = 0; i < urls.length; i++) {
  44250. var url = urls[i];
  44251. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  44252. codecSupportedFound = true;
  44253. }
  44254. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  44255. codecSupportedFound = true;
  44256. }
  44257. if (url.indexOf(".wav", url.length - 4) !== -1) {
  44258. codecSupportedFound = true;
  44259. }
  44260. if (url.indexOf("blob:") !== -1) {
  44261. codecSupportedFound = true;
  44262. }
  44263. if (codecSupportedFound) {
  44264. // Loading sound using XHR2
  44265. if (!this._streaming) {
  44266. BABYLON.Tools.LoadFile(url, function (data) { _this._soundLoaded(data); }, null, this._scene.database, true);
  44267. }
  44268. else {
  44269. this._htmlAudioElement = new Audio(url);
  44270. this._htmlAudioElement.controls = false;
  44271. this._htmlAudioElement.loop = this.loop;
  44272. this._htmlAudioElement.crossOrigin = "anonymous";
  44273. this._htmlAudioElement.preload = "auto";
  44274. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  44275. _this._isReadyToPlay = true;
  44276. if (_this.autoplay) {
  44277. _this.play();
  44278. }
  44279. if (_this._readyToPlayCallback) {
  44280. _this._readyToPlayCallback();
  44281. }
  44282. });
  44283. document.body.appendChild(this._htmlAudioElement);
  44284. }
  44285. break;
  44286. }
  44287. }
  44288. break;
  44289. default:
  44290. validParameter = false;
  44291. break;
  44292. }
  44293. if (!validParameter) {
  44294. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  44295. }
  44296. else {
  44297. if (!codecSupportedFound) {
  44298. this._isReadyToPlay = true;
  44299. // Simulating a ready to play event to avoid breaking code path
  44300. if (this._readyToPlayCallback) {
  44301. window.setTimeout(function () {
  44302. _this._readyToPlayCallback();
  44303. }, 1000);
  44304. }
  44305. }
  44306. }
  44307. }
  44308. }
  44309. else {
  44310. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  44311. this._scene.mainSoundTrack.AddSound(this);
  44312. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  44313. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  44314. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  44315. }
  44316. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  44317. if (this._readyToPlayCallback) {
  44318. window.setTimeout(function () {
  44319. _this._readyToPlayCallback();
  44320. }, 1000);
  44321. }
  44322. }
  44323. }
  44324. Sound.prototype.dispose = function () {
  44325. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isReadyToPlay) {
  44326. if (this.isPlaying) {
  44327. this.stop();
  44328. }
  44329. this._isReadyToPlay = false;
  44330. if (this.soundTrackId === -1) {
  44331. this._scene.mainSoundTrack.RemoveSound(this);
  44332. }
  44333. else {
  44334. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  44335. }
  44336. if (this._soundGain) {
  44337. this._soundGain.disconnect();
  44338. this._soundGain = null;
  44339. }
  44340. if (this._soundPanner) {
  44341. this._soundPanner.disconnect();
  44342. this._soundPanner = null;
  44343. }
  44344. if (this._soundSource) {
  44345. this._soundSource.disconnect();
  44346. this._soundSource = null;
  44347. }
  44348. this._audioBuffer = null;
  44349. if (this._htmlAudioElement) {
  44350. this._htmlAudioElement.pause();
  44351. this._htmlAudioElement.src = "";
  44352. document.body.removeChild(this._htmlAudioElement);
  44353. }
  44354. if (this._connectedMesh) {
  44355. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44356. this._connectedMesh = null;
  44357. }
  44358. }
  44359. };
  44360. Sound.prototype.isReady = function () {
  44361. return this._isReadyToPlay;
  44362. };
  44363. Sound.prototype._soundLoaded = function (audioData) {
  44364. var _this = this;
  44365. this._isLoaded = true;
  44366. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  44367. _this._audioBuffer = buffer;
  44368. _this._isReadyToPlay = true;
  44369. if (_this.autoplay) {
  44370. _this.play();
  44371. }
  44372. if (_this._readyToPlayCallback) {
  44373. _this._readyToPlayCallback();
  44374. }
  44375. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  44376. };
  44377. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  44378. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44379. this._audioBuffer = audioBuffer;
  44380. this._isReadyToPlay = true;
  44381. }
  44382. };
  44383. Sound.prototype.updateOptions = function (options) {
  44384. if (options) {
  44385. this.loop = options.loop || this.loop;
  44386. this.maxDistance = options.maxDistance || this.maxDistance;
  44387. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  44388. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  44389. this.refDistance = options.refDistance || this.refDistance;
  44390. this.distanceModel = options.distanceModel || this.distanceModel;
  44391. this._playbackRate = options.playbackRate || this._playbackRate;
  44392. this._updateSpatialParameters();
  44393. if (this.isPlaying) {
  44394. if (this._streaming) {
  44395. this._htmlAudioElement.playbackRate = this._playbackRate;
  44396. }
  44397. else {
  44398. this._soundSource.playbackRate.value = this._playbackRate;
  44399. }
  44400. }
  44401. }
  44402. };
  44403. Sound.prototype._createSpatialParameters = function () {
  44404. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44405. if (this._scene.headphone) {
  44406. this._panningModel = "HRTF";
  44407. }
  44408. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  44409. this._updateSpatialParameters();
  44410. this._soundPanner.connect(this._ouputAudioNode);
  44411. this._inputAudioNode = this._soundPanner;
  44412. }
  44413. };
  44414. Sound.prototype._updateSpatialParameters = function () {
  44415. if (this.spatialSound) {
  44416. if (this.useCustomAttenuation) {
  44417. // Tricks to disable in a way embedded Web Audio attenuation
  44418. this._soundPanner.distanceModel = "linear";
  44419. this._soundPanner.maxDistance = Number.MAX_VALUE;
  44420. this._soundPanner.refDistance = 1;
  44421. this._soundPanner.rolloffFactor = 1;
  44422. this._soundPanner.panningModel = this._panningModel;
  44423. }
  44424. else {
  44425. this._soundPanner.distanceModel = this.distanceModel;
  44426. this._soundPanner.maxDistance = this.maxDistance;
  44427. this._soundPanner.refDistance = this.refDistance;
  44428. this._soundPanner.rolloffFactor = this.rolloffFactor;
  44429. this._soundPanner.panningModel = this._panningModel;
  44430. }
  44431. }
  44432. };
  44433. Sound.prototype.switchPanningModelToHRTF = function () {
  44434. this._panningModel = "HRTF";
  44435. this._switchPanningModel();
  44436. };
  44437. Sound.prototype.switchPanningModelToEqualPower = function () {
  44438. this._panningModel = "equalpower";
  44439. this._switchPanningModel();
  44440. };
  44441. Sound.prototype._switchPanningModel = function () {
  44442. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44443. this._soundPanner.panningModel = this._panningModel;
  44444. }
  44445. };
  44446. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  44447. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44448. if (this._isOutputConnected) {
  44449. this._ouputAudioNode.disconnect();
  44450. }
  44451. this._ouputAudioNode.connect(soundTrackAudioNode);
  44452. this._isOutputConnected = true;
  44453. }
  44454. };
  44455. /**
  44456. * Transform this sound into a directional source
  44457. * @param coneInnerAngle Size of the inner cone in degree
  44458. * @param coneOuterAngle Size of the outer cone in degree
  44459. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  44460. */
  44461. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  44462. if (coneOuterAngle < coneInnerAngle) {
  44463. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  44464. return;
  44465. }
  44466. this._coneInnerAngle = coneInnerAngle;
  44467. this._coneOuterAngle = coneOuterAngle;
  44468. this._coneOuterGain = coneOuterGain;
  44469. this._isDirectional = true;
  44470. if (this.isPlaying && this.loop) {
  44471. this.stop();
  44472. this.play();
  44473. }
  44474. };
  44475. Sound.prototype.setPosition = function (newPosition) {
  44476. this._position = newPosition;
  44477. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound) {
  44478. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44479. }
  44480. };
  44481. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  44482. this._localDirection = newLocalDirection;
  44483. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  44484. this._updateDirection();
  44485. }
  44486. };
  44487. Sound.prototype._updateDirection = function () {
  44488. var mat = this._connectedMesh.getWorldMatrix();
  44489. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  44490. direction.normalize();
  44491. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  44492. };
  44493. Sound.prototype.updateDistanceFromListener = function () {
  44494. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation) {
  44495. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  44496. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  44497. }
  44498. };
  44499. Sound.prototype.setAttenuationFunction = function (callback) {
  44500. this._customAttenuationFunction = callback;
  44501. };
  44502. /**
  44503. * Play the sound
  44504. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  44505. * @param offset (optional) Start the sound setting it at a specific time
  44506. */
  44507. Sound.prototype.play = function (time, offset) {
  44508. var _this = this;
  44509. if (this._isReadyToPlay && this._scene.audioEnabled) {
  44510. try {
  44511. if (this._startOffset < 0) {
  44512. time = -this._startOffset;
  44513. this._startOffset = 0;
  44514. }
  44515. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44516. if (!this._soundSource || !this._streamingSource) {
  44517. if (this.spatialSound) {
  44518. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  44519. if (this._isDirectional) {
  44520. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  44521. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  44522. this._soundPanner.coneOuterGain = this._coneOuterGain;
  44523. if (this._connectedMesh) {
  44524. this._updateDirection();
  44525. }
  44526. else {
  44527. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  44528. }
  44529. }
  44530. }
  44531. }
  44532. if (this._streaming) {
  44533. if (!this._streamingSource) {
  44534. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  44535. this._htmlAudioElement.onended = function () { _this._onended(); };
  44536. this._htmlAudioElement.playbackRate = this._playbackRate;
  44537. }
  44538. this._streamingSource.disconnect();
  44539. this._streamingSource.connect(this._inputAudioNode);
  44540. this._htmlAudioElement.play();
  44541. }
  44542. else {
  44543. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  44544. this._soundSource.buffer = this._audioBuffer;
  44545. this._soundSource.connect(this._inputAudioNode);
  44546. this._soundSource.loop = this.loop;
  44547. this._soundSource.playbackRate.value = this._playbackRate;
  44548. this._soundSource.onended = function () { _this._onended(); };
  44549. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  44550. }
  44551. this._startTime = startTime;
  44552. this.isPlaying = true;
  44553. this.isPaused = false;
  44554. }
  44555. catch (ex) {
  44556. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  44557. }
  44558. }
  44559. };
  44560. Sound.prototype._onended = function () {
  44561. this.isPlaying = false;
  44562. if (this.onended) {
  44563. this.onended();
  44564. }
  44565. };
  44566. /**
  44567. * Stop the sound
  44568. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  44569. */
  44570. Sound.prototype.stop = function (time) {
  44571. if (this.isPlaying) {
  44572. if (this._streaming) {
  44573. this._htmlAudioElement.pause();
  44574. // Test needed for Firefox or it will generate an Invalid State Error
  44575. if (this._htmlAudioElement.currentTime > 0) {
  44576. this._htmlAudioElement.currentTime = 0;
  44577. }
  44578. }
  44579. else {
  44580. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  44581. this._soundSource.stop(stopTime);
  44582. this._soundSource.onended = null;
  44583. if (!this.isPaused) {
  44584. this._startOffset = 0;
  44585. }
  44586. }
  44587. this.isPlaying = false;
  44588. }
  44589. };
  44590. Sound.prototype.pause = function () {
  44591. if (this.isPlaying) {
  44592. this.isPaused = true;
  44593. if (this._streaming) {
  44594. this._htmlAudioElement.pause();
  44595. }
  44596. else {
  44597. this.stop(0);
  44598. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  44599. }
  44600. }
  44601. };
  44602. Sound.prototype.setVolume = function (newVolume, time) {
  44603. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44604. if (time) {
  44605. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  44606. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  44607. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  44608. }
  44609. else {
  44610. this._soundGain.gain.value = newVolume;
  44611. }
  44612. }
  44613. this._volume = newVolume;
  44614. };
  44615. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  44616. this._playbackRate = newPlaybackRate;
  44617. if (this.isPlaying) {
  44618. if (this._streaming) {
  44619. this._htmlAudioElement.playbackRate = this._playbackRate;
  44620. }
  44621. else {
  44622. this._soundSource.playbackRate.value = this._playbackRate;
  44623. }
  44624. }
  44625. };
  44626. Sound.prototype.getVolume = function () {
  44627. return this._volume;
  44628. };
  44629. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  44630. var _this = this;
  44631. if (this._connectedMesh) {
  44632. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44633. this._registerFunc = null;
  44634. }
  44635. this._connectedMesh = meshToConnectTo;
  44636. if (!this.spatialSound) {
  44637. this.spatialSound = true;
  44638. this._createSpatialParameters();
  44639. if (this.isPlaying && this.loop) {
  44640. this.stop();
  44641. this.play();
  44642. }
  44643. }
  44644. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  44645. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  44646. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  44647. };
  44648. Sound.prototype.detachFromMesh = function () {
  44649. if (this._connectedMesh) {
  44650. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  44651. this._registerFunc = null;
  44652. this._connectedMesh = null;
  44653. }
  44654. };
  44655. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (connectedMesh) {
  44656. this.setPosition(connectedMesh.getBoundingInfo().boundingSphere.centerWorld);
  44657. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  44658. this._updateDirection();
  44659. }
  44660. };
  44661. Sound.prototype.clone = function () {
  44662. var _this = this;
  44663. if (!this._streaming) {
  44664. var setBufferAndRun = function () {
  44665. if (_this._isReadyToPlay) {
  44666. clonedSound._audioBuffer = _this.getAudioBuffer();
  44667. clonedSound._isReadyToPlay = true;
  44668. if (clonedSound.autoplay) {
  44669. clonedSound.play();
  44670. }
  44671. }
  44672. else {
  44673. window.setTimeout(setBufferAndRun, 300);
  44674. }
  44675. };
  44676. var currentOptions = {
  44677. autoplay: this.autoplay, loop: this.loop,
  44678. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  44679. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  44680. refDistance: this.refDistance, distanceModel: this.distanceModel
  44681. };
  44682. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  44683. if (this.useCustomAttenuation) {
  44684. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  44685. }
  44686. clonedSound.setPosition(this._position);
  44687. clonedSound.setPlaybackRate(this._playbackRate);
  44688. setBufferAndRun();
  44689. return clonedSound;
  44690. }
  44691. else {
  44692. return null;
  44693. }
  44694. };
  44695. Sound.prototype.getAudioBuffer = function () {
  44696. return this._audioBuffer;
  44697. };
  44698. Sound.prototype.serialize = function () {
  44699. var serializationObject = {
  44700. name: this.name,
  44701. url: this.name,
  44702. autoplay: this.autoplay,
  44703. loop: this.loop,
  44704. volume: this._volume,
  44705. spatialSound: this.spatialSound,
  44706. maxDistance: this.maxDistance,
  44707. rolloffFactor: this.rolloffFactor,
  44708. refDistance: this.refDistance,
  44709. distanceModel: this.distanceModel,
  44710. playbackRate: this._playbackRate,
  44711. panningModel: this._panningModel,
  44712. soundTrackId: this.soundTrackId
  44713. };
  44714. if (this.spatialSound) {
  44715. if (this._connectedMesh)
  44716. serializationObject.connectedMeshId = this._connectedMesh.id;
  44717. serializationObject.position = this._position.asArray();
  44718. serializationObject.refDistance = this.refDistance;
  44719. serializationObject.distanceModel = this.distanceModel;
  44720. serializationObject.isDirectional = this._isDirectional;
  44721. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  44722. serializationObject.coneInnerAngle = this._coneInnerAngle;
  44723. serializationObject.coneOuterAngle = this._coneOuterAngle;
  44724. serializationObject.coneOuterGain = this._coneOuterGain;
  44725. }
  44726. return serializationObject;
  44727. };
  44728. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  44729. var soundName = parsedSound.name;
  44730. var soundUrl;
  44731. if (parsedSound.url) {
  44732. soundUrl = rootUrl + parsedSound.url;
  44733. }
  44734. else {
  44735. soundUrl = rootUrl + soundName;
  44736. }
  44737. var options = {
  44738. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  44739. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  44740. rolloffFactor: parsedSound.rolloffFactor,
  44741. refDistance: parsedSound.refDistance,
  44742. distanceModel: parsedSound.distanceModel,
  44743. playbackRate: parsedSound.playbackRate
  44744. };
  44745. var newSound;
  44746. if (!sourceSound) {
  44747. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  44748. scene._addPendingData(newSound);
  44749. }
  44750. else {
  44751. var setBufferAndRun = function () {
  44752. if (sourceSound._isReadyToPlay) {
  44753. newSound._audioBuffer = sourceSound.getAudioBuffer();
  44754. newSound._isReadyToPlay = true;
  44755. if (newSound.autoplay) {
  44756. newSound.play();
  44757. }
  44758. }
  44759. else {
  44760. window.setTimeout(setBufferAndRun, 300);
  44761. }
  44762. };
  44763. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  44764. setBufferAndRun();
  44765. }
  44766. if (parsedSound.position) {
  44767. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  44768. newSound.setPosition(soundPosition);
  44769. }
  44770. if (parsedSound.isDirectional) {
  44771. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  44772. if (parsedSound.localDirectionToMesh) {
  44773. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  44774. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  44775. }
  44776. }
  44777. if (parsedSound.connectedMeshId) {
  44778. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  44779. if (connectedMesh) {
  44780. newSound.attachToMesh(connectedMesh);
  44781. }
  44782. }
  44783. return newSound;
  44784. };
  44785. return Sound;
  44786. }());
  44787. BABYLON.Sound = Sound;
  44788. })(BABYLON || (BABYLON = {}));
  44789. //# sourceMappingURL=babylon.sound.js.map
  44790. var BABYLON;
  44791. (function (BABYLON) {
  44792. var SoundTrack = (function () {
  44793. function SoundTrack(scene, options) {
  44794. this.id = -1;
  44795. this._isMainTrack = false;
  44796. this._isInitialized = false;
  44797. this._scene = scene;
  44798. this.soundCollection = new Array();
  44799. this._options = options;
  44800. if (!this._isMainTrack) {
  44801. this._scene.soundTracks.push(this);
  44802. this.id = this._scene.soundTracks.length - 1;
  44803. }
  44804. }
  44805. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  44806. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44807. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  44808. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  44809. if (this._options) {
  44810. if (this._options.volume) {
  44811. this._outputAudioNode.gain.value = this._options.volume;
  44812. }
  44813. if (this._options.mainTrack) {
  44814. this._isMainTrack = this._options.mainTrack;
  44815. }
  44816. }
  44817. this._isInitialized = true;
  44818. }
  44819. };
  44820. SoundTrack.prototype.dispose = function () {
  44821. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44822. if (this._connectedAnalyser) {
  44823. this._connectedAnalyser.stopDebugCanvas();
  44824. }
  44825. while (this.soundCollection.length) {
  44826. this.soundCollection[0].dispose();
  44827. }
  44828. if (this._outputAudioNode) {
  44829. this._outputAudioNode.disconnect();
  44830. }
  44831. this._outputAudioNode = null;
  44832. }
  44833. };
  44834. SoundTrack.prototype.AddSound = function (sound) {
  44835. if (!this._isInitialized) {
  44836. this._initializeSoundTrackAudioGraph();
  44837. }
  44838. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44839. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  44840. }
  44841. if (sound.soundTrackId) {
  44842. if (sound.soundTrackId === -1) {
  44843. this._scene.mainSoundTrack.RemoveSound(sound);
  44844. }
  44845. else {
  44846. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  44847. }
  44848. }
  44849. this.soundCollection.push(sound);
  44850. sound.soundTrackId = this.id;
  44851. };
  44852. SoundTrack.prototype.RemoveSound = function (sound) {
  44853. var index = this.soundCollection.indexOf(sound);
  44854. if (index !== -1) {
  44855. this.soundCollection.splice(index, 1);
  44856. }
  44857. };
  44858. SoundTrack.prototype.setVolume = function (newVolume) {
  44859. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44860. this._outputAudioNode.gain.value = newVolume;
  44861. }
  44862. };
  44863. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  44864. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44865. for (var i = 0; i < this.soundCollection.length; i++) {
  44866. this.soundCollection[i].switchPanningModelToHRTF();
  44867. }
  44868. }
  44869. };
  44870. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  44871. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44872. for (var i = 0; i < this.soundCollection.length; i++) {
  44873. this.soundCollection[i].switchPanningModelToEqualPower();
  44874. }
  44875. }
  44876. };
  44877. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  44878. if (this._connectedAnalyser) {
  44879. this._connectedAnalyser.stopDebugCanvas();
  44880. }
  44881. this._connectedAnalyser = analyser;
  44882. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  44883. this._outputAudioNode.disconnect();
  44884. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  44885. }
  44886. };
  44887. return SoundTrack;
  44888. }());
  44889. BABYLON.SoundTrack = SoundTrack;
  44890. })(BABYLON || (BABYLON = {}));
  44891. //# sourceMappingURL=babylon.soundtrack.js.map
  44892. var BABYLON;
  44893. (function (BABYLON) {
  44894. var Analyser = (function () {
  44895. function Analyser(scene) {
  44896. this.SMOOTHING = 0.75;
  44897. this.FFT_SIZE = 512;
  44898. this.BARGRAPHAMPLITUDE = 256;
  44899. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  44900. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  44901. this._scene = scene;
  44902. this._audioEngine = BABYLON.Engine.audioEngine;
  44903. if (this._audioEngine.canUseWebAudio) {
  44904. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  44905. this._webAudioAnalyser.minDecibels = -140;
  44906. this._webAudioAnalyser.maxDecibels = 0;
  44907. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44908. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  44909. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  44910. }
  44911. }
  44912. Analyser.prototype.getFrequencyBinCount = function () {
  44913. if (this._audioEngine.canUseWebAudio) {
  44914. return this._webAudioAnalyser.frequencyBinCount;
  44915. }
  44916. else {
  44917. return 0;
  44918. }
  44919. };
  44920. Analyser.prototype.getByteFrequencyData = function () {
  44921. if (this._audioEngine.canUseWebAudio) {
  44922. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44923. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44924. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  44925. }
  44926. return this._byteFreqs;
  44927. };
  44928. Analyser.prototype.getByteTimeDomainData = function () {
  44929. if (this._audioEngine.canUseWebAudio) {
  44930. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44931. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44932. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  44933. }
  44934. return this._byteTime;
  44935. };
  44936. Analyser.prototype.getFloatFrequencyData = function () {
  44937. if (this._audioEngine.canUseWebAudio) {
  44938. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  44939. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  44940. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  44941. }
  44942. return this._floatFreqs;
  44943. };
  44944. Analyser.prototype.drawDebugCanvas = function () {
  44945. var _this = this;
  44946. if (this._audioEngine.canUseWebAudio) {
  44947. if (!this._debugCanvas) {
  44948. this._debugCanvas = document.createElement("canvas");
  44949. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  44950. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  44951. this._debugCanvas.style.position = "absolute";
  44952. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  44953. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  44954. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  44955. document.body.appendChild(this._debugCanvas);
  44956. this._registerFunc = function () {
  44957. _this.drawDebugCanvas();
  44958. };
  44959. this._scene.registerBeforeRender(this._registerFunc);
  44960. }
  44961. if (this._registerFunc) {
  44962. var workingArray = this.getByteFrequencyData();
  44963. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  44964. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  44965. // Draw the frequency domain chart.
  44966. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  44967. var value = workingArray[i];
  44968. var percent = value / this.BARGRAPHAMPLITUDE;
  44969. var height = this.DEBUGCANVASSIZE.height * percent;
  44970. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  44971. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  44972. var hue = i / this.getFrequencyBinCount() * 360;
  44973. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  44974. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  44975. }
  44976. }
  44977. }
  44978. };
  44979. Analyser.prototype.stopDebugCanvas = function () {
  44980. if (this._debugCanvas) {
  44981. this._scene.unregisterBeforeRender(this._registerFunc);
  44982. this._registerFunc = null;
  44983. document.body.removeChild(this._debugCanvas);
  44984. this._debugCanvas = null;
  44985. this._debugCanvasContext = null;
  44986. }
  44987. };
  44988. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  44989. if (this._audioEngine.canUseWebAudio) {
  44990. inputAudioNode.connect(this._webAudioAnalyser);
  44991. this._webAudioAnalyser.connect(outputAudioNode);
  44992. }
  44993. };
  44994. Analyser.prototype.dispose = function () {
  44995. if (this._audioEngine.canUseWebAudio) {
  44996. this._webAudioAnalyser.disconnect();
  44997. }
  44998. };
  44999. return Analyser;
  45000. }());
  45001. BABYLON.Analyser = Analyser;
  45002. })(BABYLON || (BABYLON = {}));
  45003. //# sourceMappingURL=babylon.analyser.js.map
  45004. var BABYLON;
  45005. (function (BABYLON) {
  45006. var CubeTexture = (function (_super) {
  45007. __extends(CubeTexture, _super);
  45008. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  45009. if (onLoad === void 0) { onLoad = null; }
  45010. if (onError === void 0) { onError = null; }
  45011. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45012. if (prefiltered === void 0) { prefiltered = false; }
  45013. if (forcedExtension === void 0) { forcedExtension = null; }
  45014. var _this = _super.call(this, scene) || this;
  45015. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  45016. _this.name = rootUrl;
  45017. _this.url = rootUrl;
  45018. _this._noMipmap = noMipmap;
  45019. _this.hasAlpha = false;
  45020. _this._format = format;
  45021. _this._prefiltered = prefiltered;
  45022. _this.isCube = true;
  45023. _this._textureMatrix = BABYLON.Matrix.Identity();
  45024. if (prefiltered) {
  45025. _this.gammaSpace = false;
  45026. }
  45027. if (!rootUrl && !files) {
  45028. return _this;
  45029. }
  45030. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  45031. if (!files) {
  45032. if (!extensions) {
  45033. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  45034. }
  45035. files = [];
  45036. for (var index = 0; index < extensions.length; index++) {
  45037. files.push(rootUrl + extensions[index]);
  45038. }
  45039. _this._extensions = extensions;
  45040. }
  45041. _this._files = files;
  45042. if (!_this._texture) {
  45043. if (!scene.useDelayedTextureLoading) {
  45044. if (prefiltered) {
  45045. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  45046. }
  45047. else {
  45048. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  45049. }
  45050. }
  45051. else {
  45052. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  45053. }
  45054. }
  45055. else if (onLoad) {
  45056. if (_this._texture.isReady) {
  45057. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  45058. }
  45059. else {
  45060. _this._texture.onLoadedObservable.add(onLoad);
  45061. }
  45062. }
  45063. return _this;
  45064. }
  45065. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  45066. return new CubeTexture("", scene, null, noMipmap, files);
  45067. };
  45068. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  45069. if (forcedExtension === void 0) { forcedExtension = null; }
  45070. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  45071. };
  45072. // Methods
  45073. CubeTexture.prototype.delayLoad = function () {
  45074. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  45075. return;
  45076. }
  45077. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  45078. this._texture = this._getFromCache(this.url, this._noMipmap);
  45079. if (!this._texture) {
  45080. if (this._prefiltered) {
  45081. this._texture = this.getScene().getEngine().createPrefilteredCubeTexture(this.url, this.getScene(), this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  45082. }
  45083. else {
  45084. this._texture = this.getScene().getEngine().createCubeTexture(this.url, this.getScene(), this._files, this._noMipmap, undefined, undefined, this._format);
  45085. }
  45086. }
  45087. };
  45088. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  45089. return this._textureMatrix;
  45090. };
  45091. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  45092. this._textureMatrix = value;
  45093. };
  45094. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  45095. var texture = BABYLON.SerializationHelper.Parse(function () {
  45096. return new BABYLON.CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions);
  45097. }, parsedTexture, scene);
  45098. // Animations
  45099. if (parsedTexture.animations) {
  45100. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  45101. var parsedAnimation = parsedTexture.animations[animationIndex];
  45102. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  45103. }
  45104. }
  45105. return texture;
  45106. };
  45107. CubeTexture.prototype.clone = function () {
  45108. var _this = this;
  45109. return BABYLON.SerializationHelper.Clone(function () {
  45110. return new CubeTexture(_this.url, _this.getScene(), _this._extensions, _this._noMipmap, _this._files);
  45111. }, this);
  45112. };
  45113. return CubeTexture;
  45114. }(BABYLON.BaseTexture));
  45115. BABYLON.CubeTexture = CubeTexture;
  45116. })(BABYLON || (BABYLON = {}));
  45117. //# sourceMappingURL=babylon.cubeTexture.js.map
  45118. var BABYLON;
  45119. (function (BABYLON) {
  45120. var RenderTargetTexture = (function (_super) {
  45121. __extends(RenderTargetTexture, _super);
  45122. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  45123. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  45124. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45125. if (isCube === void 0) { isCube = false; }
  45126. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45127. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45128. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  45129. if (isMulti === void 0) { isMulti = false; }
  45130. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  45131. _this.isCube = isCube;
  45132. /**
  45133. * Use this list to define the list of mesh you want to render.
  45134. */
  45135. _this.renderList = new Array();
  45136. _this.renderParticles = true;
  45137. _this.renderSprites = false;
  45138. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  45139. _this.ignoreCameraViewport = false;
  45140. // Events
  45141. /**
  45142. * An event triggered when the texture is unbind.
  45143. * @type {BABYLON.Observable}
  45144. */
  45145. _this.onBeforeBindObservable = new BABYLON.Observable();
  45146. /**
  45147. * An event triggered when the texture is unbind.
  45148. * @type {BABYLON.Observable}
  45149. */
  45150. _this.onAfterUnbindObservable = new BABYLON.Observable();
  45151. /**
  45152. * An event triggered before rendering the texture
  45153. * @type {BABYLON.Observable}
  45154. */
  45155. _this.onBeforeRenderObservable = new BABYLON.Observable();
  45156. /**
  45157. * An event triggered after rendering the texture
  45158. * @type {BABYLON.Observable}
  45159. */
  45160. _this.onAfterRenderObservable = new BABYLON.Observable();
  45161. /**
  45162. * An event triggered after the texture clear
  45163. * @type {BABYLON.Observable}
  45164. */
  45165. _this.onClearObservable = new BABYLON.Observable();
  45166. _this._currentRefreshId = -1;
  45167. _this._refreshRate = 1;
  45168. _this._samples = 1;
  45169. scene = _this.getScene();
  45170. _this.name = name;
  45171. _this.isRenderTarget = true;
  45172. _this._size = size;
  45173. _this._generateMipMaps = generateMipMaps;
  45174. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  45175. // Rendering groups
  45176. _this._renderingManager = new BABYLON.RenderingManager(scene);
  45177. if (isMulti) {
  45178. return _this;
  45179. }
  45180. _this._renderTargetOptions = {
  45181. generateMipMaps: generateMipMaps,
  45182. type: type,
  45183. samplingMode: samplingMode,
  45184. generateDepthBuffer: generateDepthBuffer,
  45185. generateStencilBuffer: generateStencilBuffer
  45186. };
  45187. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  45188. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45189. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45190. }
  45191. if (isCube) {
  45192. _this._texture = scene.getEngine().createRenderTargetCubeTexture(size, _this._renderTargetOptions);
  45193. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  45194. _this._textureMatrix = BABYLON.Matrix.Identity();
  45195. }
  45196. else {
  45197. _this._texture = scene.getEngine().createRenderTargetTexture(size, _this._renderTargetOptions);
  45198. }
  45199. return _this;
  45200. }
  45201. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  45202. get: function () {
  45203. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  45204. },
  45205. enumerable: true,
  45206. configurable: true
  45207. });
  45208. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  45209. get: function () {
  45210. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  45211. },
  45212. enumerable: true,
  45213. configurable: true
  45214. });
  45215. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  45216. get: function () {
  45217. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  45218. },
  45219. enumerable: true,
  45220. configurable: true
  45221. });
  45222. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  45223. set: function (callback) {
  45224. if (this._onAfterUnbindObserver) {
  45225. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  45226. }
  45227. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  45228. },
  45229. enumerable: true,
  45230. configurable: true
  45231. });
  45232. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  45233. set: function (callback) {
  45234. if (this._onBeforeRenderObserver) {
  45235. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  45236. }
  45237. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  45238. },
  45239. enumerable: true,
  45240. configurable: true
  45241. });
  45242. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  45243. set: function (callback) {
  45244. if (this._onAfterRenderObserver) {
  45245. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  45246. }
  45247. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  45248. },
  45249. enumerable: true,
  45250. configurable: true
  45251. });
  45252. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  45253. set: function (callback) {
  45254. if (this._onClearObserver) {
  45255. this.onClearObservable.remove(this._onClearObserver);
  45256. }
  45257. this._onClearObserver = this.onClearObservable.add(callback);
  45258. },
  45259. enumerable: true,
  45260. configurable: true
  45261. });
  45262. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  45263. get: function () {
  45264. return this._renderTargetOptions;
  45265. },
  45266. enumerable: true,
  45267. configurable: true
  45268. });
  45269. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  45270. get: function () {
  45271. return this._samples;
  45272. },
  45273. set: function (value) {
  45274. if (this._samples === value) {
  45275. return;
  45276. }
  45277. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  45278. },
  45279. enumerable: true,
  45280. configurable: true
  45281. });
  45282. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  45283. this._currentRefreshId = -1;
  45284. };
  45285. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  45286. get: function () {
  45287. return this._refreshRate;
  45288. },
  45289. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  45290. set: function (value) {
  45291. this._refreshRate = value;
  45292. this.resetRefreshCounter();
  45293. },
  45294. enumerable: true,
  45295. configurable: true
  45296. });
  45297. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  45298. if (!this._postProcessManager) {
  45299. this._postProcessManager = new BABYLON.PostProcessManager(this.getScene());
  45300. this._postProcesses = new Array();
  45301. }
  45302. this._postProcesses.push(postProcess);
  45303. this._postProcesses[0].autoClear = false;
  45304. };
  45305. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  45306. if (!this._postProcesses) {
  45307. return;
  45308. }
  45309. if (dispose) {
  45310. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  45311. var postProcess = _a[_i];
  45312. postProcess.dispose();
  45313. postProcess = null;
  45314. }
  45315. }
  45316. this._postProcesses = [];
  45317. };
  45318. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  45319. if (!this._postProcesses) {
  45320. return;
  45321. }
  45322. var index = this._postProcesses.indexOf(postProcess);
  45323. if (index === -1) {
  45324. return;
  45325. }
  45326. this._postProcesses.splice(index, 1);
  45327. if (this._postProcesses.length > 0) {
  45328. this._postProcesses[0].autoClear = false;
  45329. }
  45330. };
  45331. RenderTargetTexture.prototype._shouldRender = function () {
  45332. if (this._currentRefreshId === -1) {
  45333. this._currentRefreshId = 1;
  45334. return true;
  45335. }
  45336. if (this.refreshRate === this._currentRefreshId) {
  45337. this._currentRefreshId = 1;
  45338. return true;
  45339. }
  45340. this._currentRefreshId++;
  45341. return false;
  45342. };
  45343. RenderTargetTexture.prototype.getRenderSize = function () {
  45344. return this._size;
  45345. };
  45346. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  45347. get: function () {
  45348. return true;
  45349. },
  45350. enumerable: true,
  45351. configurable: true
  45352. });
  45353. RenderTargetTexture.prototype.scale = function (ratio) {
  45354. var newSize = this._size * ratio;
  45355. this.resize(newSize);
  45356. };
  45357. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  45358. if (this.isCube) {
  45359. return this._textureMatrix;
  45360. }
  45361. return _super.prototype.getReflectionTextureMatrix.call(this);
  45362. };
  45363. RenderTargetTexture.prototype.resize = function (size) {
  45364. this.releaseInternalTexture();
  45365. if (this.isCube) {
  45366. this._texture = this.getScene().getEngine().createRenderTargetCubeTexture(size, this._renderTargetOptions);
  45367. }
  45368. else {
  45369. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, this._renderTargetOptions);
  45370. }
  45371. };
  45372. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  45373. var scene = this.getScene();
  45374. var engine = scene.getEngine();
  45375. if (this.useCameraPostProcesses !== undefined) {
  45376. useCameraPostProcess = this.useCameraPostProcesses;
  45377. }
  45378. if (this._waitingRenderList) {
  45379. this.renderList = [];
  45380. for (var index = 0; index < this._waitingRenderList.length; index++) {
  45381. var id = this._waitingRenderList[index];
  45382. this.renderList.push(scene.getMeshByID(id));
  45383. }
  45384. delete this._waitingRenderList;
  45385. }
  45386. // Is predicate defined?
  45387. if (this.renderListPredicate) {
  45388. this.renderList.splice(0); // Clear previous renderList
  45389. var sceneMeshes = this.getScene().meshes;
  45390. for (var index = 0; index < sceneMeshes.length; index++) {
  45391. var mesh = sceneMeshes[index];
  45392. if (this.renderListPredicate(mesh)) {
  45393. this.renderList.push(mesh);
  45394. }
  45395. }
  45396. }
  45397. if (this.renderList && this.renderList.length === 0) {
  45398. return;
  45399. }
  45400. this.onBeforeBindObservable.notifyObservers(this);
  45401. // Set custom projection.
  45402. // Needs to be before binding to prevent changing the aspect ratio.
  45403. var camera;
  45404. if (this.activeCamera) {
  45405. camera = this.activeCamera;
  45406. engine.setViewport(this.activeCamera.viewport, this._size, this._size);
  45407. if (this.activeCamera !== scene.activeCamera) {
  45408. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  45409. }
  45410. }
  45411. else {
  45412. camera = scene.activeCamera;
  45413. engine.setViewport(scene.activeCamera.viewport, this._size, this._size);
  45414. }
  45415. // Prepare renderingManager
  45416. this._renderingManager.reset();
  45417. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  45418. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  45419. var sceneRenderId = scene.getRenderId();
  45420. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  45421. var mesh = currentRenderList[meshIndex];
  45422. if (mesh) {
  45423. if (!mesh.isReady()) {
  45424. // Reset _currentRefreshId
  45425. this.resetRefreshCounter();
  45426. continue;
  45427. }
  45428. mesh._preActivateForIntermediateRendering(sceneRenderId);
  45429. var isMasked = void 0;
  45430. if (!this.renderList) {
  45431. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  45432. }
  45433. else {
  45434. isMasked = false;
  45435. }
  45436. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  45437. mesh._activate(sceneRenderId);
  45438. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  45439. var subMesh = mesh.subMeshes[subIndex];
  45440. scene._activeIndices.addCount(subMesh.indexCount, false);
  45441. this._renderingManager.dispatch(subMesh);
  45442. }
  45443. }
  45444. }
  45445. }
  45446. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  45447. var particleSystem = scene.particleSystems[particleIndex];
  45448. var emitter = particleSystem.emitter;
  45449. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  45450. continue;
  45451. }
  45452. if (currentRenderList.indexOf(emitter) >= 0) {
  45453. this._renderingManager.dispatchParticles(particleSystem);
  45454. }
  45455. }
  45456. if (this.isCube) {
  45457. for (var face = 0; face < 6; face++) {
  45458. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45459. scene.incrementRenderId();
  45460. scene.resetCachedMaterial();
  45461. }
  45462. }
  45463. else {
  45464. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  45465. }
  45466. this.onAfterUnbindObservable.notifyObservers(this);
  45467. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  45468. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  45469. }
  45470. engine.setViewport(scene.activeCamera.viewport);
  45471. scene.resetCachedMaterial();
  45472. };
  45473. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  45474. var _this = this;
  45475. var scene = this.getScene();
  45476. var engine = scene.getEngine();
  45477. // Bind
  45478. if (this._postProcessManager) {
  45479. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  45480. }
  45481. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  45482. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport);
  45483. }
  45484. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  45485. // Clear
  45486. if (this.onClearObservable.hasObservers()) {
  45487. this.onClearObservable.notifyObservers(engine);
  45488. }
  45489. else {
  45490. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  45491. }
  45492. if (!this._doNotChangeAspectRatio) {
  45493. scene.updateTransformMatrix(true);
  45494. }
  45495. // Render
  45496. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  45497. if (this._postProcessManager) {
  45498. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses);
  45499. }
  45500. else if (useCameraPostProcess) {
  45501. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  45502. }
  45503. if (!this._doNotChangeAspectRatio) {
  45504. scene.updateTransformMatrix(true);
  45505. }
  45506. // Dump ?
  45507. if (dumpForDebug) {
  45508. BABYLON.Tools.DumpFramebuffer(this._size, this._size, engine);
  45509. }
  45510. // Unbind
  45511. if (!this.isCube || faceIndex === 5) {
  45512. if (this.isCube) {
  45513. if (faceIndex === 5) {
  45514. engine.generateMipMapsForCubemap(this._texture);
  45515. }
  45516. }
  45517. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  45518. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  45519. });
  45520. }
  45521. else {
  45522. this.onAfterRenderObservable.notifyObservers(faceIndex);
  45523. }
  45524. };
  45525. /**
  45526. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  45527. * This allowed control for front to back rendering or reversly depending of the special needs.
  45528. *
  45529. * @param renderingGroupId The rendering group id corresponding to its index
  45530. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  45531. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  45532. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  45533. */
  45534. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  45535. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  45536. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  45537. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  45538. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  45539. };
  45540. /**
  45541. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  45542. *
  45543. * @param renderingGroupId The rendering group id corresponding to its index
  45544. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  45545. */
  45546. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  45547. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  45548. };
  45549. RenderTargetTexture.prototype.clone = function () {
  45550. var textureSize = this.getSize();
  45551. 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);
  45552. // Base texture
  45553. newTexture.hasAlpha = this.hasAlpha;
  45554. newTexture.level = this.level;
  45555. // RenderTarget Texture
  45556. newTexture.coordinatesMode = this.coordinatesMode;
  45557. newTexture.renderList = this.renderList.slice(0);
  45558. return newTexture;
  45559. };
  45560. RenderTargetTexture.prototype.serialize = function () {
  45561. if (!this.name) {
  45562. return null;
  45563. }
  45564. var serializationObject = _super.prototype.serialize.call(this);
  45565. serializationObject.renderTargetSize = this.getRenderSize();
  45566. serializationObject.renderList = [];
  45567. for (var index = 0; index < this.renderList.length; index++) {
  45568. serializationObject.renderList.push(this.renderList[index].id);
  45569. }
  45570. return serializationObject;
  45571. };
  45572. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  45573. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  45574. this.getScene().getEngine()._releaseFramebufferObjects(this.getInternalTexture());
  45575. };
  45576. RenderTargetTexture.prototype.dispose = function () {
  45577. if (this._postProcessManager) {
  45578. this._postProcessManager.dispose();
  45579. this._postProcessManager = null;
  45580. }
  45581. this.clearPostProcesses(true);
  45582. this.renderList = null;
  45583. // Remove from custom render targets
  45584. var scene = this.getScene();
  45585. var index = scene.customRenderTargets.indexOf(this);
  45586. if (index >= 0) {
  45587. scene.customRenderTargets.splice(index, 1);
  45588. }
  45589. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  45590. var camera = _a[_i];
  45591. index = camera.customRenderTargets.indexOf(this);
  45592. if (index >= 0) {
  45593. camera.customRenderTargets.splice(index, 1);
  45594. }
  45595. }
  45596. _super.prototype.dispose.call(this);
  45597. };
  45598. RenderTargetTexture.prototype._rebuild = function () {
  45599. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  45600. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  45601. }
  45602. };
  45603. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  45604. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  45605. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  45606. return RenderTargetTexture;
  45607. }(BABYLON.Texture));
  45608. BABYLON.RenderTargetTexture = RenderTargetTexture;
  45609. })(BABYLON || (BABYLON = {}));
  45610. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  45611. var BABYLON;
  45612. (function (BABYLON) {
  45613. ;
  45614. var MultiRenderTarget = (function (_super) {
  45615. __extends(MultiRenderTarget, _super);
  45616. function MultiRenderTarget(name, size, count, scene, options) {
  45617. var _this = this;
  45618. options = options || {};
  45619. var generateMipMaps = options.generateMipMaps ? options.generateMipMaps : false;
  45620. var generateDepthTexture = options.generateDepthTexture ? options.generateDepthTexture : false;
  45621. var doNotChangeAspectRatio = options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  45622. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  45623. if (!_this.isSupported) {
  45624. _this.dispose();
  45625. return;
  45626. }
  45627. var types = [];
  45628. var samplingModes = [];
  45629. for (var i = 0; i < count; i++) {
  45630. if (options.types && options.types[i]) {
  45631. types.push(options.types[i]);
  45632. }
  45633. else {
  45634. types.push(BABYLON.Engine.TEXTURETYPE_FLOAT);
  45635. }
  45636. if (options.samplingModes && options.samplingModes[i]) {
  45637. samplingModes.push(options.samplingModes[i]);
  45638. }
  45639. else {
  45640. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  45641. }
  45642. }
  45643. var generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  45644. var generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  45645. _this._count = count;
  45646. _this._size = size;
  45647. _this._multiRenderTargetOptions = {
  45648. samplingModes: samplingModes,
  45649. generateMipMaps: generateMipMaps,
  45650. generateDepthBuffer: generateDepthBuffer,
  45651. generateStencilBuffer: generateStencilBuffer,
  45652. generateDepthTexture: generateDepthTexture,
  45653. types: types,
  45654. textureCount: count
  45655. };
  45656. _this._internalTextures = scene.getEngine().createMultipleRenderTarget(size, _this._multiRenderTargetOptions);
  45657. _this._createInternalTextures();
  45658. return _this;
  45659. }
  45660. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  45661. get: function () {
  45662. var engine = this.getScene().getEngine();
  45663. return engine.webGLVersion > 1 || engine.getCaps().drawBuffersExtension;
  45664. },
  45665. enumerable: true,
  45666. configurable: true
  45667. });
  45668. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  45669. get: function () {
  45670. return this._textures;
  45671. },
  45672. enumerable: true,
  45673. configurable: true
  45674. });
  45675. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  45676. get: function () {
  45677. return this._textures[this._textures.length - 1];
  45678. },
  45679. enumerable: true,
  45680. configurable: true
  45681. });
  45682. MultiRenderTarget.prototype._createInternalTextures = function () {
  45683. this._textures = [];
  45684. for (var i = 0; i < this._internalTextures.length; i++) {
  45685. var texture = new BABYLON.Texture(null, this.getScene());
  45686. texture._texture = this._internalTextures[i];
  45687. this._textures.push(texture);
  45688. }
  45689. // Keeps references to frame buffer and stencil/depth buffer
  45690. this._texture = this._internalTextures[0];
  45691. };
  45692. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  45693. get: function () {
  45694. return this._samples;
  45695. },
  45696. set: function (value) {
  45697. if (this._samples === value) {
  45698. return;
  45699. }
  45700. for (var i = 0; i < this._internalTextures.length; i++) {
  45701. this._samples = this.getScene().getEngine().updateRenderTargetTextureSampleCount(this._internalTextures[i], value);
  45702. }
  45703. },
  45704. enumerable: true,
  45705. configurable: true
  45706. });
  45707. MultiRenderTarget.prototype.resize = function (size) {
  45708. this.releaseInternalTextures();
  45709. this._internalTextures = this.getScene().getEngine().createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  45710. this._createInternalTextures();
  45711. };
  45712. MultiRenderTarget.prototype.dispose = function () {
  45713. this.releaseInternalTextures();
  45714. _super.prototype.dispose.call(this);
  45715. };
  45716. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  45717. if (!this._internalTextures) {
  45718. return;
  45719. }
  45720. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  45721. if (this._internalTextures[i] !== undefined) {
  45722. this._internalTextures[i].dispose();
  45723. this._internalTextures.splice(i, 1);
  45724. }
  45725. }
  45726. };
  45727. return MultiRenderTarget;
  45728. }(BABYLON.RenderTargetTexture));
  45729. BABYLON.MultiRenderTarget = MultiRenderTarget;
  45730. })(BABYLON || (BABYLON = {}));
  45731. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  45732. /// <reference path="babylon.renderTargetTexture.ts" />
  45733. var BABYLON;
  45734. (function (BABYLON) {
  45735. var MirrorTexture = (function (_super) {
  45736. __extends(MirrorTexture, _super);
  45737. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  45738. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  45739. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  45740. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  45741. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  45742. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  45743. _this._transformMatrix = BABYLON.Matrix.Zero();
  45744. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  45745. _this._blurKernelX = 0;
  45746. _this._blurKernelY = 0;
  45747. _this._blurRatio = 1.0;
  45748. _this.onBeforeRenderObservable.add(function () {
  45749. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  45750. _this._savedViewMatrix = scene.getViewMatrix();
  45751. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  45752. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  45753. scene.clipPlane = _this.mirrorPlane;
  45754. scene.getEngine().cullBackFaces = false;
  45755. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  45756. });
  45757. _this.onAfterRenderObservable.add(function () {
  45758. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  45759. scene.getEngine().cullBackFaces = true;
  45760. scene._mirroredCameraPosition = null;
  45761. delete scene.clipPlane;
  45762. });
  45763. return _this;
  45764. }
  45765. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  45766. get: function () {
  45767. return this._blurRatio;
  45768. },
  45769. set: function (value) {
  45770. if (this._blurRatio === value) {
  45771. return;
  45772. }
  45773. this._blurRatio = value;
  45774. this._preparePostProcesses();
  45775. },
  45776. enumerable: true,
  45777. configurable: true
  45778. });
  45779. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  45780. set: function (value) {
  45781. this.blurKernelX = value;
  45782. this.blurKernelY = value;
  45783. },
  45784. enumerable: true,
  45785. configurable: true
  45786. });
  45787. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  45788. get: function () {
  45789. return this._blurKernelX;
  45790. },
  45791. set: function (value) {
  45792. if (this._blurKernelX === value) {
  45793. return;
  45794. }
  45795. this._blurKernelX = value;
  45796. this._preparePostProcesses();
  45797. },
  45798. enumerable: true,
  45799. configurable: true
  45800. });
  45801. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  45802. get: function () {
  45803. return this._blurKernelY;
  45804. },
  45805. set: function (value) {
  45806. if (this._blurKernelY === value) {
  45807. return;
  45808. }
  45809. this._blurKernelY = value;
  45810. this._preparePostProcesses();
  45811. },
  45812. enumerable: true,
  45813. configurable: true
  45814. });
  45815. MirrorTexture.prototype._preparePostProcesses = function () {
  45816. this.clearPostProcesses(true);
  45817. if (this._blurKernelX && this._blurKernelY) {
  45818. var engine = this.getScene().getEngine();
  45819. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  45820. this._blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), this._blurKernelX, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  45821. this._blurX.autoClear = false;
  45822. if (this._blurRatio === 1 && this.samples < 2) {
  45823. this._blurX.outputTexture = this._texture;
  45824. }
  45825. else {
  45826. this._blurX.alwaysForcePOT = true;
  45827. }
  45828. this._blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), this._blurKernelY, this._blurRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, textureType);
  45829. this._blurY.autoClear = false;
  45830. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  45831. this.addPostProcess(this._blurX);
  45832. this.addPostProcess(this._blurY);
  45833. }
  45834. };
  45835. MirrorTexture.prototype.clone = function () {
  45836. var textureSize = this.getSize();
  45837. var newTexture = new MirrorTexture(this.name, textureSize.width, this.getScene(), this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  45838. // Base texture
  45839. newTexture.hasAlpha = this.hasAlpha;
  45840. newTexture.level = this.level;
  45841. // Mirror Texture
  45842. newTexture.mirrorPlane = this.mirrorPlane.clone();
  45843. newTexture.renderList = this.renderList.slice(0);
  45844. return newTexture;
  45845. };
  45846. MirrorTexture.prototype.serialize = function () {
  45847. if (!this.name) {
  45848. return null;
  45849. }
  45850. var serializationObject = _super.prototype.serialize.call(this);
  45851. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  45852. return serializationObject;
  45853. };
  45854. return MirrorTexture;
  45855. }(BABYLON.RenderTargetTexture));
  45856. BABYLON.MirrorTexture = MirrorTexture;
  45857. })(BABYLON || (BABYLON = {}));
  45858. //# sourceMappingURL=babylon.mirrorTexture.js.map
  45859. /// <reference path="babylon.renderTargetTexture.ts" />
  45860. var BABYLON;
  45861. (function (BABYLON) {
  45862. /**
  45863. * Creates a refraction texture used by refraction channel of the standard material.
  45864. * @param name the texture name
  45865. * @param size size of the underlying texture
  45866. * @param scene root scene
  45867. */
  45868. var RefractionTexture = (function (_super) {
  45869. __extends(RefractionTexture, _super);
  45870. function RefractionTexture(name, size, scene, generateMipMaps) {
  45871. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  45872. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  45873. _this.depth = 2.0;
  45874. _this.onBeforeRenderObservable.add(function () {
  45875. scene.clipPlane = _this.refractionPlane;
  45876. });
  45877. _this.onAfterRenderObservable.add(function () {
  45878. delete scene.clipPlane;
  45879. });
  45880. return _this;
  45881. }
  45882. RefractionTexture.prototype.clone = function () {
  45883. var textureSize = this.getSize();
  45884. var newTexture = new RefractionTexture(this.name, textureSize.width, this.getScene(), this._generateMipMaps);
  45885. // Base texture
  45886. newTexture.hasAlpha = this.hasAlpha;
  45887. newTexture.level = this.level;
  45888. // Refraction Texture
  45889. newTexture.refractionPlane = this.refractionPlane.clone();
  45890. newTexture.renderList = this.renderList.slice(0);
  45891. newTexture.depth = this.depth;
  45892. return newTexture;
  45893. };
  45894. RefractionTexture.prototype.serialize = function () {
  45895. if (!this.name) {
  45896. return null;
  45897. }
  45898. var serializationObject = _super.prototype.serialize.call(this);
  45899. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  45900. serializationObject.depth = this.depth;
  45901. return serializationObject;
  45902. };
  45903. return RefractionTexture;
  45904. }(BABYLON.RenderTargetTexture));
  45905. BABYLON.RefractionTexture = RefractionTexture;
  45906. })(BABYLON || (BABYLON = {}));
  45907. //# sourceMappingURL=babylon.refractionTexture.js.map
  45908. /// <reference path="babylon.texture.ts" />
  45909. var BABYLON;
  45910. (function (BABYLON) {
  45911. var DynamicTexture = (function (_super) {
  45912. __extends(DynamicTexture, _super);
  45913. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  45914. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  45915. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  45916. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  45917. _this.name = name;
  45918. var engine = _this.getScene().getEngine();
  45919. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45920. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  45921. _this._generateMipMaps = generateMipMaps;
  45922. if (options.getContext) {
  45923. _this._canvas = options;
  45924. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45925. }
  45926. else {
  45927. _this._canvas = document.createElement("canvas");
  45928. if (options.width) {
  45929. _this._texture = engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  45930. }
  45931. else {
  45932. _this._texture = engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  45933. }
  45934. }
  45935. var textureSize = _this.getSize();
  45936. _this._canvas.width = textureSize.width;
  45937. _this._canvas.height = textureSize.height;
  45938. _this._context = _this._canvas.getContext("2d");
  45939. return _this;
  45940. }
  45941. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  45942. get: function () {
  45943. return true;
  45944. },
  45945. enumerable: true,
  45946. configurable: true
  45947. });
  45948. DynamicTexture.prototype._recreate = function (textureSize) {
  45949. this._canvas.width = textureSize.width;
  45950. this._canvas.height = textureSize.height;
  45951. this.releaseInternalTexture();
  45952. this._texture = this.getScene().getEngine().createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  45953. };
  45954. DynamicTexture.prototype.scale = function (ratio) {
  45955. var textureSize = this.getSize();
  45956. textureSize.width *= ratio;
  45957. textureSize.height *= ratio;
  45958. this._recreate(textureSize);
  45959. };
  45960. DynamicTexture.prototype.scaleTo = function (width, height) {
  45961. var textureSize = this.getSize();
  45962. textureSize.width = width;
  45963. textureSize.height = height;
  45964. this._recreate(textureSize);
  45965. };
  45966. DynamicTexture.prototype.getContext = function () {
  45967. return this._context;
  45968. };
  45969. DynamicTexture.prototype.clear = function () {
  45970. var size = this.getSize();
  45971. this._context.fillRect(0, 0, size.width, size.height);
  45972. };
  45973. DynamicTexture.prototype.update = function (invertY) {
  45974. this.getScene().getEngine().updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format);
  45975. };
  45976. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  45977. if (update === void 0) { update = true; }
  45978. var size = this.getSize();
  45979. if (clearColor) {
  45980. this._context.fillStyle = clearColor;
  45981. this._context.fillRect(0, 0, size.width, size.height);
  45982. }
  45983. this._context.font = font;
  45984. if (x === null || x === undefined) {
  45985. var textSize = this._context.measureText(text);
  45986. x = (size.width - textSize.width) / 2;
  45987. }
  45988. if (y === null || y === undefined) {
  45989. var fontSize = parseInt((font.replace(/\D/g, '')));
  45990. ;
  45991. y = (size.height / 2) + (fontSize / 3.65);
  45992. }
  45993. this._context.fillStyle = color;
  45994. this._context.fillText(text, x, y);
  45995. if (update) {
  45996. this.update(invertY);
  45997. }
  45998. };
  45999. DynamicTexture.prototype.clone = function () {
  46000. var textureSize = this.getSize();
  46001. var newTexture = new DynamicTexture(this.name, textureSize, this.getScene(), this._generateMipMaps);
  46002. // Base texture
  46003. newTexture.hasAlpha = this.hasAlpha;
  46004. newTexture.level = this.level;
  46005. // Dynamic Texture
  46006. newTexture.wrapU = this.wrapU;
  46007. newTexture.wrapV = this.wrapV;
  46008. return newTexture;
  46009. };
  46010. DynamicTexture.prototype._rebuild = function () {
  46011. this.update();
  46012. };
  46013. return DynamicTexture;
  46014. }(BABYLON.Texture));
  46015. BABYLON.DynamicTexture = DynamicTexture;
  46016. })(BABYLON || (BABYLON = {}));
  46017. //# sourceMappingURL=babylon.dynamicTexture.js.map
  46018. var BABYLON;
  46019. (function (BABYLON) {
  46020. var VideoTexture = (function (_super) {
  46021. __extends(VideoTexture, _super);
  46022. /**
  46023. * Creates a video texture.
  46024. * Sample : https://doc.babylonjs.com/tutorials/01._Advanced_Texturing
  46025. * @param {Array} urlsOrVideo can be used to provide an array of urls or an already setup HTML video element.
  46026. * @param {BABYLON.Scene} scene is obviously the current scene.
  46027. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  46028. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  46029. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  46030. */
  46031. function VideoTexture(name, urlsOrVideo, scene, generateMipMaps, invertY, samplingMode) {
  46032. if (generateMipMaps === void 0) { generateMipMaps = false; }
  46033. if (invertY === void 0) { invertY = false; }
  46034. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46035. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46036. _this._autoLaunch = true;
  46037. var urls;
  46038. _this.name = name;
  46039. if (urlsOrVideo instanceof HTMLVideoElement) {
  46040. _this.video = urlsOrVideo;
  46041. }
  46042. else {
  46043. urls = urlsOrVideo;
  46044. _this.video = document.createElement("video");
  46045. _this.video.autoplay = false;
  46046. _this.video.loop = true;
  46047. }
  46048. _this._generateMipMaps = generateMipMaps;
  46049. _this._samplingMode = samplingMode;
  46050. if (!_this.getScene().getEngine().needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  46051. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  46052. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  46053. }
  46054. else {
  46055. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46056. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46057. _this._generateMipMaps = false;
  46058. }
  46059. if (urls) {
  46060. _this.video.addEventListener("canplay", function () {
  46061. _this._createTexture();
  46062. });
  46063. urls.forEach(function (url) {
  46064. var source = document.createElement("source");
  46065. source.src = url;
  46066. _this.video.appendChild(source);
  46067. });
  46068. }
  46069. else {
  46070. _this._createTexture();
  46071. }
  46072. _this._lastUpdate = BABYLON.Tools.Now;
  46073. return _this;
  46074. }
  46075. VideoTexture.prototype.__setTextureReady = function () {
  46076. this._texture.isReady = true;
  46077. };
  46078. VideoTexture.prototype._createTexture = function () {
  46079. this._texture = this.getScene().getEngine().createDynamicTexture(this.video.videoWidth, this.video.videoHeight, this._generateMipMaps, this._samplingMode);
  46080. if (this._autoLaunch) {
  46081. this._autoLaunch = false;
  46082. this.video.play();
  46083. }
  46084. this._setTextureReady = this.__setTextureReady.bind(this);
  46085. this.video.addEventListener("playing", this._setTextureReady);
  46086. };
  46087. VideoTexture.prototype.update = function () {
  46088. var now = BABYLON.Tools.Now;
  46089. if (now - this._lastUpdate < 15 || this.video.readyState !== this.video.HAVE_ENOUGH_DATA) {
  46090. return false;
  46091. }
  46092. this._lastUpdate = now;
  46093. this.getScene().getEngine().updateVideoTexture(this._texture, this.video, this._invertY);
  46094. return true;
  46095. };
  46096. VideoTexture.prototype.dispose = function () {
  46097. _super.prototype.dispose.call(this);
  46098. this.video.removeEventListener("playing", this._setTextureReady);
  46099. };
  46100. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  46101. var video = document.createElement("video");
  46102. var constraintsDeviceId;
  46103. if (constraints && constraints.deviceId) {
  46104. constraintsDeviceId = {
  46105. exact: constraints.deviceId
  46106. };
  46107. }
  46108. navigator.getUserMedia = navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
  46109. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  46110. if (navigator.getUserMedia) {
  46111. navigator.getUserMedia({
  46112. video: {
  46113. deviceId: constraintsDeviceId,
  46114. width: {
  46115. min: (constraints && constraints.minWidth) || 256,
  46116. max: (constraints && constraints.maxWidth) || 640
  46117. },
  46118. height: {
  46119. min: (constraints && constraints.minHeight) || 256,
  46120. max: (constraints && constraints.maxHeight) || 480
  46121. }
  46122. }
  46123. }, function (stream) {
  46124. if (video.mozSrcObject !== undefined) {
  46125. video.mozSrcObject = stream;
  46126. }
  46127. else {
  46128. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  46129. }
  46130. video.play();
  46131. if (onReady) {
  46132. onReady(new BABYLON.VideoTexture("video", video, scene, true, true));
  46133. }
  46134. }, function (e) {
  46135. BABYLON.Tools.Error(e.name);
  46136. });
  46137. }
  46138. };
  46139. return VideoTexture;
  46140. }(BABYLON.Texture));
  46141. BABYLON.VideoTexture = VideoTexture;
  46142. })(BABYLON || (BABYLON = {}));
  46143. //# sourceMappingURL=babylon.videoTexture.js.map
  46144. var BABYLON;
  46145. (function (BABYLON) {
  46146. var RawTexture = (function (_super) {
  46147. __extends(RawTexture, _super);
  46148. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode) {
  46149. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46150. if (invertY === void 0) { invertY = false; }
  46151. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46152. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  46153. _this.format = format;
  46154. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode);
  46155. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46156. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46157. return _this;
  46158. }
  46159. RawTexture.prototype.update = function (data) {
  46160. this.getScene().getEngine().updateRawTexture(this._texture, data, this.format, this._invertY);
  46161. };
  46162. // Statics
  46163. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46165. if (invertY === void 0) { invertY = false; }
  46166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46167. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  46168. };
  46169. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46170. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46171. if (invertY === void 0) { invertY = false; }
  46172. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46173. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46174. };
  46175. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46176. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46177. if (invertY === void 0) { invertY = false; }
  46178. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46179. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  46180. };
  46181. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46182. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46183. if (invertY === void 0) { invertY = false; }
  46184. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46185. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode);
  46186. };
  46187. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  46188. if (generateMipMaps === void 0) { generateMipMaps = true; }
  46189. if (invertY === void 0) { invertY = false; }
  46190. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  46191. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode);
  46192. };
  46193. return RawTexture;
  46194. }(BABYLON.Texture));
  46195. BABYLON.RawTexture = RawTexture;
  46196. })(BABYLON || (BABYLON = {}));
  46197. //# sourceMappingURL=babylon.rawTexture.js.map
  46198. var BABYLON;
  46199. (function (BABYLON) {
  46200. var PostProcess = (function () {
  46201. function PostProcess(name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  46202. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  46203. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46204. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  46205. if (blockCompilation === void 0) { blockCompilation = false; }
  46206. this.name = name;
  46207. this.width = -1;
  46208. this.height = -1;
  46209. this.autoClear = true;
  46210. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  46211. /*
  46212. Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  46213. Can only be used on a single postprocess or on the last one of a chain.
  46214. */
  46215. this.enablePixelPerfectMode = false;
  46216. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  46217. this.alwaysForcePOT = false;
  46218. this.samples = 1;
  46219. this._reusable = false;
  46220. this._textures = new BABYLON.SmartArray(2);
  46221. this._currentRenderTextureInd = 0;
  46222. this._scaleRatio = new BABYLON.Vector2(1, 1);
  46223. this._texelSize = BABYLON.Vector2.Zero();
  46224. // Events
  46225. /**
  46226. * An event triggered when the postprocess is activated.
  46227. * @type {BABYLON.Observable}
  46228. */
  46229. this.onActivateObservable = new BABYLON.Observable();
  46230. /**
  46231. * An event triggered when the postprocess changes its size.
  46232. * @type {BABYLON.Observable}
  46233. */
  46234. this.onSizeChangedObservable = new BABYLON.Observable();
  46235. /**
  46236. * An event triggered when the postprocess applies its effect.
  46237. * @type {BABYLON.Observable}
  46238. */
  46239. this.onApplyObservable = new BABYLON.Observable();
  46240. /**
  46241. * An event triggered before rendering the postprocess
  46242. * @type {BABYLON.Observable}
  46243. */
  46244. this.onBeforeRenderObservable = new BABYLON.Observable();
  46245. /**
  46246. * An event triggered after rendering the postprocess
  46247. * @type {BABYLON.Observable}
  46248. */
  46249. this.onAfterRenderObservable = new BABYLON.Observable();
  46250. if (camera != null) {
  46251. this._camera = camera;
  46252. this._scene = camera.getScene();
  46253. camera.attachPostProcess(this);
  46254. this._engine = this._scene.getEngine();
  46255. this._scene.postProcesses.push(this);
  46256. }
  46257. else {
  46258. this._engine = engine;
  46259. this._engine.postProcesses.push(this);
  46260. }
  46261. this._options = options;
  46262. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  46263. this._reusable = reusable || false;
  46264. this._textureType = textureType;
  46265. this._samplers = samplers || [];
  46266. this._samplers.push("textureSampler");
  46267. this._fragmentUrl = fragmentUrl;
  46268. this._vertexUrl = vertexUrl;
  46269. this._parameters = parameters || [];
  46270. this._parameters.push("scale");
  46271. this._indexParameters = indexParameters;
  46272. if (!blockCompilation) {
  46273. this.updateEffect(defines);
  46274. }
  46275. }
  46276. Object.defineProperty(PostProcess.prototype, "onActivate", {
  46277. set: function (callback) {
  46278. if (this._onActivateObserver) {
  46279. this.onActivateObservable.remove(this._onActivateObserver);
  46280. }
  46281. this._onActivateObserver = this.onActivateObservable.add(callback);
  46282. },
  46283. enumerable: true,
  46284. configurable: true
  46285. });
  46286. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  46287. set: function (callback) {
  46288. if (this._onSizeChangedObserver) {
  46289. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  46290. }
  46291. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  46292. },
  46293. enumerable: true,
  46294. configurable: true
  46295. });
  46296. Object.defineProperty(PostProcess.prototype, "onApply", {
  46297. set: function (callback) {
  46298. if (this._onApplyObserver) {
  46299. this.onApplyObservable.remove(this._onApplyObserver);
  46300. }
  46301. this._onApplyObserver = this.onApplyObservable.add(callback);
  46302. },
  46303. enumerable: true,
  46304. configurable: true
  46305. });
  46306. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  46307. set: function (callback) {
  46308. if (this._onBeforeRenderObserver) {
  46309. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  46310. }
  46311. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  46312. },
  46313. enumerable: true,
  46314. configurable: true
  46315. });
  46316. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  46317. set: function (callback) {
  46318. if (this._onAfterRenderObserver) {
  46319. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  46320. }
  46321. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  46322. },
  46323. enumerable: true,
  46324. configurable: true
  46325. });
  46326. Object.defineProperty(PostProcess.prototype, "outputTexture", {
  46327. get: function () {
  46328. return this._textures.data[this._currentRenderTextureInd];
  46329. },
  46330. set: function (value) {
  46331. this._forcedOutputTexture = value;
  46332. },
  46333. enumerable: true,
  46334. configurable: true
  46335. });
  46336. PostProcess.prototype.getCamera = function () {
  46337. return this._camera;
  46338. };
  46339. Object.defineProperty(PostProcess.prototype, "texelSize", {
  46340. get: function () {
  46341. if (this._shareOutputWithPostProcess) {
  46342. return this._shareOutputWithPostProcess.texelSize;
  46343. }
  46344. if (this._forcedOutputTexture) {
  46345. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  46346. }
  46347. return this._texelSize;
  46348. },
  46349. enumerable: true,
  46350. configurable: true
  46351. });
  46352. PostProcess.prototype.getEngine = function () {
  46353. return this._engine;
  46354. };
  46355. PostProcess.prototype.getEffect = function () {
  46356. return this._effect;
  46357. };
  46358. PostProcess.prototype.shareOutputWith = function (postProcess) {
  46359. this._disposeTextures();
  46360. this._shareOutputWithPostProcess = postProcess;
  46361. return this;
  46362. };
  46363. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  46364. this._effect = this._engine.createEffect({ vertex: this._vertexUrl, fragment: this._fragmentUrl }, ["position"], uniforms || this._parameters, samplers || this._samplers, defines !== undefined ? defines : "", null, onCompiled, onError, indexParameters || this._indexParameters);
  46365. };
  46366. PostProcess.prototype.isReusable = function () {
  46367. return this._reusable;
  46368. };
  46369. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  46370. PostProcess.prototype.markTextureDirty = function () {
  46371. this.width = -1;
  46372. };
  46373. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  46374. var _this = this;
  46375. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  46376. camera = camera || this._camera;
  46377. var scene = camera.getScene();
  46378. var engine = scene.getEngine();
  46379. var maxSize = engine.getCaps().maxTextureSize;
  46380. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderingCanvas().width) * this._options) | 0;
  46381. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderingCanvas().height) * this._options) | 0;
  46382. var desiredWidth = this._options.width || requiredWidth;
  46383. var desiredHeight = this._options.height || requiredHeight;
  46384. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  46385. if (!this._options.width) {
  46386. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  46387. }
  46388. if (!this._options.height) {
  46389. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  46390. }
  46391. }
  46392. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  46393. if (this._textures.length > 0) {
  46394. for (var i = 0; i < this._textures.length; i++) {
  46395. this._engine._releaseTexture(this._textures.data[i]);
  46396. }
  46397. this._textures.reset();
  46398. }
  46399. this.width = desiredWidth;
  46400. this.height = desiredHeight;
  46401. var textureSize = { width: this.width, height: this.height };
  46402. var textureOptions = {
  46403. generateMipMaps: false,
  46404. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  46405. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  46406. samplingMode: this.renderTargetSamplingMode,
  46407. type: this._textureType
  46408. };
  46409. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46410. if (this._reusable) {
  46411. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  46412. }
  46413. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  46414. this.onSizeChangedObservable.notifyObservers(this);
  46415. }
  46416. this._textures.forEach(function (texture) {
  46417. if (texture.samples !== _this.samples) {
  46418. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  46419. }
  46420. });
  46421. }
  46422. var target;
  46423. if (this._shareOutputWithPostProcess) {
  46424. target = this._shareOutputWithPostProcess.outputTexture;
  46425. }
  46426. else if (this._forcedOutputTexture) {
  46427. target = this._forcedOutputTexture;
  46428. this.width = this._forcedOutputTexture.width;
  46429. this.height = this._forcedOutputTexture.height;
  46430. }
  46431. else {
  46432. target = this.outputTexture;
  46433. }
  46434. if (this.enablePixelPerfectMode) {
  46435. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  46436. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  46437. }
  46438. else {
  46439. this._scaleRatio.copyFromFloats(1, 1);
  46440. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  46441. }
  46442. this.onActivateObservable.notifyObservers(camera);
  46443. // Clear
  46444. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  46445. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  46446. }
  46447. if (this._reusable) {
  46448. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  46449. }
  46450. };
  46451. Object.defineProperty(PostProcess.prototype, "isSupported", {
  46452. get: function () {
  46453. return this._effect.isSupported;
  46454. },
  46455. enumerable: true,
  46456. configurable: true
  46457. });
  46458. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  46459. get: function () {
  46460. if (this._shareOutputWithPostProcess) {
  46461. return this._shareOutputWithPostProcess.aspectRatio;
  46462. }
  46463. if (this._forcedOutputTexture) {
  46464. var size = this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  46465. }
  46466. return this.width / this.height;
  46467. },
  46468. enumerable: true,
  46469. configurable: true
  46470. });
  46471. PostProcess.prototype.apply = function () {
  46472. // Check
  46473. if (!this._effect || !this._effect.isReady())
  46474. return null;
  46475. // States
  46476. this._engine.enableEffect(this._effect);
  46477. this._engine.setState(false);
  46478. this._engine.setDepthBuffer(false);
  46479. this._engine.setDepthWrite(false);
  46480. // Alpha
  46481. this._engine.setAlphaMode(this.alphaMode);
  46482. if (this.alphaConstants) {
  46483. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  46484. }
  46485. // Texture
  46486. var source;
  46487. if (this._shareOutputWithPostProcess) {
  46488. source = this._shareOutputWithPostProcess.outputTexture;
  46489. }
  46490. else if (this._forcedOutputTexture) {
  46491. source = this._forcedOutputTexture;
  46492. }
  46493. else {
  46494. source = this.outputTexture;
  46495. }
  46496. this._effect._bindTexture("textureSampler", source);
  46497. // Parameters
  46498. this._effect.setVector2("scale", this._scaleRatio);
  46499. this.onApplyObservable.notifyObservers(this._effect);
  46500. return this._effect;
  46501. };
  46502. PostProcess.prototype._disposeTextures = function () {
  46503. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  46504. return;
  46505. }
  46506. if (this._textures.length > 0) {
  46507. for (var i = 0; i < this._textures.length; i++) {
  46508. this._engine._releaseTexture(this._textures.data[i]);
  46509. }
  46510. }
  46511. this._textures.dispose();
  46512. };
  46513. PostProcess.prototype._rebuild = function () {
  46514. };
  46515. PostProcess.prototype.dispose = function (camera) {
  46516. camera = camera || this._camera;
  46517. this._disposeTextures();
  46518. if (this._scene) {
  46519. var index_1 = this._scene.postProcesses.indexOf(this);
  46520. if (index_1 !== -1) {
  46521. this._scene.postProcesses.splice(index_1, 1);
  46522. }
  46523. }
  46524. else {
  46525. var index_2 = this._engine.postProcesses.indexOf(this);
  46526. if (index_2 !== -1) {
  46527. this._engine.postProcesses.splice(index_2, 1);
  46528. }
  46529. }
  46530. if (!camera) {
  46531. return;
  46532. }
  46533. camera.detachPostProcess(this);
  46534. var index = camera._postProcesses.indexOf(this);
  46535. if (index === 0 && camera._postProcesses.length > 0) {
  46536. this._camera._postProcesses[0].markTextureDirty();
  46537. }
  46538. this.onActivateObservable.clear();
  46539. this.onAfterRenderObservable.clear();
  46540. this.onApplyObservable.clear();
  46541. this.onBeforeRenderObservable.clear();
  46542. this.onSizeChangedObservable.clear();
  46543. };
  46544. return PostProcess;
  46545. }());
  46546. BABYLON.PostProcess = PostProcess;
  46547. })(BABYLON || (BABYLON = {}));
  46548. //# sourceMappingURL=babylon.postProcess.js.map
  46549. var BABYLON;
  46550. (function (BABYLON) {
  46551. var PassPostProcess = (function (_super) {
  46552. __extends(PassPostProcess, _super);
  46553. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  46554. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  46555. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  46556. }
  46557. return PassPostProcess;
  46558. }(BABYLON.PostProcess));
  46559. BABYLON.PassPostProcess = PassPostProcess;
  46560. })(BABYLON || (BABYLON = {}));
  46561. //# sourceMappingURL=babylon.passPostProcess.js.map
  46562. var BABYLON;
  46563. (function (BABYLON) {
  46564. var ShadowGenerator = (function () {
  46565. /**
  46566. * Creates a ShadowGenerator object.
  46567. * A ShadowGenerator is the required tool to use the shadows.
  46568. * Each light casting shadows needs to use its own ShadowGenerator.
  46569. * Required parameters :
  46570. * - `mapSize` (integer): the size of the texture what stores the shadows. Example : 1024.
  46571. * - `light`: the light object generating the shadows.
  46572. * - `useFullFloatFirst`: by default the generator will try to use half float textures but if you need precision (for self shadowing for instance), you can use this option to enforce full float texture.
  46573. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  46574. */
  46575. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  46576. // Members
  46577. this._bias = 0.00005;
  46578. this._blurBoxOffset = 1;
  46579. this._blurScale = 2;
  46580. this._blurKernel = 1;
  46581. this._useKernelBlur = false;
  46582. this._filter = ShadowGenerator.FILTER_NONE;
  46583. this._darkness = 0;
  46584. this._transparencyShadow = false;
  46585. /**
  46586. * Controls the extent to which the shadows fade out at the edge of the frustum
  46587. * Used only by directionals and spots
  46588. */
  46589. this.frustumEdgeFalloff = 0;
  46590. this.forceBackFacesOnly = false;
  46591. this._lightDirection = BABYLON.Vector3.Zero();
  46592. this._viewMatrix = BABYLON.Matrix.Zero();
  46593. this._projectionMatrix = BABYLON.Matrix.Zero();
  46594. this._transformMatrix = BABYLON.Matrix.Zero();
  46595. this._worldViewProjection = BABYLON.Matrix.Zero();
  46596. this._currentFaceIndex = 0;
  46597. this._currentFaceIndexCache = 0;
  46598. this._isCube = false;
  46599. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  46600. this._mapSize = mapSize;
  46601. this._light = light;
  46602. this._scene = light.getScene();
  46603. light._shadowGenerator = this;
  46604. // Texture type fallback from float to int if not supported.
  46605. var caps = this._scene.getEngine().getCaps();
  46606. if (!useFullFloatFirst) {
  46607. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46608. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46609. }
  46610. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46611. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46612. }
  46613. else {
  46614. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46615. }
  46616. }
  46617. else {
  46618. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  46619. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  46620. }
  46621. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  46622. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  46623. }
  46624. else {
  46625. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  46626. }
  46627. }
  46628. this._initializeGenerator();
  46629. }
  46630. Object.defineProperty(ShadowGenerator, "FILTER_NONE", {
  46631. // Static
  46632. get: function () {
  46633. return ShadowGenerator._FILTER_NONE;
  46634. },
  46635. enumerable: true,
  46636. configurable: true
  46637. });
  46638. Object.defineProperty(ShadowGenerator, "FILTER_POISSONSAMPLING", {
  46639. get: function () {
  46640. return ShadowGenerator._FILTER_POISSONSAMPLING;
  46641. },
  46642. enumerable: true,
  46643. configurable: true
  46644. });
  46645. Object.defineProperty(ShadowGenerator, "FILTER_EXPONENTIALSHADOWMAP", {
  46646. get: function () {
  46647. return ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP;
  46648. },
  46649. enumerable: true,
  46650. configurable: true
  46651. });
  46652. Object.defineProperty(ShadowGenerator, "FILTER_BLUREXPONENTIALSHADOWMAP", {
  46653. get: function () {
  46654. return ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP;
  46655. },
  46656. enumerable: true,
  46657. configurable: true
  46658. });
  46659. Object.defineProperty(ShadowGenerator, "FILTER_CLOSEEXPONENTIALSHADOWMAP", {
  46660. get: function () {
  46661. return ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46662. },
  46663. enumerable: true,
  46664. configurable: true
  46665. });
  46666. Object.defineProperty(ShadowGenerator, "FILTER_BLURCLOSEEXPONENTIALSHADOWMAP", {
  46667. get: function () {
  46668. return ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46669. },
  46670. enumerable: true,
  46671. configurable: true
  46672. });
  46673. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  46674. get: function () {
  46675. return this._bias;
  46676. },
  46677. set: function (bias) {
  46678. this._bias = bias;
  46679. },
  46680. enumerable: true,
  46681. configurable: true
  46682. });
  46683. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  46684. get: function () {
  46685. return this._blurBoxOffset;
  46686. },
  46687. set: function (value) {
  46688. if (this._blurBoxOffset === value) {
  46689. return;
  46690. }
  46691. this._blurBoxOffset = value;
  46692. this._disposeBlurPostProcesses();
  46693. },
  46694. enumerable: true,
  46695. configurable: true
  46696. });
  46697. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  46698. get: function () {
  46699. return this._blurScale;
  46700. },
  46701. set: function (value) {
  46702. if (this._blurScale === value) {
  46703. return;
  46704. }
  46705. this._blurScale = value;
  46706. this._disposeBlurPostProcesses();
  46707. },
  46708. enumerable: true,
  46709. configurable: true
  46710. });
  46711. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  46712. get: function () {
  46713. return this._blurKernel;
  46714. },
  46715. set: function (value) {
  46716. if (this._blurKernel === value) {
  46717. return;
  46718. }
  46719. this._blurKernel = value;
  46720. this._disposeBlurPostProcesses();
  46721. },
  46722. enumerable: true,
  46723. configurable: true
  46724. });
  46725. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  46726. get: function () {
  46727. return this._useKernelBlur;
  46728. },
  46729. set: function (value) {
  46730. if (this._useKernelBlur === value) {
  46731. return;
  46732. }
  46733. this._useKernelBlur = value;
  46734. this._disposeBlurPostProcesses();
  46735. },
  46736. enumerable: true,
  46737. configurable: true
  46738. });
  46739. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  46740. get: function () {
  46741. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  46742. },
  46743. set: function (value) {
  46744. this._depthScale = value;
  46745. },
  46746. enumerable: true,
  46747. configurable: true
  46748. });
  46749. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  46750. get: function () {
  46751. return this._filter;
  46752. },
  46753. set: function (value) {
  46754. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  46755. if (this._light.needCube()) {
  46756. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46757. this.useExponentialShadowMap = true;
  46758. return;
  46759. }
  46760. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46761. this.useCloseExponentialShadowMap = true;
  46762. return;
  46763. }
  46764. }
  46765. if (this._filter === value) {
  46766. return;
  46767. }
  46768. this._filter = value;
  46769. this._disposeBlurPostProcesses();
  46770. this._applyFilterValues();
  46771. this._light._markMeshesAsLightDirty();
  46772. },
  46773. enumerable: true,
  46774. configurable: true
  46775. });
  46776. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  46777. get: function () {
  46778. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  46779. },
  46780. set: function (value) {
  46781. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  46782. return;
  46783. }
  46784. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  46785. },
  46786. enumerable: true,
  46787. configurable: true
  46788. });
  46789. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  46790. get: function () {
  46791. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46792. return this.useExponentialShadowMap;
  46793. },
  46794. set: function (value) {
  46795. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  46796. this.useExponentialShadowMap = value;
  46797. },
  46798. enumerable: true,
  46799. configurable: true
  46800. });
  46801. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  46802. get: function () {
  46803. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46804. return this.useBlurExponentialShadowMap;
  46805. },
  46806. set: function (value) {
  46807. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  46808. this.useBlurExponentialShadowMap = value;
  46809. },
  46810. enumerable: true,
  46811. configurable: true
  46812. });
  46813. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  46814. get: function () {
  46815. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  46816. },
  46817. set: function (value) {
  46818. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  46819. return;
  46820. }
  46821. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46822. },
  46823. enumerable: true,
  46824. configurable: true
  46825. });
  46826. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  46827. get: function () {
  46828. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  46829. },
  46830. set: function (value) {
  46831. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  46832. return;
  46833. }
  46834. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46835. },
  46836. enumerable: true,
  46837. configurable: true
  46838. });
  46839. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  46840. get: function () {
  46841. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  46842. },
  46843. set: function (value) {
  46844. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  46845. return;
  46846. }
  46847. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46848. },
  46849. enumerable: true,
  46850. configurable: true
  46851. });
  46852. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  46853. get: function () {
  46854. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  46855. },
  46856. set: function (value) {
  46857. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  46858. return;
  46859. }
  46860. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  46861. },
  46862. enumerable: true,
  46863. configurable: true
  46864. });
  46865. /**
  46866. * Returns the darkness value (float).
  46867. */
  46868. ShadowGenerator.prototype.getDarkness = function () {
  46869. return this._darkness;
  46870. };
  46871. /**
  46872. * Sets the ShadowGenerator darkness value (float <= 1.0).
  46873. * Returns the ShadowGenerator.
  46874. */
  46875. ShadowGenerator.prototype.setDarkness = function (darkness) {
  46876. if (darkness >= 1.0)
  46877. this._darkness = 1.0;
  46878. else if (darkness <= 0.0)
  46879. this._darkness = 0.0;
  46880. else
  46881. this._darkness = darkness;
  46882. return this;
  46883. };
  46884. /**
  46885. * Sets the ability to have transparent shadow (boolean).
  46886. * Returns the ShadowGenerator.
  46887. */
  46888. ShadowGenerator.prototype.setTransparencyShadow = function (hasShadow) {
  46889. this._transparencyShadow = hasShadow;
  46890. return this;
  46891. };
  46892. /**
  46893. * Returns a RenderTargetTexture object : the shadow map texture.
  46894. */
  46895. ShadowGenerator.prototype.getShadowMap = function () {
  46896. return this._shadowMap;
  46897. };
  46898. /**
  46899. * Returns the most ready computed shadow map as a RenderTargetTexture object.
  46900. */
  46901. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  46902. if (this._shadowMap2) {
  46903. return this._shadowMap2;
  46904. }
  46905. return this._shadowMap;
  46906. };
  46907. /**
  46908. * Returns the associated light object.
  46909. */
  46910. ShadowGenerator.prototype.getLight = function () {
  46911. return this._light;
  46912. };
  46913. ShadowGenerator.prototype._initializeGenerator = function () {
  46914. this._light._markMeshesAsLightDirty();
  46915. this._initializeShadowMap();
  46916. };
  46917. ShadowGenerator.prototype._initializeShadowMap = function () {
  46918. var _this = this;
  46919. // Render target
  46920. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  46921. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46922. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46923. this._shadowMap.anisotropicFilteringLevel = 1;
  46924. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46925. this._shadowMap.renderParticles = false;
  46926. // Record Face Index before render.
  46927. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  46928. _this._currentFaceIndex = faceIndex;
  46929. });
  46930. // Custom render function.
  46931. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  46932. // Blur if required afer render.
  46933. this._shadowMap.onAfterUnbindObservable.add(function () {
  46934. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  46935. return;
  46936. }
  46937. if (!_this._blurPostProcesses) {
  46938. _this._initializeBlurRTTAndPostProcesses();
  46939. }
  46940. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, _this.getShadowMapForRendering().getInternalTexture());
  46941. });
  46942. // Clear according to the chosen filter.
  46943. this._shadowMap.onClearObservable.add(function (engine) {
  46944. if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  46945. engine.clear(new BABYLON.Color4(0, 0, 0, 0), true, true, true);
  46946. }
  46947. else {
  46948. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  46949. }
  46950. });
  46951. };
  46952. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  46953. var _this = this;
  46954. var engine = this._scene.getEngine();
  46955. var targetSize = this._mapSize / this.blurScale;
  46956. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  46957. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  46958. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46959. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  46960. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  46961. }
  46962. if (this.useKernelBlur) {
  46963. this._kernelBlurXPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurX", new BABYLON.Vector2(1, 0), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  46964. this._kernelBlurXPostprocess.width = targetSize;
  46965. this._kernelBlurXPostprocess.height = targetSize;
  46966. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  46967. effect.setTexture("textureSampler", _this._shadowMap);
  46968. });
  46969. this._kernelBlurYPostprocess = new BABYLON.BlurPostProcess(this._light.name + "KernelBlurY", new BABYLON.Vector2(0, 1), this.blurKernel, 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._textureType);
  46970. this._kernelBlurXPostprocess.autoClear = false;
  46971. this._kernelBlurYPostprocess.autoClear = false;
  46972. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  46973. this._kernelBlurXPostprocess.packedFloat = true;
  46974. this._kernelBlurYPostprocess.packedFloat = true;
  46975. }
  46976. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  46977. }
  46978. else {
  46979. this._boxBlurPostprocess = new BABYLON.PostProcess(this._light.name + "DepthBoxBlur", "depthBoxBlur", ["screenSize", "boxOffset"], [], 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, "#define OFFSET " + this._blurBoxOffset, this._textureType);
  46980. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  46981. effect.setFloat2("screenSize", targetSize, targetSize);
  46982. effect.setTexture("textureSampler", _this._shadowMap);
  46983. });
  46984. this._boxBlurPostprocess.autoClear = false;
  46985. this._blurPostProcesses = [this._boxBlurPostprocess];
  46986. }
  46987. };
  46988. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  46989. var index;
  46990. for (index = 0; index < opaqueSubMeshes.length; index++) {
  46991. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  46992. }
  46993. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  46994. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  46995. }
  46996. if (this._transparencyShadow) {
  46997. for (index = 0; index < transparentSubMeshes.length; index++) {
  46998. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  46999. }
  47000. }
  47001. };
  47002. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  47003. var _this = this;
  47004. var mesh = subMesh.getRenderingMesh();
  47005. var scene = this._scene;
  47006. var engine = scene.getEngine();
  47007. // Culling
  47008. engine.setState(subMesh.getMaterial().backFaceCulling);
  47009. // Managing instances
  47010. var batch = mesh._getInstancesRenderList(subMesh._id);
  47011. if (batch.mustReturn) {
  47012. return;
  47013. }
  47014. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  47015. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  47016. engine.enableEffect(this._effect);
  47017. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  47018. var material = subMesh.getMaterial();
  47019. this._effect.setFloat2("biasAndScale", this.bias, this.depthScale);
  47020. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  47021. this._effect.setVector3("lightPosition", this.getLight().position);
  47022. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  47023. // Alpha test
  47024. if (material && material.needAlphaTesting()) {
  47025. var alphaTexture = material.getAlphaTestTexture();
  47026. if (alphaTexture) {
  47027. this._effect.setTexture("diffuseSampler", alphaTexture);
  47028. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  47029. }
  47030. }
  47031. // Bones
  47032. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47033. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  47034. }
  47035. if (this.forceBackFacesOnly) {
  47036. engine.setState(true, 0, false, true);
  47037. }
  47038. // Draw
  47039. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  47040. if (this.forceBackFacesOnly) {
  47041. engine.setState(true, 0, false, false);
  47042. }
  47043. }
  47044. else {
  47045. // Need to reset refresh rate of the shadowMap
  47046. this._shadowMap.resetRefreshCounter();
  47047. }
  47048. };
  47049. ShadowGenerator.prototype._applyFilterValues = function () {
  47050. if (this.filter === ShadowGenerator.FILTER_NONE) {
  47051. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  47052. }
  47053. else {
  47054. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  47055. }
  47056. };
  47057. /**
  47058. * Force shader compilation including textures ready check
  47059. */
  47060. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  47061. var _this = this;
  47062. var scene = this._scene;
  47063. var engine = scene.getEngine();
  47064. var subMeshes = new Array();
  47065. var currentIndex = 0;
  47066. for (var _i = 0, _a = this.getShadowMap().renderList; _i < _a.length; _i++) {
  47067. var mesh = _a[_i];
  47068. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  47069. }
  47070. var checkReady = function () {
  47071. if (!_this._scene || !_this._scene.getEngine()) {
  47072. return;
  47073. }
  47074. var subMesh = subMeshes[currentIndex];
  47075. if (_this.isReady(subMesh, options ? options.useInstances : false)) {
  47076. currentIndex++;
  47077. if (currentIndex >= subMeshes.length) {
  47078. if (onCompiled) {
  47079. onCompiled(_this);
  47080. }
  47081. return;
  47082. }
  47083. }
  47084. setTimeout(checkReady, 16);
  47085. };
  47086. if (subMeshes.length > 0) {
  47087. checkReady();
  47088. }
  47089. };
  47090. /**
  47091. * Boolean : true when the ShadowGenerator is finally computed.
  47092. */
  47093. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  47094. var defines = [];
  47095. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  47096. defines.push("#define FLOAT");
  47097. }
  47098. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47099. defines.push("#define ESM");
  47100. }
  47101. var attribs = [BABYLON.VertexBuffer.PositionKind];
  47102. var mesh = subMesh.getMesh();
  47103. var material = subMesh.getMaterial();
  47104. // Alpha test
  47105. if (material && material.needAlphaTesting()) {
  47106. var alphaTexture = material.getAlphaTestTexture();
  47107. if (alphaTexture) {
  47108. defines.push("#define ALPHATEST");
  47109. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  47110. attribs.push(BABYLON.VertexBuffer.UVKind);
  47111. defines.push("#define UV1");
  47112. }
  47113. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  47114. if (alphaTexture.coordinatesIndex === 1) {
  47115. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  47116. defines.push("#define UV2");
  47117. }
  47118. }
  47119. }
  47120. }
  47121. // Bones
  47122. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  47123. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  47124. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  47125. if (mesh.numBoneInfluencers > 4) {
  47126. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  47127. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  47128. }
  47129. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  47130. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  47131. }
  47132. else {
  47133. defines.push("#define NUM_BONE_INFLUENCERS 0");
  47134. }
  47135. // Instances
  47136. if (useInstances) {
  47137. defines.push("#define INSTANCES");
  47138. attribs.push("world0");
  47139. attribs.push("world1");
  47140. attribs.push("world2");
  47141. attribs.push("world3");
  47142. }
  47143. // Get correct effect
  47144. var join = defines.join("\n");
  47145. if (this._cachedDefines !== join) {
  47146. this._cachedDefines = join;
  47147. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightPosition", "depthValues", "biasAndScale"], ["diffuseSampler"], join);
  47148. }
  47149. return this._effect.isReady();
  47150. };
  47151. /**
  47152. * This creates the defines related to the standard BJS materials.
  47153. */
  47154. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  47155. var scene = this._scene;
  47156. var light = this._light;
  47157. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47158. return;
  47159. }
  47160. defines["SHADOW" + lightIndex] = true;
  47161. if (this.usePoissonSampling) {
  47162. defines["SHADOWPCF" + lightIndex] = true;
  47163. }
  47164. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  47165. defines["SHADOWESM" + lightIndex] = true;
  47166. }
  47167. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  47168. defines["SHADOWCLOSEESM" + lightIndex] = true;
  47169. }
  47170. if (light.needCube()) {
  47171. defines["SHADOWCUBE" + lightIndex] = true;
  47172. }
  47173. };
  47174. /**
  47175. * This binds shadow lights related to the standard BJS materials.
  47176. * It implies the unifroms available on the materials are the standard BJS ones.
  47177. */
  47178. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  47179. var light = this._light;
  47180. var scene = this._scene;
  47181. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  47182. return;
  47183. }
  47184. if (!light.needCube()) {
  47185. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  47186. }
  47187. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  47188. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / this.getShadowMap().getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  47189. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera), lightIndex);
  47190. };
  47191. // Methods
  47192. /**
  47193. * Returns a Matrix object : the updated transformation matrix.
  47194. */
  47195. ShadowGenerator.prototype.getTransformMatrix = function () {
  47196. var scene = this._scene;
  47197. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  47198. return this._transformMatrix;
  47199. }
  47200. this._currentRenderID = scene.getRenderId();
  47201. this._currentFaceIndexCache = this._currentFaceIndex;
  47202. var lightPosition = this._light.position;
  47203. if (this._light.computeTransformedInformation()) {
  47204. lightPosition = this._light.transformedPosition;
  47205. }
  47206. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  47207. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  47208. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  47209. }
  47210. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  47211. this._cachedPosition = lightPosition.clone();
  47212. this._cachedDirection = this._lightDirection.clone();
  47213. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  47214. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, this.getShadowMap().renderList);
  47215. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  47216. }
  47217. return this._transformMatrix;
  47218. };
  47219. ShadowGenerator.prototype.recreateShadowMap = function () {
  47220. // Track render list.
  47221. var renderList = this._shadowMap.renderList;
  47222. // Clean up existing data.
  47223. this._disposeRTTandPostProcesses();
  47224. // Reinitializes.
  47225. this._initializeGenerator();
  47226. // Reaffect the filter to ensure a correct fallback if necessary.
  47227. this.filter = this.filter;
  47228. // Reaffect the filter.
  47229. this._applyFilterValues();
  47230. // Reaffect Render List.
  47231. this._shadowMap.renderList = renderList;
  47232. };
  47233. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  47234. if (this._shadowMap2) {
  47235. this._shadowMap2.dispose();
  47236. this._shadowMap2 = null;
  47237. }
  47238. if (this._downSamplePostprocess) {
  47239. this._downSamplePostprocess.dispose();
  47240. this._downSamplePostprocess = null;
  47241. }
  47242. if (this._boxBlurPostprocess) {
  47243. this._boxBlurPostprocess.dispose();
  47244. this._boxBlurPostprocess = null;
  47245. }
  47246. if (this._kernelBlurXPostprocess) {
  47247. this._kernelBlurXPostprocess.dispose();
  47248. this._kernelBlurXPostprocess = null;
  47249. }
  47250. if (this._kernelBlurYPostprocess) {
  47251. this._kernelBlurYPostprocess.dispose();
  47252. this._kernelBlurYPostprocess = null;
  47253. }
  47254. this._blurPostProcesses = null;
  47255. };
  47256. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  47257. if (this._shadowMap) {
  47258. this._shadowMap.dispose();
  47259. this._shadowMap = null;
  47260. }
  47261. this._disposeBlurPostProcesses();
  47262. };
  47263. /**
  47264. * Disposes the ShadowGenerator.
  47265. * Returns nothing.
  47266. */
  47267. ShadowGenerator.prototype.dispose = function () {
  47268. this._disposeRTTandPostProcesses();
  47269. this._light._shadowGenerator = null;
  47270. this._light._markMeshesAsLightDirty();
  47271. };
  47272. /**
  47273. * Serializes the ShadowGenerator and returns a serializationObject.
  47274. */
  47275. ShadowGenerator.prototype.serialize = function () {
  47276. var serializationObject = {};
  47277. var shadowMap = this.getShadowMap();
  47278. serializationObject.lightId = this._light.id;
  47279. serializationObject.mapSize = shadowMap.getRenderSize();
  47280. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  47281. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  47282. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47283. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  47284. serializationObject.usePoissonSampling = this.usePoissonSampling;
  47285. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  47286. serializationObject.depthScale = this.depthScale;
  47287. serializationObject.darkness = this.getDarkness();
  47288. serializationObject.blurBoxOffset = this.blurBoxOffset;
  47289. serializationObject.blurKernel = this.blurKernel;
  47290. serializationObject.blurScale = this.blurScale;
  47291. serializationObject.useKernelBlur = this.useKernelBlur;
  47292. serializationObject.transparencyShadow = this._transparencyShadow;
  47293. serializationObject.renderList = [];
  47294. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  47295. var mesh = shadowMap.renderList[meshIndex];
  47296. serializationObject.renderList.push(mesh.id);
  47297. }
  47298. return serializationObject;
  47299. };
  47300. /**
  47301. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  47302. */
  47303. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  47304. //casting to point light, as light is missing the position attr and typescript complains.
  47305. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  47306. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  47307. var shadowMap = shadowGenerator.getShadowMap();
  47308. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  47309. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  47310. meshes.forEach(function (mesh) {
  47311. shadowMap.renderList.push(mesh);
  47312. });
  47313. }
  47314. if (parsedShadowGenerator.usePoissonSampling) {
  47315. shadowGenerator.usePoissonSampling = true;
  47316. }
  47317. else if (parsedShadowGenerator.useExponentialShadowMap) {
  47318. shadowGenerator.useExponentialShadowMap = true;
  47319. }
  47320. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47321. shadowGenerator.useBlurExponentialShadowMap = true;
  47322. }
  47323. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  47324. shadowGenerator.useCloseExponentialShadowMap = true;
  47325. }
  47326. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  47327. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  47328. }
  47329. else if (parsedShadowGenerator.useVarianceShadowMap) {
  47330. shadowGenerator.useExponentialShadowMap = true;
  47331. }
  47332. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  47333. shadowGenerator.useBlurExponentialShadowMap = true;
  47334. }
  47335. if (parsedShadowGenerator.depthScale) {
  47336. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  47337. }
  47338. if (parsedShadowGenerator.blurScale) {
  47339. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  47340. }
  47341. if (parsedShadowGenerator.blurBoxOffset) {
  47342. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  47343. }
  47344. if (parsedShadowGenerator.useKernelBlur) {
  47345. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  47346. }
  47347. if (parsedShadowGenerator.blurKernel) {
  47348. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  47349. }
  47350. if (parsedShadowGenerator.bias !== undefined) {
  47351. shadowGenerator.bias = parsedShadowGenerator.bias;
  47352. }
  47353. if (parsedShadowGenerator.darkness) {
  47354. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  47355. }
  47356. if (parsedShadowGenerator.transparencyShadow) {
  47357. shadowGenerator.setTransparencyShadow(true);
  47358. }
  47359. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  47360. return shadowGenerator;
  47361. };
  47362. ShadowGenerator._FILTER_NONE = 0;
  47363. ShadowGenerator._FILTER_EXPONENTIALSHADOWMAP = 1;
  47364. ShadowGenerator._FILTER_POISSONSAMPLING = 2;
  47365. ShadowGenerator._FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  47366. ShadowGenerator._FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  47367. ShadowGenerator._FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  47368. return ShadowGenerator;
  47369. }());
  47370. BABYLON.ShadowGenerator = ShadowGenerator;
  47371. })(BABYLON || (BABYLON = {}));
  47372. //# sourceMappingURL=babylon.shadowGenerator.js.map
  47373. var BABYLON;
  47374. (function (BABYLON) {
  47375. var DefaultLoadingScreen = (function () {
  47376. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  47377. if (_loadingText === void 0) { _loadingText = ""; }
  47378. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  47379. var _this = this;
  47380. this._renderingCanvas = _renderingCanvas;
  47381. this._loadingText = _loadingText;
  47382. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  47383. // Resize
  47384. this._resizeLoadingUI = function () {
  47385. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  47386. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  47387. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  47388. _this._loadingDiv.style.left = canvasRect.left + "px";
  47389. _this._loadingDiv.style.top = canvasRect.top + "px";
  47390. _this._loadingDiv.style.width = canvasRect.width + "px";
  47391. _this._loadingDiv.style.height = canvasRect.height + "px";
  47392. };
  47393. }
  47394. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  47395. if (this._loadingDiv) {
  47396. // Do not add a loading screen if there is already one
  47397. return;
  47398. }
  47399. this._loadingDiv = document.createElement("div");
  47400. this._loadingDiv.id = "babylonjsLoadingDiv";
  47401. this._loadingDiv.style.opacity = "0";
  47402. this._loadingDiv.style.transition = "opacity 1.5s ease";
  47403. // Loading text
  47404. this._loadingTextDiv = document.createElement("div");
  47405. this._loadingTextDiv.style.position = "absolute";
  47406. this._loadingTextDiv.style.left = "0";
  47407. this._loadingTextDiv.style.top = "50%";
  47408. this._loadingTextDiv.style.marginTop = "80px";
  47409. this._loadingTextDiv.style.width = "100%";
  47410. this._loadingTextDiv.style.height = "20px";
  47411. this._loadingTextDiv.style.fontFamily = "Arial";
  47412. this._loadingTextDiv.style.fontSize = "14px";
  47413. this._loadingTextDiv.style.color = "white";
  47414. this._loadingTextDiv.style.textAlign = "center";
  47415. this._loadingTextDiv.innerHTML = "Loading";
  47416. this._loadingDiv.appendChild(this._loadingTextDiv);
  47417. //set the predefined text
  47418. this._loadingTextDiv.innerHTML = this._loadingText;
  47419. // Generating keyframes
  47420. var style = document.createElement('style');
  47421. style.type = 'text/css';
  47422. var keyFrames = "@-webkit-keyframes spin1 { 0% { -webkit-transform: rotate(0deg);}\n 100% { -webkit-transform: rotate(360deg);}\n } @keyframes spin1 { 0% { transform: rotate(0deg);}\n 100% { transform: rotate(360deg);}\n }";
  47423. style.innerHTML = keyFrames;
  47424. document.getElementsByTagName('head')[0].appendChild(style);
  47425. // Loading img
  47426. var imgBack = new Image();
  47427. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZQHvphnV65cjTMzxaQY3eA5V9OO/hmnm1lSjE7woFsQbiXki4++foHnXkW4mLC1JUl947333tsMY3emqfB9jtPJlXN5U0+bOXPmWCPxgOccSy4+AfqPio+9/oFnbyatbqVE28GSZfjQ1NT0KQzaHMcdyPfyaNoE12HcvdxT29K3Fkv8A2vWrPmcifAFZNtD91yRY+SBZ+9UsMtEgD+jTpeenp6JXI6xpKkuUDqRcA6Kr0Wpens+InQTnIpV6Fdi+BQT64ulS5eOIzefD62na7CeoGcnLCM8ykt5OWlzcPv772/BS/w3nP+K+xU11+DvQe5dcrQlTfWAwbNMb8XA8AyGX80xtLlA6TAJuteMbVhhia1v5VMcr+LWMeoZ4xiYw7q6urbhHbgG+paCkIRQehHu4pO3O5fVydEomF5Ulx548JfVD2wqfKE2I3R3ob/f2GoC1DWhdz7HG3i5j2pvb9+Z24m6HvVZQtYsZFWcowlzePEP4jJdR/OQhxTVpAs9NMXxmZxuZKo8IG4s+v8R2tUFphSBTBWzH+OAFwn/gS3TuN55xYoVqfc6dXd3fwHZ1xFaTX0iyGbwjJqXXAammxP00EXx6UMGEx7ram7+vKnzBZ/87Xiwp40tEdDTgYwlHG/CmadSjO7L+XiialOZAej7POFG2VK0Khngl6Pn8/LL0YEtlFh4n8oDAqvaAYH8tzH2iNDm1IIFn8Ax50G7xtgCAU07CfAG4RHOz+vLZL7e0dGxlYlKHaj8BHo25xgrsfV5wrYH4KmouxV+ZZDnCUdwmXxMGgFvFUVWD+jQuOot6rI0tb4gcfaG9v+MrcAn+wj38gL8C7cObmlp2ZRjOkWYD6ypuAf6zjFHLSJ0c/6YQ813DM/yZXgehreiVgP8cvSfsOeExYsXuzs6n8v9j8mqBRZQmdjXVPuira1NHSpn8UDf4Xu0vd2uCtDzacJOlDDf5ng94X8JTWarB8R1EK7ju7udiYgEz/v3pLFKm4oHUHhh3iZdfshpaEYpA4pvKLLXBujLYKRq71XLhUHg27z12rW9B6L/QhLrWWxRH7nzeDK8awi/5HRTEx0K6MZQ694LHk0DqrgfADkreIYz1q5c+UlTEQzesIuMryrggYQWjNL3RGO7p2tuFMeqjaOidgzyCz1yJMTJ6L6d66WEVCcHIO/dQkI75Chs2g97Hoc3jRz9Lge1ED5l4r0gckqRPB0gTw34t1B+h3IqxZkmrn2SULUa7ezZszdE5xfR9130Xsm5ilrnHrmkQOcKvrkncxqrIiY6wlewbw7BOUfDo/b84zzvj9C7J7eCS0NrUiRKCPjUE7ScMBdlF/B2HqBi0ERXBcuXL99YnQz9fX2ah3Up4UnsWGEmDRuUhoTn+Z5PfvbZZ2N/fuCZRJgnfhNVBu73EZoIKt7l0L2UBsYeDZg016nb5EUCWuXQewinUtTuyq2aTStF14a8SD+VDQVj6hDYxjuXf4Hjl83sSMCmTp8j4FtoMuRQ5dAZcii3kk/0s2bBhxIcBxjxUlib1hWInEDO/6qKV+y4geO5HAMntEE/pq+nZyo0ywsG1SmwL4Orf+0yqGCfmvR73LAn9lAeBjQTEhkA+1h49a08iRflcq4H5iuXFU9cz4lqihC/LXS/NZa6Bc+pz5gql5ub6VXD2tZWTSPeyS7XgeLhXrMnEhj6MSHSwaIhFGZH8oA/JzzFeexvJbRN2HW03moT6cEChx6w4QY2rurn85JWrxsiCy0FwjcIqos8w7GZNPulkawDEbFHlaBtjzODEDrVztuKXMmADPWA3RaljyJeNdKq98ilAez8iJdyGqfO31V4NoV/EvyaCqR54V2EshE5Lqcb+TrkstkTLD4WKB4PNNZQ8P05HAelMXNSPWChC8JsYvwthJo0jSoF6fIqjjqe08Aat+LIkd+AVjn09zxbZFqK3tjXAUbXUaWDjTUSyN4J45YZX2Igo4cEOVfFson2ALIxSjR0jog5YNgpfNHM90BxIjDyWIB8Z2NfB01HISJ20wPaw4w1FlavXq1v8aPGXhFw9JNRFTDItifU/RwwpfmKxYsDK180kU4x0lhAXvOSJUs+bezlIDL2N4xi4GpjK4MGCuzUA+SPxzn3m4iKgKyV2DCV08DeMWg0B+zHHOt2DpjS3Mz1BfFOM25C5ZH4LxldJBB0g7GVARkaXgv8VsKqZtIMPpN9RUnJgRzU5Wfp22vifcG3+2vQvmdsdQXsX2pm+oKX+GYjjQXkPWqsXshpRhcJ0RpbGShSHiSuheP37ZYHsGusVHOrU1lMxkO9od4eE+8LlSzQqfetpnPAooBN/2Um+gISp89MkF8K4G3RrMJYoOhbYGxlQEGhSOGogfoLwipExGtUZVVBYIVAluaAaUpuWA+YujlPF22Ra/iBLYEOsV6tV4w0FiitfmLsXiBMU0NiAVrfsp77Zd8MHPgbDoHtva6uLs1jiv1piAKy5tCG+4KJ9wVO/p6RDzvy+b5rzSwP9Okh/WKPERiCWzfk4K8bUSTiOljAyCdx5DZG4gE8W5Dov+NYUfsV/j50fUC4dmXIQDh0qQ6PVgJsOcLM8oA410Ggvo6Ojr81di+g2TKuQOiyJOKWxlpCJpM5zUjKAL3awTsamQfEbYhjtDGKa5tPsyn/wAuiURftlBO56h6aunEwCMxxvV1d+2Fr7Jce2vAu5LUtLeoGi/19gtbToCaR97BoD6BvUs+WkXqgbw6OuhC6wH5l4rRGaCFOvYnjYbyxnpcsCvDVhYOxo6+zszNwSNHVTtJEmSiwzlMAQmNPwIPW42Dds2hfEK/5WJo0Fth+5VNxFHSlkoTzFRh/N3wnq0OGWxXtdoO8enFwaI4jsyidYgNZTxhrMEjEJ4w+En65ESWRXZ7Q4K/COqDAPlhka87WedB8KawmngTIHREOJs5pMiRp+p/GGgxL1FiA9hxjK6G1tVVdhJGAV15+cPXq1f7dahVC20Wg4miCp0uTe3Xh4Hwu93rY1B7SR/t7xQbP5R1FGgpy8IlKe+MJhZ9Aa7u5jPm+pGLX2BMDOZ+hDXgQiXIJ5xoXHZg96anEEFcvOTi0SMUXS4w0FijSTzTWYEA3hkTSEtDI2qw6RoytDLA6jctCvzKqJ8oPFOO7kAhnYe9cZGiWiZ/N9ezguWaSL4h3TUfvKJIfoN0I4sjigYSdZyxlcDVMgEczEY41ER6oZFBOh2Yqegf2zYoziFC3DuZZrjSTPLDtMlxaNPmPP/54W2OPxksrVozP5fLPGr8vEOpbxJCr3jQSJyDvGRNRhv7iHh8vE5LMpKznHBz4zSTOaXwe+mXGGh9tbWvVQf+iyfCAON/ZlTj4v43ECfB94Le4CuMrWVpTtw7O9fZOM5M8oD7xVSOLBdLuNWN1g7bgJUF8+4qpBjf7Te9M6hD4tBDc0289Wh2MHbuaSR7gsHOMLBaQ9W/G6o5MJrNDPu9dcYdQ33Yc95I6OFV5hnp2cGCliDingX5KU+9MShd0dmqta/k8J4zwnV2JsuuNxAnI83VwNpO52kiSoC4djA255cuXBzYPycGzjTQWkPdNY00OfRcQVLafRnd39ySLLsG1i20AyPZ3cDb7AyNJgnp1cOhUHUhcFiL045v9jTUa8Gjlm29fsQQhb3DzJLUEhC+oiK7EISPOwapoEh+7JQJti5YfGXs0YNC62ouC1h9lsrlToClsjc/RM7uSe0kd3EmlzTO/Kqk8Q106mM/Yw2aOB9jnOg6sWTHxJ9FraSJMy6nGz7RbZUDYmN7e3BnQ5Gisez7u3J9c0JwA6Pb0aCFvNObgwKk6NoU59uJwaJ8y1viAT4vCtEFXYO8SFQGtCZpllyXQtNqL+4lmZ/BN/5qJKQFZozEHe9JtAGSaw4wsFnie4JmUQcjleh8yZq0Fnmq3y0D02IzPMgnonYqYIfA4pC+TcXrgIahLB+PEb5s5HrjaR0b7kbHGB0pK7TDO1/T39x1lUZGAPlUH0xTbz+KSoC4dDDx2DQCHzTCaWOB5zjbW+KCSpW0IS0BIJmy6zWCk7WDuxZ4r5oO6dHB7e/sBZo4H2OfUsYOv9jHW+ECJdkAtA/c6MpmMd+XaEKj7km9M4F5TEfBzSKovDLKG1cHobw+b6EDa3WOksYBPAhevBUJMxl8GJTRhFyMLBKSJFn5ls9nvmogS0DfaHOzb3h8AcUuNNBLQNiWa0gRv4MwMMyBwCqxAfCIH82JdYSJKQN+ocjA5NHD2I/e1aj/23iPyhbG6A+bAgXsZoUEII/UAkkQORu71JqIE7o22HBw4VaelpWU74mPPDc/39d1trO5Qb4vJ8QXxbwat06WofcTInMCzeToAtN4VXUn/l1AXDkan9tDSfmL6C81BZooHxDkN9CMveLFZFFAWWZtDwVta3G0sJcAbe3bmYEiniShBXabcL+wflQDD5mD0yKlvk0b/Tk33AG5F7idG+/ibRe54oEl1nLG6A+ZYe1jyAIuG/u2LB3MazxwAfL5vJFGJinxQUwcju6c/n3+FNPm5JhJyy2k/sQTp5nm+2HBJCGi1X1WpwzuBoQXAN+IcjDz8mdePKi/WhH1uxd7GcCjIVBcWpUYDfZ0VbclEJSr2akMBhVrdX6j+Jx3DpSh7vKB8CIiqKwcrcXGqdr05k3RKbU9ryTQVkUB3aHMrEshw7kGCXiv8xxG0h6Uzent6Fpn6MhA17A6GT/3yTxNO1coJbgWur3JFf1fXNuTes5AZe18xXobFHJKv04JZc3O7CtIcgGL9KW03u3QCfL4D4b292dhrpoYgsYOhEz4kaOuHqXKqiagYiN9QnUlyKgX84JUYsQFP9GKzMFRSe8XJb9upE9Dn62CK/KQT75wdTLz+NXgPNdrDuYzeUd0ByN4Wp07n+EdCRZuTY1/ymZQDwIjQye9pA32xdw6IiUgHc639mN8kzCLRjkxzQRzitUpkZ8LZBP1CILUd55EVvdgsCrzJl5i8mgCja+Zgjst4Pq3DUnMmtSWqyNIuQruRU3+CbO08n+pvBAZAjf1IU5kcGJc0YRMBfVV3MPd2RN4+YbvYukI/3sSpe+LUmbw0ryG/6ts1oSLeYrMw6C0xeaFAGc+Wq3hbfeRk582b55lrzf3UHJwWkD0Wp+6BQ3+BfXEXw6UCdHX4TVB0BoJi9Y1Cp59XbUWN8HW7lRjLli3zbINE+1hNiCRI1cGakIhT99ani/A6z1z1nDoUqNQfbO40kyqDfrCBwMg3E5rsCy+8sFlHR8dEnFzRTq/I8hQ9NFFOtGhXVOxgFeUqfknUK7Ctpjl1ANKJ/vmUkvrdwRZmWjpA4J9MTyja2toKY8TQa/ufxP/Whdd5c5cQJHIwfBsTvkKiaqd6/fRyOHKqavdL0H+V2sxmWvrQCAeKItfmQlNyDG/8SVwnetMHyxmA7lm0K2I7GFrlVBW/V6FPP9GqeU4V0Kt2+O2yhctUN6AJBEWD9ngMnessJxh5AfCoQe+8q+xQOYLuWbQrQh2MXP1XYh8S9DKC2sI1z6kCatW3/RCZ6Vj9fNPMqx2wQVNJQlcNEl/mGG5pv48bi7HxMVSOoHsW7QqPg5GlvnJtk6/B9+HMqYUfaXE6rampqWy4dVhgi8FfLprnBXEex+i/wCSkNiSNDSpUxxt7Ccj2nQQYAwUHc9yE3HEotuifDklnfFYMdGNC/lWCxotDf4PvB/jHZTs71c+f2n+ryqCPPcb5/pKdGrTvbH2MUjH4ByOLBDpON9YSFi5cuI1FOwFbbyTox5T6y+iwFL8CqvWvwVtolWgSv/N4sXbl5ZP3r8hRLT50d56KgYJDCYXVhYOhtqqReKDdZuGJtSQSOk8f67x581SspvH3lpoBe9Vefbg/lzveaXmnAf6tEDMNGRp3LnV3ch29o10lQIf+bOKZc+XnmMGARF2EK4vUwQiSw33n7ZlqDWwcaK9Ob29vd26vwj+OT8m3kKFxdd9tlILSJ1Wo8Y8RZT/YiKOY4le5P3SGZJAc7telg7FroL16Jc/n/a1cBBCxsSblwT8LOfofcCh4AQ4x1uoCXZtgVKnYDXLMUECnPSQD29VBcrhfVw7GHrVXb6WylGg0SvUZcrr+YPYuwWVfaE9ltmpA2Q6EQq2UY+yigzf2oqCH4v4MIysD94fdwdig9uqDnB4T5/d+gwHPGNVFcOopyJiPLOfmGTwa0Ek8qS8RKDKORLFWH95utwbDd94SRqqN/Cv4PDXbTFfXfUZWBvRUPJCRBJiIqfnnccy0Dz74wHkWoypY2D4ZGU8gK+kKjQKQ8RcTW1uQI2fmc7nH7LIMFEW+sw6xdyN4CgvNByNIDjp+ZyRVhzlV7dVLaZc7t1cRoW0w9of/No6ptbuRdZupqC3QPZY33HchMkbJiRPssgyaHkN82XaJXPtOJuN+JRuixQI6Cu1VXiZtJehcFGpeNPyXI6cqPWTIvsxU1R7o912akevre4OHfTHot3fEfRbD3y8+Qu0djO5Ce5UXNGl7dTt4z0RGqnOuhgLZgmcPk2FHrrd3jgwkAVQ58e1ioxjcHeMLPWQcq+5gZKm9+hJHjXo5z4xQBQsxxyDjEfir+nNq5GfQo/nYh6f9e4NUgGEFx3DEzvw1nPrOhSJ+kh6GUBUHw6//Kmls96dJ2qv6FxNF9z8g405kVLVXDfkaiFAd4JIkttYUGFpyDOf91Ch/YVEe8DA/gORpuywDfLNMjBOQt4qEupbTPTX4YeJig+/qrnoxkfMeIdH2UHGBfP0H6kFepElc1rY5lBQYXZbzuO7BWYH7b3V3d/+TX1FEG/JSExEJdOi7qsnrx3DuNM8Zdg2NqnN/BjK0EXlVhxORr56wP6Lv/DT+X1FzYLynaOWe2s1TjCQW4An9t6Jk4hBVdH6YpB9YNXoS+SRk/JaQZHd5J2CnesLuyGaze3KZ2hTemoNcpO+uB3pAQuzvC7SeJSfc0258Wo97aX9PT+TmMEMB73jsO0wJzXnVx4llL7pe5kWaFtSqGHHgu6rpPr5jsdx+hyI59G+hA4C25GDO1V69mbf/77h0+lZpzZX44B+Ye1X1cWKz92pKrYlcjtzc6gfN+ufhApd/ErcwTvuTRNI0m4c4Tg77u6gfbCHdTuQcrRFaRKiFU7Xl1O/RqX9RObevRxR43gmEBYUn9wEJIMeF/jk0yVKTta2tE0jg43kx1OatWifEYKDrHYKGDnfkMrU1xHUPaoh7k8i+030EvoV3c6i4aTCoc/9+9NVkFgh6BmZFaig08he3oxYkwBEkQGCzg7gfG6kzaDvuSyLfgIyqt1cF6SAspoS4iJf3c9xaf3JrGEgUzZcOGgvO4agzjTQUkI9V5z4851MuLhBvUUp1gR7tjXEHL+shXFZnduNIBomi6T73FVLLByQePu4N3CxMbVxyzfeQUTYZrdpA3yvoPVf/1jdTGggC6aXx0ieLSecFcWoj72vkhU4IcswU7gVORksb6FHnufbouJ4Xbv+gf1g0EADav9uSeO9YenpA3IfURFVZ0gqEms1rRg0qCzM4TuYy1T061jt0dXXpX0xJ96FMDXIqQXtJ3tSfze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  47428. imgBack.style.position = "absolute";
  47429. imgBack.style.left = "50%";
  47430. imgBack.style.top = "50%";
  47431. imgBack.style.marginLeft = "-60px";
  47432. imgBack.style.marginTop = "-60px";
  47433. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  47434. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  47435. imgBack.style.transformOrigin = "50% 50%";
  47436. imgBack.style.webkitTransformOrigin = "50% 50%";
  47437. this._loadingDiv.appendChild(imgBack);
  47438. this._resizeLoadingUI();
  47439. window.addEventListener("resize", this._resizeLoadingUI);
  47440. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47441. document.body.appendChild(this._loadingDiv);
  47442. this._loadingDiv.style.opacity = "1";
  47443. };
  47444. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  47445. var _this = this;
  47446. if (!this._loadingDiv) {
  47447. return;
  47448. }
  47449. var onTransitionEnd = function () {
  47450. if (!_this._loadingDiv) {
  47451. return;
  47452. }
  47453. document.body.removeChild(_this._loadingDiv);
  47454. window.removeEventListener("resize", _this._resizeLoadingUI);
  47455. _this._loadingDiv = null;
  47456. };
  47457. this._loadingDiv.style.opacity = "0";
  47458. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  47459. };
  47460. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  47461. set: function (text) {
  47462. this._loadingText = text;
  47463. if (this._loadingTextDiv) {
  47464. this._loadingTextDiv.innerHTML = this._loadingText;
  47465. }
  47466. },
  47467. enumerable: true,
  47468. configurable: true
  47469. });
  47470. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  47471. get: function () {
  47472. return this._loadingDivBackgroundColor;
  47473. },
  47474. set: function (color) {
  47475. this._loadingDivBackgroundColor = color;
  47476. if (!this._loadingDiv) {
  47477. return;
  47478. }
  47479. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  47480. },
  47481. enumerable: true,
  47482. configurable: true
  47483. });
  47484. return DefaultLoadingScreen;
  47485. }());
  47486. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  47487. })(BABYLON || (BABYLON = {}));
  47488. //# sourceMappingURL=babylon.loadingScreen.js.map
  47489. var BABYLON;
  47490. (function (BABYLON) {
  47491. var SceneLoader = (function () {
  47492. function SceneLoader() {
  47493. }
  47494. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  47495. get: function () {
  47496. return 0;
  47497. },
  47498. enumerable: true,
  47499. configurable: true
  47500. });
  47501. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  47502. get: function () {
  47503. return 1;
  47504. },
  47505. enumerable: true,
  47506. configurable: true
  47507. });
  47508. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  47509. get: function () {
  47510. return 2;
  47511. },
  47512. enumerable: true,
  47513. configurable: true
  47514. });
  47515. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  47516. get: function () {
  47517. return 3;
  47518. },
  47519. enumerable: true,
  47520. configurable: true
  47521. });
  47522. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  47523. get: function () {
  47524. return SceneLoader._ForceFullSceneLoadingForIncremental;
  47525. },
  47526. set: function (value) {
  47527. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  47528. },
  47529. enumerable: true,
  47530. configurable: true
  47531. });
  47532. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  47533. get: function () {
  47534. return SceneLoader._ShowLoadingScreen;
  47535. },
  47536. set: function (value) {
  47537. SceneLoader._ShowLoadingScreen = value;
  47538. },
  47539. enumerable: true,
  47540. configurable: true
  47541. });
  47542. Object.defineProperty(SceneLoader, "loggingLevel", {
  47543. get: function () {
  47544. return SceneLoader._loggingLevel;
  47545. },
  47546. set: function (value) {
  47547. SceneLoader._loggingLevel = value;
  47548. },
  47549. enumerable: true,
  47550. configurable: true
  47551. });
  47552. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  47553. get: function () {
  47554. return SceneLoader._CleanBoneMatrixWeights;
  47555. },
  47556. set: function (value) {
  47557. SceneLoader._CleanBoneMatrixWeights = value;
  47558. },
  47559. enumerable: true,
  47560. configurable: true
  47561. });
  47562. SceneLoader._getDefaultPlugin = function () {
  47563. return SceneLoader._registeredPlugins[".babylon"];
  47564. };
  47565. SceneLoader._getPluginForExtension = function (extension) {
  47566. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  47567. if (registeredPlugin) {
  47568. return registeredPlugin;
  47569. }
  47570. return SceneLoader._getDefaultPlugin();
  47571. };
  47572. SceneLoader._getPluginForDirectLoad = function (data) {
  47573. for (var extension in SceneLoader._registeredPlugins) {
  47574. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  47575. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  47576. return SceneLoader._registeredPlugins[extension];
  47577. }
  47578. }
  47579. return SceneLoader._getDefaultPlugin();
  47580. };
  47581. SceneLoader._getPluginForFilename = function (sceneFilename) {
  47582. if (sceneFilename.name) {
  47583. sceneFilename = sceneFilename.name;
  47584. }
  47585. var dotPosition = sceneFilename.lastIndexOf(".");
  47586. var queryStringPosition = sceneFilename.indexOf("?");
  47587. if (queryStringPosition === -1) {
  47588. queryStringPosition = sceneFilename.length;
  47589. }
  47590. var extension = sceneFilename.substring(dotPosition, queryStringPosition).toLowerCase();
  47591. return SceneLoader._getPluginForExtension(extension);
  47592. };
  47593. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  47594. SceneLoader._getDirectLoad = function (sceneFilename) {
  47595. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  47596. return sceneFilename.substr(5);
  47597. }
  47598. return null;
  47599. };
  47600. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47601. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  47602. var registeredPlugin = directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename);
  47603. var plugin = registeredPlugin.plugin;
  47604. var useArrayBuffer = registeredPlugin.isBinary;
  47605. var database;
  47606. SceneLoader.OnPluginActivatedObservable.notifyObservers(registeredPlugin.plugin);
  47607. var dataCallback = function (data) {
  47608. if (scene.isDisposed) {
  47609. onError("Scene has been disposed");
  47610. return;
  47611. }
  47612. scene.database = database;
  47613. try {
  47614. onSuccess(plugin, data);
  47615. }
  47616. catch (e) {
  47617. onError(null, e);
  47618. }
  47619. };
  47620. var manifestChecked = function (success) {
  47621. BABYLON.Tools.LoadFile(rootUrl + sceneFilename, dataCallback, onProgress, database, useArrayBuffer, function (request) {
  47622. onError(request.status + " " + request.statusText);
  47623. });
  47624. };
  47625. if (directLoad) {
  47626. dataCallback(directLoad);
  47627. return;
  47628. }
  47629. if (rootUrl.indexOf("file:") === -1) {
  47630. if (scene.getEngine().enableOfflineSupport) {
  47631. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  47632. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked);
  47633. }
  47634. else {
  47635. manifestChecked(true);
  47636. }
  47637. }
  47638. else {
  47639. BABYLON.Tools.ReadFile(sceneFilename, dataCallback, onProgress, useArrayBuffer);
  47640. }
  47641. };
  47642. // Public functions
  47643. SceneLoader.GetPluginForExtension = function (extension) {
  47644. return SceneLoader._getPluginForExtension(extension).plugin;
  47645. };
  47646. SceneLoader.RegisterPlugin = function (plugin) {
  47647. if (typeof plugin.extensions === "string") {
  47648. var extension = plugin.extensions;
  47649. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47650. plugin: plugin,
  47651. isBinary: false
  47652. };
  47653. }
  47654. else {
  47655. var extensions = plugin.extensions;
  47656. Object.keys(extensions).forEach(function (extension) {
  47657. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  47658. plugin: plugin,
  47659. isBinary: extensions[extension].isBinary
  47660. };
  47661. });
  47662. }
  47663. };
  47664. /**
  47665. * Import meshes into a scene
  47666. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  47667. * @param rootUrl a string that defines the root url for scene and resources
  47668. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47669. * @param scene the instance of BABYLON.Scene to append to
  47670. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  47671. * @param onProgress a callback with a progress event for each file being loaded
  47672. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47673. */
  47674. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47675. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47676. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47677. return;
  47678. }
  47679. var loadingToken = {};
  47680. scene._addPendingData(loadingToken);
  47681. var errorHandler = function (message, exception) {
  47682. if (onError) {
  47683. onError(scene, "Unable to import meshes from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47684. }
  47685. scene._removePendingData(loadingToken);
  47686. };
  47687. var progressHandler = function (event) {
  47688. if (onProgress) {
  47689. onProgress(event);
  47690. }
  47691. };
  47692. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47693. if (plugin.importMesh) {
  47694. var syncedPlugin = plugin;
  47695. var meshes = [];
  47696. var particleSystems = [];
  47697. var skeletons = [];
  47698. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  47699. return;
  47700. }
  47701. if (onSuccess) {
  47702. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47703. onSuccess(meshes, particleSystems, skeletons);
  47704. scene._removePendingData(loadingToken);
  47705. }
  47706. }
  47707. else {
  47708. var asyncedPlugin = plugin;
  47709. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, function (meshes, particleSystems, skeletons) {
  47710. if (onSuccess) {
  47711. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  47712. onSuccess(meshes, particleSystems, skeletons);
  47713. scene._removePendingData(loadingToken);
  47714. }
  47715. }, progressHandler, errorHandler);
  47716. }
  47717. }, progressHandler, errorHandler);
  47718. };
  47719. /**
  47720. * Load a scene
  47721. * @param rootUrl a string that defines the root url for scene and resources
  47722. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47723. * @param engine is the instance of BABYLON.Engine to use to create the scene
  47724. * @param onSuccess a callback with the scene when import succeeds
  47725. * @param onProgress a callback with a progress event for each file being loaded
  47726. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47727. */
  47728. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError) {
  47729. SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError);
  47730. };
  47731. /**
  47732. * Append a scene
  47733. * @param rootUrl a string that defines the root url for scene and resources
  47734. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  47735. * @param scene is the instance of BABYLON.Scene to append to
  47736. * @param onSuccess a callback with the scene when import succeeds
  47737. * @param onProgress a callback with a progress event for each file being loaded
  47738. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  47739. */
  47740. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError) {
  47741. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  47742. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  47743. return;
  47744. }
  47745. if (SceneLoader.ShowLoadingScreen) {
  47746. scene.getEngine().displayLoadingUI();
  47747. }
  47748. var loadingToken = {};
  47749. scene._addPendingData(loadingToken);
  47750. var errorHandler = function (message, exception) {
  47751. if (onError) {
  47752. onError(scene, "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : ""));
  47753. }
  47754. scene._removePendingData(loadingToken);
  47755. scene.getEngine().hideLoadingUI();
  47756. };
  47757. var progressHandler = function (event) {
  47758. if (onProgress) {
  47759. onProgress(event);
  47760. }
  47761. };
  47762. SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data) {
  47763. if (plugin.load) {
  47764. var syncedPlugin = plugin;
  47765. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  47766. return;
  47767. }
  47768. if (onSuccess) {
  47769. onSuccess(scene);
  47770. }
  47771. scene.loadingPluginName = plugin.name;
  47772. scene._removePendingData(loadingToken);
  47773. }
  47774. else {
  47775. var asyncedPlugin = plugin;
  47776. asyncedPlugin.loadAsync(scene, data, rootUrl, function () {
  47777. if (onSuccess) {
  47778. onSuccess(scene);
  47779. }
  47780. scene.loadingPluginName = plugin.name;
  47781. scene._removePendingData(loadingToken);
  47782. }, progressHandler, errorHandler);
  47783. }
  47784. if (SceneLoader.ShowLoadingScreen) {
  47785. scene.executeWhenReady(function () {
  47786. scene.getEngine().hideLoadingUI();
  47787. });
  47788. }
  47789. }, progressHandler, errorHandler);
  47790. };
  47791. // Flags
  47792. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  47793. SceneLoader._ShowLoadingScreen = true;
  47794. SceneLoader._CleanBoneMatrixWeights = false;
  47795. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  47796. // Members
  47797. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  47798. SceneLoader._registeredPlugins = {};
  47799. return SceneLoader;
  47800. }());
  47801. BABYLON.SceneLoader = SceneLoader;
  47802. ;
  47803. })(BABYLON || (BABYLON = {}));
  47804. //# sourceMappingURL=babylon.sceneLoader.js.map
  47805. var BABYLON;
  47806. (function (BABYLON) {
  47807. var Internals;
  47808. (function (Internals) {
  47809. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  47810. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  47811. var parsedMaterial = parsedData.materials[index];
  47812. if (parsedMaterial.id === id) {
  47813. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  47814. }
  47815. }
  47816. return null;
  47817. };
  47818. var isDescendantOf = function (mesh, names, hierarchyIds) {
  47819. for (var i in names) {
  47820. if (mesh.name === names[i]) {
  47821. hierarchyIds.push(mesh.id);
  47822. return true;
  47823. }
  47824. }
  47825. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  47826. hierarchyIds.push(mesh.id);
  47827. return true;
  47828. }
  47829. return false;
  47830. };
  47831. var logOperation = function (operation, producer) {
  47832. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  47833. };
  47834. BABYLON.SceneLoader.RegisterPlugin({
  47835. name: "babylon.js",
  47836. extensions: ".babylon",
  47837. canDirectLoad: function (data) {
  47838. if (data.indexOf("babylon") !== -1) {
  47839. return true;
  47840. }
  47841. return false;
  47842. },
  47843. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  47844. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  47845. // when SceneLoader.debugLogging = true (default), or exception encountered.
  47846. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  47847. // and avoid problems with multiple concurrent .babylon loads.
  47848. var log = "importMesh has failed JSON parse";
  47849. try {
  47850. var parsedData = JSON.parse(data);
  47851. log = "";
  47852. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  47853. if (!meshesNames) {
  47854. meshesNames = null;
  47855. }
  47856. else if (!Array.isArray(meshesNames)) {
  47857. meshesNames = [meshesNames];
  47858. }
  47859. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  47860. var loadedSkeletonsIds = [];
  47861. var loadedMaterialsIds = [];
  47862. var hierarchyIds = [];
  47863. var index;
  47864. var cache;
  47865. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  47866. var parsedMesh = parsedData.meshes[index];
  47867. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  47868. if (meshesNames !== null) {
  47869. // Remove found mesh name from list.
  47870. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  47871. }
  47872. //Geometry?
  47873. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  47874. //does the file contain geometries?
  47875. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  47876. //find the correct geometry and add it to the scene
  47877. var found = false;
  47878. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  47879. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  47880. return;
  47881. }
  47882. else {
  47883. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  47884. if (parsedGeometryData.id === parsedMesh.geometryId) {
  47885. switch (geometryType) {
  47886. case "boxes":
  47887. BABYLON.Geometry.Primitives.Box.Parse(parsedGeometryData, scene);
  47888. break;
  47889. case "spheres":
  47890. BABYLON.Geometry.Primitives.Sphere.Parse(parsedGeometryData, scene);
  47891. break;
  47892. case "cylinders":
  47893. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedGeometryData, scene);
  47894. break;
  47895. case "toruses":
  47896. BABYLON.Geometry.Primitives.Torus.Parse(parsedGeometryData, scene);
  47897. break;
  47898. case "grounds":
  47899. BABYLON.Geometry.Primitives.Ground.Parse(parsedGeometryData, scene);
  47900. break;
  47901. case "planes":
  47902. BABYLON.Geometry.Primitives.Plane.Parse(parsedGeometryData, scene);
  47903. break;
  47904. case "torusKnots":
  47905. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedGeometryData, scene);
  47906. break;
  47907. case "vertexData":
  47908. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  47909. break;
  47910. }
  47911. found = true;
  47912. }
  47913. });
  47914. }
  47915. });
  47916. if (found === false) {
  47917. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  47918. }
  47919. }
  47920. }
  47921. // Material ?
  47922. if (parsedMesh.materialId) {
  47923. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  47924. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  47925. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  47926. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  47927. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  47928. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  47929. var subMatId = parsedMultiMaterial.materials[matIndex];
  47930. loadedMaterialsIds.push(subMatId);
  47931. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  47932. log += "\n\tMaterial " + mat.toString(fullDetails);
  47933. }
  47934. loadedMaterialsIds.push(parsedMultiMaterial.id);
  47935. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  47936. materialFound = true;
  47937. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  47938. break;
  47939. }
  47940. }
  47941. }
  47942. if (materialFound === false) {
  47943. loadedMaterialsIds.push(parsedMesh.materialId);
  47944. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  47945. if (!mat) {
  47946. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  47947. }
  47948. else {
  47949. log += "\n\tMaterial " + mat.toString(fullDetails);
  47950. }
  47951. }
  47952. }
  47953. // Skeleton ?
  47954. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  47955. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  47956. if (skeletonAlreadyLoaded === false) {
  47957. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  47958. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  47959. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  47960. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  47961. skeletons.push(skeleton);
  47962. loadedSkeletonsIds.push(parsedSkeleton.id);
  47963. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  47964. }
  47965. }
  47966. }
  47967. }
  47968. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  47969. meshes.push(mesh);
  47970. log += "\n\tMesh " + mesh.toString(fullDetails);
  47971. }
  47972. }
  47973. // Connecting parents
  47974. var currentMesh;
  47975. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47976. currentMesh = scene.meshes[index];
  47977. if (currentMesh._waitingParentId) {
  47978. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  47979. currentMesh._waitingParentId = undefined;
  47980. }
  47981. }
  47982. // freeze and compute world matrix application
  47983. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  47984. currentMesh = scene.meshes[index];
  47985. if (currentMesh._waitingFreezeWorldMatrix) {
  47986. currentMesh.freezeWorldMatrix();
  47987. currentMesh._waitingFreezeWorldMatrix = undefined;
  47988. }
  47989. else {
  47990. currentMesh.computeWorldMatrix(true);
  47991. }
  47992. }
  47993. }
  47994. // Particles
  47995. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  47996. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  47997. var parsedParticleSystem = parsedData.particleSystems[index];
  47998. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  47999. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  48000. }
  48001. }
  48002. }
  48003. return true;
  48004. }
  48005. catch (err) {
  48006. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log);
  48007. log = null;
  48008. throw err;
  48009. }
  48010. finally {
  48011. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48012. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48013. }
  48014. }
  48015. },
  48016. load: function (scene, data, rootUrl) {
  48017. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  48018. // when SceneLoader.debugLogging = true (default), or exception encountered.
  48019. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  48020. // and avoid problems with multiple concurrent .babylon loads.
  48021. var log = "importScene has failed JSON parse";
  48022. try {
  48023. var parsedData = JSON.parse(data);
  48024. log = "";
  48025. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  48026. // Scene
  48027. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  48028. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  48029. }
  48030. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  48031. scene.autoClear = parsedData.autoClear;
  48032. }
  48033. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  48034. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  48035. }
  48036. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  48037. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  48038. }
  48039. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  48040. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  48041. }
  48042. // Fog
  48043. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  48044. scene.fogMode = parsedData.fogMode;
  48045. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  48046. scene.fogStart = parsedData.fogStart;
  48047. scene.fogEnd = parsedData.fogEnd;
  48048. scene.fogDensity = parsedData.fogDensity;
  48049. log += "\tFog mode for scene: ";
  48050. switch (scene.fogMode) {
  48051. // getters not compiling, so using hardcoded
  48052. case 1:
  48053. log += "exp\n";
  48054. break;
  48055. case 2:
  48056. log += "exp2\n";
  48057. break;
  48058. case 3:
  48059. log += "linear\n";
  48060. break;
  48061. }
  48062. }
  48063. //Physics
  48064. if (parsedData.physicsEnabled) {
  48065. var physicsPlugin;
  48066. if (parsedData.physicsEngine === "cannon") {
  48067. physicsPlugin = new BABYLON.CannonJSPlugin();
  48068. }
  48069. else if (parsedData.physicsEngine === "oimo") {
  48070. physicsPlugin = new BABYLON.OimoJSPlugin();
  48071. }
  48072. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  48073. //else - default engine, which is currently oimo
  48074. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  48075. scene.enablePhysics(physicsGravity, physicsPlugin);
  48076. }
  48077. // Metadata
  48078. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  48079. scene.metadata = parsedData.metadata;
  48080. }
  48081. //collisions, if defined. otherwise, default is true
  48082. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  48083. scene.collisionsEnabled = parsedData.collisionsEnabled;
  48084. }
  48085. scene.workerCollisions = !!parsedData.workerCollisions;
  48086. var index;
  48087. var cache;
  48088. // Lights
  48089. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  48090. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  48091. var parsedLight = parsedData.lights[index];
  48092. var light = BABYLON.Light.Parse(parsedLight, scene);
  48093. log += (index === 0 ? "\n\tLights:" : "");
  48094. log += "\n\t\t" + light.toString(fullDetails);
  48095. }
  48096. }
  48097. // Animations
  48098. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  48099. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  48100. var parsedAnimation = parsedData.animations[index];
  48101. var animation = BABYLON.Animation.Parse(parsedAnimation);
  48102. scene.animations.push(animation);
  48103. log += (index === 0 ? "\n\tAnimations:" : "");
  48104. log += "\n\t\t" + animation.toString(fullDetails);
  48105. }
  48106. }
  48107. if (parsedData.autoAnimate) {
  48108. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  48109. }
  48110. // Materials
  48111. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  48112. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  48113. var parsedMaterial = parsedData.materials[index];
  48114. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  48115. log += (index === 0 ? "\n\tMaterials:" : "");
  48116. log += "\n\t\t" + mat.toString(fullDetails);
  48117. }
  48118. }
  48119. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  48120. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  48121. var parsedMultiMaterial = parsedData.multiMaterials[index];
  48122. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  48123. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  48124. log += "\n\t\t" + mmat.toString(fullDetails);
  48125. }
  48126. }
  48127. // Morph targets
  48128. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  48129. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  48130. var managerData = _a[_i];
  48131. var parsedManager = BABYLON.MorphTargetManager.Parse(managerData, scene);
  48132. }
  48133. }
  48134. // Skeletons
  48135. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  48136. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  48137. var parsedSkeleton = parsedData.skeletons[index];
  48138. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  48139. log += (index === 0 ? "\n\tSkeletons:" : "");
  48140. log += "\n\t\t" + skeleton.toString(fullDetails);
  48141. }
  48142. }
  48143. // Geometries
  48144. var geometries = parsedData.geometries;
  48145. if (geometries !== undefined && geometries !== null) {
  48146. // Boxes
  48147. var boxes = geometries.boxes;
  48148. if (boxes !== undefined && boxes !== null) {
  48149. for (index = 0, cache = boxes.length; index < cache; index++) {
  48150. var parsedBox = boxes[index];
  48151. BABYLON.Geometry.Primitives.Box.Parse(parsedBox, scene);
  48152. }
  48153. }
  48154. // Spheres
  48155. var spheres = geometries.spheres;
  48156. if (spheres !== undefined && spheres !== null) {
  48157. for (index = 0, cache = spheres.length; index < cache; index++) {
  48158. var parsedSphere = spheres[index];
  48159. BABYLON.Geometry.Primitives.Sphere.Parse(parsedSphere, scene);
  48160. }
  48161. }
  48162. // Cylinders
  48163. var cylinders = geometries.cylinders;
  48164. if (cylinders !== undefined && cylinders !== null) {
  48165. for (index = 0, cache = cylinders.length; index < cache; index++) {
  48166. var parsedCylinder = cylinders[index];
  48167. BABYLON.Geometry.Primitives.Cylinder.Parse(parsedCylinder, scene);
  48168. }
  48169. }
  48170. // Toruses
  48171. var toruses = geometries.toruses;
  48172. if (toruses !== undefined && toruses !== null) {
  48173. for (index = 0, cache = toruses.length; index < cache; index++) {
  48174. var parsedTorus = toruses[index];
  48175. BABYLON.Geometry.Primitives.Torus.Parse(parsedTorus, scene);
  48176. }
  48177. }
  48178. // Grounds
  48179. var grounds = geometries.grounds;
  48180. if (grounds !== undefined && grounds !== null) {
  48181. for (index = 0, cache = grounds.length; index < cache; index++) {
  48182. var parsedGround = grounds[index];
  48183. BABYLON.Geometry.Primitives.Ground.Parse(parsedGround, scene);
  48184. }
  48185. }
  48186. // Planes
  48187. var planes = geometries.planes;
  48188. if (planes !== undefined && planes !== null) {
  48189. for (index = 0, cache = planes.length; index < cache; index++) {
  48190. var parsedPlane = planes[index];
  48191. BABYLON.Geometry.Primitives.Plane.Parse(parsedPlane, scene);
  48192. }
  48193. }
  48194. // TorusKnots
  48195. var torusKnots = geometries.torusKnots;
  48196. if (torusKnots !== undefined && torusKnots !== null) {
  48197. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  48198. var parsedTorusKnot = torusKnots[index];
  48199. BABYLON.Geometry.Primitives.TorusKnot.Parse(parsedTorusKnot, scene);
  48200. }
  48201. }
  48202. // VertexData
  48203. var vertexData = geometries.vertexData;
  48204. if (vertexData !== undefined && vertexData !== null) {
  48205. for (index = 0, cache = vertexData.length; index < cache; index++) {
  48206. var parsedVertexData = vertexData[index];
  48207. BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl);
  48208. }
  48209. }
  48210. }
  48211. // Meshes
  48212. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  48213. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  48214. var parsedMesh = parsedData.meshes[index];
  48215. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  48216. log += (index === 0 ? "\n\tMeshes:" : "");
  48217. log += "\n\t\t" + mesh.toString(fullDetails);
  48218. }
  48219. }
  48220. // Cameras
  48221. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  48222. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  48223. var parsedCamera = parsedData.cameras[index];
  48224. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  48225. log += (index === 0 ? "\n\tCameras:" : "");
  48226. log += "\n\t\t" + camera.toString(fullDetails);
  48227. }
  48228. }
  48229. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  48230. scene.setActiveCameraByID(parsedData.activeCameraID);
  48231. }
  48232. // Browsing all the graph to connect the dots
  48233. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  48234. var camera = scene.cameras[index];
  48235. if (camera._waitingParentId) {
  48236. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  48237. camera._waitingParentId = undefined;
  48238. }
  48239. }
  48240. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48241. var light = scene.lights[index];
  48242. if (light._waitingParentId) {
  48243. light.parent = scene.getLastEntryByID(light._waitingParentId);
  48244. light._waitingParentId = undefined;
  48245. }
  48246. }
  48247. // Sounds
  48248. var loadedSounds = [];
  48249. var loadedSound;
  48250. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  48251. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  48252. var parsedSound = parsedData.sounds[index];
  48253. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  48254. if (!parsedSound.url)
  48255. parsedSound.url = parsedSound.name;
  48256. if (!loadedSounds[parsedSound.url]) {
  48257. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  48258. loadedSounds[parsedSound.url] = loadedSound;
  48259. }
  48260. else {
  48261. BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]);
  48262. }
  48263. }
  48264. else {
  48265. var emptySound = new BABYLON.Sound(parsedSound.name, null, scene);
  48266. }
  48267. }
  48268. }
  48269. loadedSounds = [];
  48270. // Connect parents & children and parse actions
  48271. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48272. var mesh = scene.meshes[index];
  48273. if (mesh._waitingParentId) {
  48274. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  48275. mesh._waitingParentId = undefined;
  48276. }
  48277. if (mesh._waitingActions) {
  48278. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  48279. mesh._waitingActions = undefined;
  48280. }
  48281. }
  48282. // freeze world matrix application
  48283. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  48284. var currentMesh = scene.meshes[index];
  48285. if (currentMesh._waitingFreezeWorldMatrix) {
  48286. currentMesh.freezeWorldMatrix();
  48287. currentMesh._waitingFreezeWorldMatrix = undefined;
  48288. }
  48289. else {
  48290. currentMesh.computeWorldMatrix(true);
  48291. }
  48292. }
  48293. // Particles Systems
  48294. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  48295. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  48296. var parsedParticleSystem = parsedData.particleSystems[index];
  48297. BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  48298. }
  48299. }
  48300. // Lens flares
  48301. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  48302. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  48303. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  48304. BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  48305. }
  48306. }
  48307. // Shadows
  48308. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  48309. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  48310. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  48311. BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  48312. }
  48313. }
  48314. // Lights exclusions / inclusions
  48315. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  48316. var light = scene.lights[index];
  48317. // Excluded check
  48318. if (light._excludedMeshesIds.length > 0) {
  48319. for (var excludedIndex = 0; excludedIndex < light._excludedMeshesIds.length; excludedIndex++) {
  48320. var excludedMesh = scene.getMeshByID(light._excludedMeshesIds[excludedIndex]);
  48321. if (excludedMesh) {
  48322. light.excludedMeshes.push(excludedMesh);
  48323. }
  48324. }
  48325. light._excludedMeshesIds = [];
  48326. }
  48327. // Included check
  48328. if (light._includedOnlyMeshesIds.length > 0) {
  48329. for (var includedOnlyIndex = 0; includedOnlyIndex < light._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  48330. var includedOnlyMesh = scene.getMeshByID(light._includedOnlyMeshesIds[includedOnlyIndex]);
  48331. if (includedOnlyMesh) {
  48332. light.includedOnlyMeshes.push(includedOnlyMesh);
  48333. }
  48334. }
  48335. light._includedOnlyMeshesIds = [];
  48336. }
  48337. }
  48338. // Actions (scene)
  48339. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  48340. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  48341. }
  48342. // Finish
  48343. return true;
  48344. }
  48345. catch (err) {
  48346. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log);
  48347. log = null;
  48348. throw err;
  48349. }
  48350. finally {
  48351. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  48352. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  48353. }
  48354. }
  48355. }
  48356. });
  48357. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48358. })(BABYLON || (BABYLON = {}));
  48359. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  48360. var BABYLON;
  48361. (function (BABYLON) {
  48362. var FilesInput = (function () {
  48363. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback) {
  48364. this._engine = engine;
  48365. this._currentScene = scene;
  48366. this._sceneLoadedCallback = sceneLoadedCallback;
  48367. this._progressCallback = progressCallback;
  48368. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  48369. this._textureLoadingCallback = textureLoadingCallback;
  48370. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  48371. this._onReloadCallback = onReloadCallback;
  48372. }
  48373. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  48374. var _this = this;
  48375. if (elementToMonitor) {
  48376. this._elementToMonitor = elementToMonitor;
  48377. this._dragEnterHandler = function (e) { _this.drag(e); };
  48378. this._dragOverHandler = function (e) { _this.drag(e); };
  48379. this._dropHandler = function (e) { _this.drop(e); };
  48380. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  48381. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  48382. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  48383. }
  48384. };
  48385. FilesInput.prototype.dispose = function () {
  48386. if (!this._elementToMonitor) {
  48387. return;
  48388. }
  48389. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  48390. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  48391. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  48392. };
  48393. FilesInput.prototype.renderFunction = function () {
  48394. if (this._additionalRenderLoopLogicCallback) {
  48395. this._additionalRenderLoopLogicCallback();
  48396. }
  48397. if (this._currentScene) {
  48398. if (this._textureLoadingCallback) {
  48399. var remaining = this._currentScene.getWaitingItemsCount();
  48400. if (remaining > 0) {
  48401. this._textureLoadingCallback(remaining);
  48402. }
  48403. }
  48404. this._currentScene.render();
  48405. }
  48406. };
  48407. FilesInput.prototype.drag = function (e) {
  48408. e.stopPropagation();
  48409. e.preventDefault();
  48410. };
  48411. FilesInput.prototype.drop = function (eventDrop) {
  48412. eventDrop.stopPropagation();
  48413. eventDrop.preventDefault();
  48414. this.loadFiles(eventDrop);
  48415. };
  48416. FilesInput.prototype._handleFolderDrop = function (entry, files, callback) {
  48417. var reader = entry.createReader(), relativePath = entry.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  48418. reader.readEntries(function (fileEntries) {
  48419. var remaining = fileEntries.length;
  48420. for (var _i = 0, fileEntries_1 = fileEntries; _i < fileEntries_1.length; _i++) {
  48421. var fileEntry = fileEntries_1[_i];
  48422. if (fileEntry.isFile) {
  48423. fileEntry.file(function (file) {
  48424. file.correctName = relativePath + file.name;
  48425. files.push(file);
  48426. remaining--;
  48427. if (remaining === 0) {
  48428. callback();
  48429. }
  48430. });
  48431. }
  48432. else {
  48433. remaining--;
  48434. if (remaining === 0) {
  48435. callback();
  48436. }
  48437. }
  48438. }
  48439. });
  48440. };
  48441. FilesInput.prototype._processFiles = function (files) {
  48442. for (var i = 0; i < files.length; i++) {
  48443. var name = files[i].correctName.toLowerCase();
  48444. var extension = name.split('.').pop();
  48445. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  48446. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  48447. this._sceneFileToLoad = files[i];
  48448. }
  48449. else {
  48450. FilesInput.FilesToLoad[name] = files[i];
  48451. }
  48452. }
  48453. if (this._onReloadCallback) {
  48454. this._onReloadCallback(this._sceneFileToLoad);
  48455. }
  48456. else {
  48457. this.reload();
  48458. }
  48459. };
  48460. FilesInput.prototype.loadFiles = function (event) {
  48461. var _this = this;
  48462. if (this._startingProcessingFilesCallback)
  48463. this._startingProcessingFilesCallback();
  48464. // Handling data transfer via drag'n'drop
  48465. if (event && event.dataTransfer && event.dataTransfer.files) {
  48466. this._filesToLoad = event.dataTransfer.files;
  48467. }
  48468. // Handling files from input files
  48469. if (event && event.target && event.target.files) {
  48470. this._filesToLoad = event.target.files;
  48471. }
  48472. if (this._filesToLoad && this._filesToLoad.length > 0) {
  48473. var files_1 = [];
  48474. var folders = [];
  48475. var items = event.dataTransfer ? event.dataTransfer.items : null;
  48476. for (var i = 0; i < this._filesToLoad.length; i++) {
  48477. var fileToLoad = this._filesToLoad[i];
  48478. var name_1 = fileToLoad.name.toLowerCase();
  48479. var type = fileToLoad.type;
  48480. var entry = void 0;
  48481. fileToLoad.correctName = name_1;
  48482. if (items) {
  48483. var item = items[i];
  48484. if (item.getAsEntry) {
  48485. entry = item.getAsEntry();
  48486. }
  48487. else if (item.webkitGetAsEntry) {
  48488. entry = item.webkitGetAsEntry();
  48489. }
  48490. }
  48491. if (!entry) {
  48492. files_1.push(fileToLoad);
  48493. }
  48494. else {
  48495. if (entry.isDirectory) {
  48496. folders.push(entry);
  48497. }
  48498. else {
  48499. files_1.push(fileToLoad);
  48500. }
  48501. }
  48502. }
  48503. if (folders.length === 0) {
  48504. this._processFiles(files_1);
  48505. }
  48506. else {
  48507. var remaining = folders.length;
  48508. // Extract folder content
  48509. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  48510. var folder = folders_1[_i];
  48511. this._handleFolderDrop(folder, files_1, function () {
  48512. remaining--;
  48513. if (remaining === 0) {
  48514. _this._processFiles(files_1);
  48515. }
  48516. });
  48517. }
  48518. }
  48519. }
  48520. };
  48521. FilesInput.prototype.reload = function () {
  48522. var _this = this;
  48523. // If a ".babylon" file has been provided
  48524. if (this._sceneFileToLoad) {
  48525. if (this._currentScene) {
  48526. if (BABYLON.Tools.errorsCount > 0) {
  48527. BABYLON.Tools.ClearLogCache();
  48528. BABYLON.Tools.Log("Babylon.js engine (v" + BABYLON.Engine.Version + ") launched");
  48529. }
  48530. this._engine.stopRenderLoop();
  48531. this._currentScene.dispose();
  48532. }
  48533. BABYLON.SceneLoader.Load("file:", this._sceneFileToLoad, this._engine, function (newScene) {
  48534. _this._currentScene = newScene;
  48535. if (_this._sceneLoadedCallback) {
  48536. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  48537. }
  48538. // Wait for textures and shaders to be ready
  48539. _this._currentScene.executeWhenReady(function () {
  48540. _this._engine.runRenderLoop(function () {
  48541. _this.renderFunction();
  48542. });
  48543. });
  48544. }, function (progress) {
  48545. if (_this._progressCallback) {
  48546. _this._progressCallback(progress);
  48547. }
  48548. });
  48549. }
  48550. else {
  48551. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  48552. }
  48553. };
  48554. FilesInput.FilesToLoad = new Array();
  48555. return FilesInput;
  48556. }());
  48557. BABYLON.FilesInput = FilesInput;
  48558. })(BABYLON || (BABYLON = {}));
  48559. //# sourceMappingURL=babylon.filesInput.js.map
  48560. var BABYLON;
  48561. (function (BABYLON) {
  48562. /**
  48563. * This class implement a typical dictionary using a string as key and the generic type T as value.
  48564. * The underlying implementation relies on an associative array to ensure the best performances.
  48565. * The value can be anything including 'null' but except 'undefined'
  48566. */
  48567. var StringDictionary = (function () {
  48568. function StringDictionary() {
  48569. this._count = 0;
  48570. this._data = {};
  48571. }
  48572. /**
  48573. * This will clear this dictionary and copy the content from the 'source' one.
  48574. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  48575. * @param source the dictionary to take the content from and copy to this dictionary
  48576. */
  48577. StringDictionary.prototype.copyFrom = function (source) {
  48578. var _this = this;
  48579. this.clear();
  48580. source.forEach(function (t, v) { return _this.add(t, v); });
  48581. };
  48582. /**
  48583. * Get a value based from its key
  48584. * @param key the given key to get the matching value from
  48585. * @return the value if found, otherwise undefined is returned
  48586. */
  48587. StringDictionary.prototype.get = function (key) {
  48588. var val = this._data[key];
  48589. if (val !== undefined) {
  48590. return val;
  48591. }
  48592. return undefined;
  48593. };
  48594. /**
  48595. * Get a value from its key or add it if it doesn't exist.
  48596. * This method will ensure you that a given key/data will be present in the dictionary.
  48597. * @param key the given key to get the matching value from
  48598. * @param factory the factory that will create the value if the key is not present in the dictionary.
  48599. * The factory will only be invoked if there's no data for the given key.
  48600. * @return the value corresponding to the key.
  48601. */
  48602. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  48603. var val = this.get(key);
  48604. if (val !== undefined) {
  48605. return val;
  48606. }
  48607. val = factory(key);
  48608. if (val) {
  48609. this.add(key, val);
  48610. }
  48611. return val;
  48612. };
  48613. /**
  48614. * Get a value from its key if present in the dictionary otherwise add it
  48615. * @param key the key to get the value from
  48616. * @param val if there's no such key/value pair in the dictionary add it with this value
  48617. * @return the value corresponding to the key
  48618. */
  48619. StringDictionary.prototype.getOrAdd = function (key, val) {
  48620. var curVal = this.get(key);
  48621. if (curVal !== undefined) {
  48622. return curVal;
  48623. }
  48624. this.add(key, val);
  48625. return val;
  48626. };
  48627. /**
  48628. * Check if there's a given key in the dictionary
  48629. * @param key the key to check for
  48630. * @return true if the key is present, false otherwise
  48631. */
  48632. StringDictionary.prototype.contains = function (key) {
  48633. return this._data[key] !== undefined;
  48634. };
  48635. /**
  48636. * Add a new key and its corresponding value
  48637. * @param key the key to add
  48638. * @param value the value corresponding to the key
  48639. * @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
  48640. */
  48641. StringDictionary.prototype.add = function (key, value) {
  48642. if (this._data[key] !== undefined) {
  48643. return false;
  48644. }
  48645. this._data[key] = value;
  48646. ++this._count;
  48647. return true;
  48648. };
  48649. StringDictionary.prototype.set = function (key, value) {
  48650. if (this._data[key] === undefined) {
  48651. return false;
  48652. }
  48653. this._data[key] = value;
  48654. return true;
  48655. };
  48656. /**
  48657. * Get the element of the given key and remove it from the dictionary
  48658. * @param key
  48659. */
  48660. StringDictionary.prototype.getAndRemove = function (key) {
  48661. var val = this.get(key);
  48662. if (val !== undefined) {
  48663. delete this._data[key];
  48664. --this._count;
  48665. return val;
  48666. }
  48667. return null;
  48668. };
  48669. /**
  48670. * Remove a key/value from the dictionary.
  48671. * @param key the key to remove
  48672. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  48673. */
  48674. StringDictionary.prototype.remove = function (key) {
  48675. if (this.contains(key)) {
  48676. delete this._data[key];
  48677. --this._count;
  48678. return true;
  48679. }
  48680. return false;
  48681. };
  48682. /**
  48683. * Clear the whole content of the dictionary
  48684. */
  48685. StringDictionary.prototype.clear = function () {
  48686. this._data = {};
  48687. this._count = 0;
  48688. };
  48689. Object.defineProperty(StringDictionary.prototype, "count", {
  48690. get: function () {
  48691. return this._count;
  48692. },
  48693. enumerable: true,
  48694. configurable: true
  48695. });
  48696. /**
  48697. * Execute a callback on each key/val of the dictionary.
  48698. * Note that you can remove any element in this dictionary in the callback implementation
  48699. * @param callback the callback to execute on a given key/value pair
  48700. */
  48701. StringDictionary.prototype.forEach = function (callback) {
  48702. for (var cur in this._data) {
  48703. var val = this._data[cur];
  48704. callback(cur, val);
  48705. }
  48706. };
  48707. /**
  48708. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  48709. * If the callback returns null or undefined the method will iterate to the next key/value pair
  48710. * Note that you can remove any element in this dictionary in the callback implementation
  48711. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  48712. */
  48713. StringDictionary.prototype.first = function (callback) {
  48714. for (var cur in this._data) {
  48715. var val = this._data[cur];
  48716. var res = callback(cur, val);
  48717. if (res) {
  48718. return res;
  48719. }
  48720. }
  48721. return null;
  48722. };
  48723. return StringDictionary;
  48724. }());
  48725. BABYLON.StringDictionary = StringDictionary;
  48726. })(BABYLON || (BABYLON = {}));
  48727. //# sourceMappingURL=babylon.stringDictionary.js.map
  48728. var BABYLON;
  48729. (function (BABYLON) {
  48730. var Tags = (function () {
  48731. function Tags() {
  48732. }
  48733. Tags.EnableFor = function (obj) {
  48734. obj._tags = obj._tags || {};
  48735. obj.hasTags = function () {
  48736. return Tags.HasTags(obj);
  48737. };
  48738. obj.addTags = function (tagsString) {
  48739. return Tags.AddTagsTo(obj, tagsString);
  48740. };
  48741. obj.removeTags = function (tagsString) {
  48742. return Tags.RemoveTagsFrom(obj, tagsString);
  48743. };
  48744. obj.matchesTagsQuery = function (tagsQuery) {
  48745. return Tags.MatchesQuery(obj, tagsQuery);
  48746. };
  48747. };
  48748. Tags.DisableFor = function (obj) {
  48749. delete obj._tags;
  48750. delete obj.hasTags;
  48751. delete obj.addTags;
  48752. delete obj.removeTags;
  48753. delete obj.matchesTagsQuery;
  48754. };
  48755. Tags.HasTags = function (obj) {
  48756. if (!obj._tags) {
  48757. return false;
  48758. }
  48759. return !BABYLON.Tools.IsEmpty(obj._tags);
  48760. };
  48761. Tags.GetTags = function (obj, asString) {
  48762. if (asString === void 0) { asString = true; }
  48763. if (!obj._tags) {
  48764. return null;
  48765. }
  48766. if (asString) {
  48767. var tagsArray = [];
  48768. for (var tag in obj._tags) {
  48769. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  48770. tagsArray.push(tag);
  48771. }
  48772. }
  48773. return tagsArray.join(" ");
  48774. }
  48775. else {
  48776. return obj._tags;
  48777. }
  48778. };
  48779. // the tags 'true' and 'false' are reserved and cannot be used as tags
  48780. // a tag cannot start with '||', '&&', and '!'
  48781. // it cannot contain whitespaces
  48782. Tags.AddTagsTo = function (obj, tagsString) {
  48783. if (!tagsString) {
  48784. return;
  48785. }
  48786. if (typeof tagsString !== "string") {
  48787. return;
  48788. }
  48789. var tags = tagsString.split(" ");
  48790. tags.forEach(function (tag, index, array) {
  48791. Tags._AddTagTo(obj, tag);
  48792. });
  48793. };
  48794. Tags._AddTagTo = function (obj, tag) {
  48795. tag = tag.trim();
  48796. if (tag === "" || tag === "true" || tag === "false") {
  48797. return;
  48798. }
  48799. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  48800. return;
  48801. }
  48802. Tags.EnableFor(obj);
  48803. obj._tags[tag] = true;
  48804. };
  48805. Tags.RemoveTagsFrom = function (obj, tagsString) {
  48806. if (!Tags.HasTags(obj)) {
  48807. return;
  48808. }
  48809. var tags = tagsString.split(" ");
  48810. for (var t in tags) {
  48811. Tags._RemoveTagFrom(obj, tags[t]);
  48812. }
  48813. };
  48814. Tags._RemoveTagFrom = function (obj, tag) {
  48815. delete obj._tags[tag];
  48816. };
  48817. Tags.MatchesQuery = function (obj, tagsQuery) {
  48818. if (tagsQuery === undefined) {
  48819. return true;
  48820. }
  48821. if (tagsQuery === "") {
  48822. return Tags.HasTags(obj);
  48823. }
  48824. return BABYLON.Internals.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  48825. };
  48826. return Tags;
  48827. }());
  48828. BABYLON.Tags = Tags;
  48829. })(BABYLON || (BABYLON = {}));
  48830. //# sourceMappingURL=babylon.tags.js.map
  48831. var BABYLON;
  48832. (function (BABYLON) {
  48833. var Internals;
  48834. (function (Internals) {
  48835. var AndOrNotEvaluator = (function () {
  48836. function AndOrNotEvaluator() {
  48837. }
  48838. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  48839. if (!query.match(/\([^\(\)]*\)/g)) {
  48840. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  48841. }
  48842. else {
  48843. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  48844. // remove parenthesis
  48845. r = r.slice(1, r.length - 1);
  48846. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  48847. });
  48848. }
  48849. if (query === "true") {
  48850. return true;
  48851. }
  48852. if (query === "false") {
  48853. return false;
  48854. }
  48855. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  48856. };
  48857. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  48858. evaluateCallback = evaluateCallback || (function (r) {
  48859. return r === "true" ? true : false;
  48860. });
  48861. var result;
  48862. var or = parenthesisContent.split("||");
  48863. for (var i in or) {
  48864. if (or.hasOwnProperty(i)) {
  48865. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  48866. var and = ori.split("&&");
  48867. if (and.length > 1) {
  48868. for (var j = 0; j < and.length; ++j) {
  48869. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  48870. if (andj !== "true" && andj !== "false") {
  48871. if (andj[0] === "!") {
  48872. result = !evaluateCallback(andj.substring(1));
  48873. }
  48874. else {
  48875. result = evaluateCallback(andj);
  48876. }
  48877. }
  48878. else {
  48879. result = andj === "true" ? true : false;
  48880. }
  48881. if (!result) {
  48882. ori = "false";
  48883. break;
  48884. }
  48885. }
  48886. }
  48887. if (result || ori === "true") {
  48888. result = true;
  48889. break;
  48890. }
  48891. // result equals false (or undefined)
  48892. if (ori !== "true" && ori !== "false") {
  48893. if (ori[0] === "!") {
  48894. result = !evaluateCallback(ori.substring(1));
  48895. }
  48896. else {
  48897. result = evaluateCallback(ori);
  48898. }
  48899. }
  48900. else {
  48901. result = ori === "true" ? true : false;
  48902. }
  48903. }
  48904. }
  48905. // the whole parenthesis scope is replaced by 'true' or 'false'
  48906. return result ? "true" : "false";
  48907. };
  48908. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  48909. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  48910. // remove whitespaces
  48911. r = r.replace(/[\s]/g, function () { return ""; });
  48912. return r.length % 2 ? "!" : "";
  48913. });
  48914. booleanString = booleanString.trim();
  48915. if (booleanString === "!true") {
  48916. booleanString = "false";
  48917. }
  48918. else if (booleanString === "!false") {
  48919. booleanString = "true";
  48920. }
  48921. return booleanString;
  48922. };
  48923. return AndOrNotEvaluator;
  48924. }());
  48925. Internals.AndOrNotEvaluator = AndOrNotEvaluator;
  48926. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  48927. })(BABYLON || (BABYLON = {}));
  48928. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  48929. var BABYLON;
  48930. (function (BABYLON) {
  48931. var Database = (function () {
  48932. function Database(urlToScene, callbackManifestChecked) {
  48933. // Handling various flavors of prefixed version of IndexedDB
  48934. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  48935. this.callbackManifestChecked = callbackManifestChecked;
  48936. this.currentSceneUrl = Database.ReturnFullUrlLocation(urlToScene);
  48937. this.db = null;
  48938. this.enableSceneOffline = false;
  48939. this.enableTexturesOffline = false;
  48940. this.manifestVersionFound = 0;
  48941. this.mustUpdateRessources = false;
  48942. this.hasReachedQuota = false;
  48943. if (!Database.IDBStorageEnabled) {
  48944. this.callbackManifestChecked(true);
  48945. }
  48946. else {
  48947. this.checkManifestFile();
  48948. }
  48949. }
  48950. Database.prototype.checkManifestFile = function () {
  48951. var _this = this;
  48952. function noManifestFile() {
  48953. that.enableSceneOffline = false;
  48954. that.enableTexturesOffline = false;
  48955. that.callbackManifestChecked(false);
  48956. }
  48957. var that = this;
  48958. var timeStampUsed = false;
  48959. var manifestURL = this.currentSceneUrl + ".manifest";
  48960. var xhr = new XMLHttpRequest();
  48961. if (navigator.onLine) {
  48962. // Adding a timestamp to by-pass browsers' cache
  48963. timeStampUsed = true;
  48964. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + (new Date()).getTime();
  48965. }
  48966. xhr.open("GET", manifestURL, true);
  48967. xhr.addEventListener("load", function () {
  48968. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  48969. try {
  48970. var manifestFile = JSON.parse(xhr.response);
  48971. _this.enableSceneOffline = manifestFile.enableSceneOffline;
  48972. _this.enableTexturesOffline = manifestFile.enableTexturesOffline;
  48973. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  48974. _this.manifestVersionFound = manifestFile.version;
  48975. }
  48976. if (_this.callbackManifestChecked) {
  48977. _this.callbackManifestChecked(true);
  48978. }
  48979. }
  48980. catch (ex) {
  48981. noManifestFile();
  48982. }
  48983. }
  48984. else {
  48985. noManifestFile();
  48986. }
  48987. }, false);
  48988. xhr.addEventListener("error", function (event) {
  48989. if (timeStampUsed) {
  48990. timeStampUsed = false;
  48991. // Let's retry without the timeStamp
  48992. // It could fail when coupled with HTML5 Offline API
  48993. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  48994. xhr.open("GET", retryManifestURL, true);
  48995. xhr.send();
  48996. }
  48997. else {
  48998. noManifestFile();
  48999. }
  49000. }, false);
  49001. try {
  49002. xhr.send();
  49003. }
  49004. catch (ex) {
  49005. BABYLON.Tools.Error("Error on XHR send request.");
  49006. that.callbackManifestChecked(false);
  49007. }
  49008. };
  49009. Database.prototype.openAsync = function (successCallback, errorCallback) {
  49010. var _this = this;
  49011. function handleError() {
  49012. that.isSupported = false;
  49013. if (errorCallback)
  49014. errorCallback();
  49015. }
  49016. var that = this;
  49017. if (!this.idbFactory || !(this.enableSceneOffline || this.enableTexturesOffline)) {
  49018. // Your browser doesn't support IndexedDB
  49019. this.isSupported = false;
  49020. if (errorCallback)
  49021. errorCallback();
  49022. }
  49023. else {
  49024. // If the DB hasn't been opened or created yet
  49025. if (!this.db) {
  49026. this.hasReachedQuota = false;
  49027. this.isSupported = true;
  49028. var request = this.idbFactory.open("babylonjs", 1);
  49029. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  49030. request.onerror = function (event) {
  49031. handleError();
  49032. };
  49033. // executes when a version change transaction cannot complete due to other active transactions
  49034. request.onblocked = function (event) {
  49035. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  49036. handleError();
  49037. };
  49038. // DB has been opened successfully
  49039. request.onsuccess = function (event) {
  49040. _this.db = request.result;
  49041. successCallback();
  49042. };
  49043. // Initialization of the DB. Creating Scenes & Textures stores
  49044. request.onupgradeneeded = function (event) {
  49045. _this.db = (event.target).result;
  49046. try {
  49047. var scenesStore = _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  49048. var versionsStore = _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  49049. var texturesStore = _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  49050. }
  49051. catch (ex) {
  49052. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  49053. handleError();
  49054. }
  49055. };
  49056. }
  49057. else {
  49058. if (successCallback)
  49059. successCallback();
  49060. }
  49061. }
  49062. };
  49063. Database.prototype.loadImageFromDB = function (url, image) {
  49064. var _this = this;
  49065. var completeURL = Database.ReturnFullUrlLocation(url);
  49066. var saveAndLoadImage = function () {
  49067. if (!_this.hasReachedQuota && _this.db !== null) {
  49068. // the texture is not yet in the DB, let's try to save it
  49069. _this._saveImageIntoDBAsync(completeURL, image);
  49070. }
  49071. else {
  49072. image.src = url;
  49073. }
  49074. };
  49075. if (!this.mustUpdateRessources) {
  49076. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  49077. }
  49078. else {
  49079. saveAndLoadImage();
  49080. }
  49081. };
  49082. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  49083. if (this.isSupported && this.db !== null) {
  49084. var texture;
  49085. var transaction = this.db.transaction(["textures"]);
  49086. transaction.onabort = function (event) {
  49087. image.src = url;
  49088. };
  49089. transaction.oncomplete = function (event) {
  49090. var blobTextureURL;
  49091. if (texture) {
  49092. var URL = window.URL || window.webkitURL;
  49093. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  49094. image.onerror = function () {
  49095. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  49096. image.src = url;
  49097. };
  49098. image.src = blobTextureURL;
  49099. }
  49100. else {
  49101. notInDBCallback();
  49102. }
  49103. };
  49104. var getRequest = transaction.objectStore("textures").get(url);
  49105. getRequest.onsuccess = function (event) {
  49106. texture = (event.target).result;
  49107. };
  49108. getRequest.onerror = function (event) {
  49109. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  49110. image.src = url;
  49111. };
  49112. }
  49113. else {
  49114. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49115. image.src = url;
  49116. }
  49117. };
  49118. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  49119. var _this = this;
  49120. if (this.isSupported) {
  49121. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  49122. var generateBlobUrl = function () {
  49123. var blobTextureURL;
  49124. if (blob) {
  49125. var URL = window.URL || window.webkitURL;
  49126. try {
  49127. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  49128. }
  49129. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  49130. catch (ex) {
  49131. blobTextureURL = URL.createObjectURL(blob);
  49132. }
  49133. }
  49134. image.src = blobTextureURL;
  49135. };
  49136. if (Database.IsUASupportingBlobStorage) {
  49137. var xhr = new XMLHttpRequest(), blob;
  49138. xhr.open("GET", url, true);
  49139. xhr.responseType = "blob";
  49140. xhr.addEventListener("load", function () {
  49141. if (xhr.status === 200) {
  49142. // Blob as response (XHR2)
  49143. blob = xhr.response;
  49144. var transaction = _this.db.transaction(["textures"], "readwrite");
  49145. // the transaction could abort because of a QuotaExceededError error
  49146. transaction.onabort = function (event) {
  49147. try {
  49148. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49149. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49150. _this.hasReachedQuota = true;
  49151. }
  49152. }
  49153. catch (ex) { }
  49154. generateBlobUrl();
  49155. };
  49156. transaction.oncomplete = function (event) {
  49157. generateBlobUrl();
  49158. };
  49159. var newTexture = { textureUrl: url, data: blob };
  49160. try {
  49161. // Put the blob into the dabase
  49162. var addRequest = transaction.objectStore("textures").put(newTexture);
  49163. addRequest.onsuccess = function (event) {
  49164. };
  49165. addRequest.onerror = function (event) {
  49166. generateBlobUrl();
  49167. };
  49168. }
  49169. catch (ex) {
  49170. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  49171. if (ex.code === 25) {
  49172. Database.IsUASupportingBlobStorage = false;
  49173. }
  49174. image.src = url;
  49175. }
  49176. }
  49177. else {
  49178. image.src = url;
  49179. }
  49180. }, false);
  49181. xhr.addEventListener("error", function (event) {
  49182. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  49183. image.src = url;
  49184. }, false);
  49185. xhr.send();
  49186. }
  49187. else {
  49188. image.src = url;
  49189. }
  49190. }
  49191. else {
  49192. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49193. image.src = url;
  49194. }
  49195. };
  49196. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  49197. var _this = this;
  49198. var updateVersion = function (event) {
  49199. // the version is not yet in the DB or we need to update it
  49200. _this._saveVersionIntoDBAsync(url, versionLoaded);
  49201. };
  49202. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  49203. };
  49204. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  49205. var _this = this;
  49206. if (this.isSupported) {
  49207. var version;
  49208. try {
  49209. var transaction = this.db.transaction(["versions"]);
  49210. transaction.oncomplete = function (event) {
  49211. if (version) {
  49212. // If the version in the JSON file is > than the version in DB
  49213. if (_this.manifestVersionFound > version.data) {
  49214. _this.mustUpdateRessources = true;
  49215. updateInDBCallback();
  49216. }
  49217. else {
  49218. callback(version.data);
  49219. }
  49220. }
  49221. else {
  49222. _this.mustUpdateRessources = true;
  49223. updateInDBCallback();
  49224. }
  49225. };
  49226. transaction.onabort = function (event) {
  49227. callback(-1);
  49228. };
  49229. var getRequest = transaction.objectStore("versions").get(url);
  49230. getRequest.onsuccess = function (event) {
  49231. version = (event.target).result;
  49232. };
  49233. getRequest.onerror = function (event) {
  49234. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  49235. callback(-1);
  49236. };
  49237. }
  49238. catch (ex) {
  49239. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  49240. callback(-1);
  49241. }
  49242. }
  49243. else {
  49244. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49245. callback(-1);
  49246. }
  49247. };
  49248. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  49249. var _this = this;
  49250. if (this.isSupported && !this.hasReachedQuota) {
  49251. try {
  49252. // Open a transaction to the database
  49253. var transaction = this.db.transaction(["versions"], "readwrite");
  49254. // the transaction could abort because of a QuotaExceededError error
  49255. transaction.onabort = function (event) {
  49256. try {
  49257. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49258. _this.hasReachedQuota = true;
  49259. }
  49260. }
  49261. catch (ex) { }
  49262. callback(-1);
  49263. };
  49264. transaction.oncomplete = function (event) {
  49265. callback(_this.manifestVersionFound);
  49266. };
  49267. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  49268. // Put the scene into the database
  49269. var addRequest = transaction.objectStore("versions").put(newVersion);
  49270. addRequest.onsuccess = function (event) {
  49271. };
  49272. addRequest.onerror = function (event) {
  49273. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  49274. };
  49275. }
  49276. catch (ex) {
  49277. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  49278. callback(-1);
  49279. }
  49280. }
  49281. else {
  49282. callback(-1);
  49283. }
  49284. };
  49285. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  49286. var _this = this;
  49287. var completeUrl = Database.ReturnFullUrlLocation(url);
  49288. var saveAndLoadFile = function (event) {
  49289. // the scene is not yet in the DB, let's try to save it
  49290. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  49291. };
  49292. this._checkVersionFromDB(completeUrl, function (version) {
  49293. if (version !== -1) {
  49294. if (!_this.mustUpdateRessources) {
  49295. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  49296. }
  49297. else {
  49298. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  49299. }
  49300. }
  49301. else {
  49302. errorCallback();
  49303. }
  49304. });
  49305. };
  49306. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  49307. if (this.isSupported) {
  49308. var targetStore;
  49309. if (url.indexOf(".babylon") !== -1) {
  49310. targetStore = "scenes";
  49311. }
  49312. else {
  49313. targetStore = "textures";
  49314. }
  49315. var file;
  49316. var transaction = this.db.transaction([targetStore]);
  49317. transaction.oncomplete = function (event) {
  49318. if (file) {
  49319. callback(file.data);
  49320. }
  49321. else {
  49322. notInDBCallback();
  49323. }
  49324. };
  49325. transaction.onabort = function (event) {
  49326. notInDBCallback();
  49327. };
  49328. var getRequest = transaction.objectStore(targetStore).get(url);
  49329. getRequest.onsuccess = function (event) {
  49330. file = (event.target).result;
  49331. };
  49332. getRequest.onerror = function (event) {
  49333. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  49334. notInDBCallback();
  49335. };
  49336. }
  49337. else {
  49338. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49339. callback();
  49340. }
  49341. };
  49342. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  49343. var _this = this;
  49344. if (this.isSupported) {
  49345. var targetStore;
  49346. if (url.indexOf(".babylon") !== -1) {
  49347. targetStore = "scenes";
  49348. }
  49349. else {
  49350. targetStore = "textures";
  49351. }
  49352. // Create XHR
  49353. var xhr = new XMLHttpRequest(), fileData;
  49354. xhr.open("GET", url, true);
  49355. if (useArrayBuffer) {
  49356. xhr.responseType = "arraybuffer";
  49357. }
  49358. xhr.onprogress = progressCallback;
  49359. xhr.addEventListener("load", function () {
  49360. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  49361. // Blob as response (XHR2)
  49362. //fileData = xhr.responseText;
  49363. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  49364. if (!_this.hasReachedQuota) {
  49365. // Open a transaction to the database
  49366. var transaction = _this.db.transaction([targetStore], "readwrite");
  49367. // the transaction could abort because of a QuotaExceededError error
  49368. transaction.onabort = function (event) {
  49369. try {
  49370. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  49371. if (event.srcElement['error'] && event.srcElement['error'].name === "QuotaExceededError") {
  49372. _this.hasReachedQuota = true;
  49373. }
  49374. }
  49375. catch (ex) { }
  49376. callback(fileData);
  49377. };
  49378. transaction.oncomplete = function (event) {
  49379. callback(fileData);
  49380. };
  49381. var newFile;
  49382. if (targetStore === "scenes") {
  49383. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  49384. }
  49385. else {
  49386. newFile = { textureUrl: url, data: fileData };
  49387. }
  49388. try {
  49389. // Put the scene into the database
  49390. var addRequest = transaction.objectStore(targetStore).put(newFile);
  49391. addRequest.onsuccess = function (event) {
  49392. };
  49393. addRequest.onerror = function (event) {
  49394. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  49395. };
  49396. }
  49397. catch (ex) {
  49398. callback(fileData);
  49399. }
  49400. }
  49401. else {
  49402. callback(fileData);
  49403. }
  49404. }
  49405. else {
  49406. callback();
  49407. }
  49408. }, false);
  49409. xhr.addEventListener("error", function (event) {
  49410. BABYLON.Tools.Error("error on XHR request.");
  49411. callback();
  49412. }, false);
  49413. xhr.send();
  49414. }
  49415. else {
  49416. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  49417. callback();
  49418. }
  49419. };
  49420. Database.IsUASupportingBlobStorage = true;
  49421. Database.IDBStorageEnabled = true;
  49422. Database.parseURL = function (url) {
  49423. var a = document.createElement('a');
  49424. a.href = url;
  49425. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  49426. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  49427. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  49428. return absLocation;
  49429. };
  49430. Database.ReturnFullUrlLocation = function (url) {
  49431. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  49432. return (Database.parseURL(window.location.href) + url);
  49433. }
  49434. else {
  49435. return url;
  49436. }
  49437. };
  49438. return Database;
  49439. }());
  49440. BABYLON.Database = Database;
  49441. })(BABYLON || (BABYLON = {}));
  49442. //# sourceMappingURL=babylon.database.js.map
  49443. var BABYLON;
  49444. (function (BABYLON) {
  49445. var FresnelParameters = (function () {
  49446. function FresnelParameters() {
  49447. this._isEnabled = true;
  49448. this.leftColor = BABYLON.Color3.White();
  49449. this.rightColor = BABYLON.Color3.Black();
  49450. this.bias = 0;
  49451. this.power = 1;
  49452. }
  49453. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  49454. get: function () {
  49455. return this._isEnabled;
  49456. },
  49457. set: function (value) {
  49458. if (this._isEnabled === value) {
  49459. return;
  49460. }
  49461. this._isEnabled = value;
  49462. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  49463. },
  49464. enumerable: true,
  49465. configurable: true
  49466. });
  49467. FresnelParameters.prototype.clone = function () {
  49468. var newFresnelParameters = new FresnelParameters();
  49469. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  49470. return newFresnelParameters;
  49471. };
  49472. FresnelParameters.prototype.serialize = function () {
  49473. var serializationObject = {};
  49474. serializationObject.isEnabled = this.isEnabled;
  49475. serializationObject.leftColor = this.leftColor;
  49476. serializationObject.rightColor = this.rightColor;
  49477. serializationObject.bias = this.bias;
  49478. serializationObject.power = this.power;
  49479. return serializationObject;
  49480. };
  49481. FresnelParameters.Parse = function (parsedFresnelParameters) {
  49482. var fresnelParameters = new FresnelParameters();
  49483. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  49484. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  49485. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  49486. fresnelParameters.bias = parsedFresnelParameters.bias;
  49487. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  49488. return fresnelParameters;
  49489. };
  49490. return FresnelParameters;
  49491. }());
  49492. BABYLON.FresnelParameters = FresnelParameters;
  49493. })(BABYLON || (BABYLON = {}));
  49494. //# sourceMappingURL=babylon.fresnelParameters.js.map
  49495. var BABYLON;
  49496. (function (BABYLON) {
  49497. var MultiMaterial = (function (_super) {
  49498. __extends(MultiMaterial, _super);
  49499. function MultiMaterial(name, scene) {
  49500. var _this = _super.call(this, name, scene, true) || this;
  49501. scene.multiMaterials.push(_this);
  49502. _this.subMaterials = new Array();
  49503. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  49504. return _this;
  49505. }
  49506. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  49507. get: function () {
  49508. return this._subMaterials;
  49509. },
  49510. set: function (value) {
  49511. this._subMaterials = value;
  49512. this._hookArray(value);
  49513. },
  49514. enumerable: true,
  49515. configurable: true
  49516. });
  49517. MultiMaterial.prototype._hookArray = function (array) {
  49518. var _this = this;
  49519. var oldPush = array.push;
  49520. array.push = function () {
  49521. var items = [];
  49522. for (var _i = 0; _i < arguments.length; _i++) {
  49523. items[_i] = arguments[_i];
  49524. }
  49525. var result = oldPush.apply(array, items);
  49526. _this._markAllSubMeshesAsTexturesDirty();
  49527. return result;
  49528. };
  49529. var oldSplice = array.splice;
  49530. array.splice = function (index, deleteCount) {
  49531. var deleted = oldSplice.apply(array, [index, deleteCount]);
  49532. _this._markAllSubMeshesAsTexturesDirty();
  49533. return deleted;
  49534. };
  49535. };
  49536. // Properties
  49537. MultiMaterial.prototype.getSubMaterial = function (index) {
  49538. if (index < 0 || index >= this.subMaterials.length) {
  49539. return this.getScene().defaultMaterial;
  49540. }
  49541. return this.subMaterials[index];
  49542. };
  49543. MultiMaterial.prototype.getActiveTextures = function () {
  49544. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) { return subMaterial.getActiveTextures(); }));
  49545. var _a;
  49546. };
  49547. // Methods
  49548. MultiMaterial.prototype.getClassName = function () {
  49549. return "MultiMaterial";
  49550. };
  49551. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  49552. for (var index = 0; index < this.subMaterials.length; index++) {
  49553. var subMaterial = this.subMaterials[index];
  49554. if (subMaterial) {
  49555. if (this.subMaterials[index].storeEffectOnSubMeshes) {
  49556. if (!this.subMaterials[index].isReadyForSubMesh(mesh, subMesh, useInstances)) {
  49557. return false;
  49558. }
  49559. continue;
  49560. }
  49561. if (!this.subMaterials[index].isReady(mesh)) {
  49562. return false;
  49563. }
  49564. }
  49565. }
  49566. return true;
  49567. };
  49568. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  49569. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  49570. for (var index = 0; index < this.subMaterials.length; index++) {
  49571. var subMaterial = null;
  49572. if (cloneChildren) {
  49573. subMaterial = this.subMaterials[index].clone(name + "-" + this.subMaterials[index].name);
  49574. }
  49575. else {
  49576. subMaterial = this.subMaterials[index];
  49577. }
  49578. newMultiMaterial.subMaterials.push(subMaterial);
  49579. }
  49580. return newMultiMaterial;
  49581. };
  49582. MultiMaterial.prototype.serialize = function () {
  49583. var serializationObject = {};
  49584. serializationObject.name = this.name;
  49585. serializationObject.id = this.id;
  49586. serializationObject.tags = BABYLON.Tags.GetTags(this);
  49587. serializationObject.materials = [];
  49588. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  49589. var subMat = this.subMaterials[matIndex];
  49590. if (subMat) {
  49591. serializationObject.materials.push(subMat.id);
  49592. }
  49593. else {
  49594. serializationObject.materials.push(null);
  49595. }
  49596. }
  49597. return serializationObject;
  49598. };
  49599. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  49600. var scene = this.getScene();
  49601. if (!scene) {
  49602. return;
  49603. }
  49604. var index = scene.multiMaterials.indexOf(this);
  49605. if (index >= 0) {
  49606. scene.multiMaterials.splice(index, 1);
  49607. }
  49608. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  49609. };
  49610. return MultiMaterial;
  49611. }(BABYLON.Material));
  49612. BABYLON.MultiMaterial = MultiMaterial;
  49613. })(BABYLON || (BABYLON = {}));
  49614. //# sourceMappingURL=babylon.multiMaterial.js.map
  49615. var BABYLON;
  49616. (function (BABYLON) {
  49617. var FreeCameraTouchInput = (function () {
  49618. function FreeCameraTouchInput() {
  49619. this._offsetX = null;
  49620. this._offsetY = null;
  49621. this._pointerCount = 0;
  49622. this._pointerPressed = [];
  49623. this.touchAngularSensibility = 200000.0;
  49624. this.touchMoveSensibility = 250.0;
  49625. }
  49626. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  49627. var _this = this;
  49628. var previousPosition;
  49629. if (this._pointerInput === undefined) {
  49630. this._onLostFocus = function (evt) {
  49631. _this._offsetX = null;
  49632. _this._offsetY = null;
  49633. };
  49634. this._pointerInput = function (p, s) {
  49635. var evt = p.event;
  49636. if (evt.pointerType === "mouse") {
  49637. return;
  49638. }
  49639. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  49640. if (!noPreventDefault) {
  49641. evt.preventDefault();
  49642. }
  49643. _this._pointerPressed.push(evt.pointerId);
  49644. if (_this._pointerPressed.length !== 1) {
  49645. return;
  49646. }
  49647. previousPosition = {
  49648. x: evt.clientX,
  49649. y: evt.clientY
  49650. };
  49651. }
  49652. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  49653. if (!noPreventDefault) {
  49654. evt.preventDefault();
  49655. }
  49656. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49657. if (index === -1) {
  49658. return;
  49659. }
  49660. _this._pointerPressed.splice(index, 1);
  49661. if (index != 0) {
  49662. return;
  49663. }
  49664. previousPosition = null;
  49665. _this._offsetX = null;
  49666. _this._offsetY = null;
  49667. }
  49668. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  49669. if (!noPreventDefault) {
  49670. evt.preventDefault();
  49671. }
  49672. if (!previousPosition) {
  49673. return;
  49674. }
  49675. var index = _this._pointerPressed.indexOf(evt.pointerId);
  49676. if (index != 0) {
  49677. return;
  49678. }
  49679. _this._offsetX = evt.clientX - previousPosition.x;
  49680. _this._offsetY = -(evt.clientY - previousPosition.y);
  49681. }
  49682. };
  49683. }
  49684. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  49685. element.addEventListener("blur", this._onLostFocus);
  49686. };
  49687. FreeCameraTouchInput.prototype.detachControl = function (element) {
  49688. if (this._pointerInput && element) {
  49689. this.camera.getScene().onPointerObservable.remove(this._observer);
  49690. this._observer = null;
  49691. element.removeEventListener("blur", this._onLostFocus);
  49692. this._onLostFocus = null;
  49693. this._pointerPressed = [];
  49694. this._offsetX = null;
  49695. this._offsetY = null;
  49696. this._pointerCount = 0;
  49697. }
  49698. };
  49699. FreeCameraTouchInput.prototype.checkInputs = function () {
  49700. if (this._offsetX) {
  49701. var camera = this.camera;
  49702. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  49703. if (this._pointerPressed.length > 1) {
  49704. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  49705. }
  49706. else {
  49707. var speed = camera._computeLocalCameraSpeed();
  49708. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  49709. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  49710. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  49711. }
  49712. }
  49713. };
  49714. FreeCameraTouchInput.prototype.getClassName = function () {
  49715. return "FreeCameraTouchInput";
  49716. };
  49717. FreeCameraTouchInput.prototype.getSimpleName = function () {
  49718. return "touch";
  49719. };
  49720. __decorate([
  49721. BABYLON.serialize()
  49722. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  49723. __decorate([
  49724. BABYLON.serialize()
  49725. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  49726. return FreeCameraTouchInput;
  49727. }());
  49728. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  49729. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  49730. })(BABYLON || (BABYLON = {}));
  49731. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  49732. /// <reference path="babylon.freeCamera.ts" />
  49733. var BABYLON;
  49734. (function (BABYLON) {
  49735. // We're mainly based on the logic defined into the FreeCamera code
  49736. var TouchCamera = (function (_super) {
  49737. __extends(TouchCamera, _super);
  49738. //-- end properties for backward compatibility for inputs
  49739. function TouchCamera(name, position, scene) {
  49740. var _this = _super.call(this, name, position, scene) || this;
  49741. _this.inputs.addTouch();
  49742. _this._setupInputs();
  49743. return _this;
  49744. }
  49745. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  49746. //-- Begin properties for backward compatibility for inputs
  49747. get: function () {
  49748. var touch = this.inputs.attached["touch"];
  49749. if (touch)
  49750. return touch.touchAngularSensibility;
  49751. },
  49752. set: function (value) {
  49753. var touch = this.inputs.attached["touch"];
  49754. if (touch)
  49755. touch.touchAngularSensibility = value;
  49756. },
  49757. enumerable: true,
  49758. configurable: true
  49759. });
  49760. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  49761. get: function () {
  49762. var touch = this.inputs.attached["touch"];
  49763. if (touch)
  49764. return touch.touchMoveSensibility;
  49765. },
  49766. set: function (value) {
  49767. var touch = this.inputs.attached["touch"];
  49768. if (touch)
  49769. touch.touchMoveSensibility = value;
  49770. },
  49771. enumerable: true,
  49772. configurable: true
  49773. });
  49774. TouchCamera.prototype.getClassName = function () {
  49775. return "TouchCamera";
  49776. };
  49777. TouchCamera.prototype._setupInputs = function () {
  49778. var mouse = this.inputs.attached["mouse"];
  49779. if (mouse) {
  49780. mouse.touchEnabled = false;
  49781. }
  49782. };
  49783. return TouchCamera;
  49784. }(BABYLON.FreeCamera));
  49785. BABYLON.TouchCamera = TouchCamera;
  49786. })(BABYLON || (BABYLON = {}));
  49787. //# sourceMappingURL=babylon.touchCamera.js.map
  49788. var BABYLON;
  49789. (function (BABYLON) {
  49790. var ProceduralTexture = (function (_super) {
  49791. __extends(ProceduralTexture, _super);
  49792. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  49793. if (generateMipMaps === void 0) { generateMipMaps = true; }
  49794. if (isCube === void 0) { isCube = false; }
  49795. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  49796. _this.isCube = isCube;
  49797. _this.isEnabled = true;
  49798. _this._currentRefreshId = -1;
  49799. _this._refreshRate = 1;
  49800. _this._vertexBuffers = {};
  49801. _this._uniforms = new Array();
  49802. _this._samplers = new Array();
  49803. _this._textures = new Array();
  49804. _this._floats = new Array();
  49805. _this._floatsArrays = {};
  49806. _this._colors3 = new Array();
  49807. _this._colors4 = new Array();
  49808. _this._vectors2 = new Array();
  49809. _this._vectors3 = new Array();
  49810. _this._matrices = new Array();
  49811. _this._fallbackTextureUsed = false;
  49812. scene._proceduralTextures.push(_this);
  49813. _this.name = name;
  49814. _this.isRenderTarget = true;
  49815. _this._size = size;
  49816. _this._generateMipMaps = generateMipMaps;
  49817. _this.setFragment(fragment);
  49818. _this._fallbackTexture = fallbackTexture;
  49819. var engine = scene.getEngine();
  49820. if (isCube) {
  49821. _this._texture = engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  49822. _this.setFloat("face", 0);
  49823. }
  49824. else {
  49825. _this._texture = engine.createRenderTargetTexture(size, generateMipMaps);
  49826. }
  49827. // VBO
  49828. var vertices = [];
  49829. vertices.push(1, 1);
  49830. vertices.push(-1, 1);
  49831. vertices.push(-1, -1);
  49832. vertices.push(1, -1);
  49833. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  49834. // Indices
  49835. var indices = [];
  49836. indices.push(0);
  49837. indices.push(1);
  49838. indices.push(2);
  49839. indices.push(0);
  49840. indices.push(2);
  49841. indices.push(3);
  49842. _this._indexBuffer = engine.createIndexBuffer(indices);
  49843. return _this;
  49844. }
  49845. ProceduralTexture.prototype.reset = function () {
  49846. if (this._effect === undefined) {
  49847. return;
  49848. }
  49849. var engine = this.getScene().getEngine();
  49850. engine._releaseEffect(this._effect);
  49851. };
  49852. ProceduralTexture.prototype.isReady = function () {
  49853. var _this = this;
  49854. var engine = this.getScene().getEngine();
  49855. var shaders;
  49856. if (!this._fragment) {
  49857. return false;
  49858. }
  49859. if (this._fallbackTextureUsed) {
  49860. return true;
  49861. }
  49862. if (this._fragment.fragmentElement !== undefined) {
  49863. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  49864. }
  49865. else {
  49866. shaders = { vertex: "procedural", fragment: this._fragment };
  49867. }
  49868. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", null, null, function () {
  49869. _this.releaseInternalTexture();
  49870. if (_this._fallbackTexture) {
  49871. _this._texture = _this._fallbackTexture._texture;
  49872. _this._texture.incrementReferences();
  49873. }
  49874. _this._fallbackTextureUsed = true;
  49875. });
  49876. return this._effect.isReady();
  49877. };
  49878. ProceduralTexture.prototype.resetRefreshCounter = function () {
  49879. this._currentRefreshId = -1;
  49880. };
  49881. ProceduralTexture.prototype.setFragment = function (fragment) {
  49882. this._fragment = fragment;
  49883. };
  49884. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  49885. get: function () {
  49886. return this._refreshRate;
  49887. },
  49888. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  49889. set: function (value) {
  49890. this._refreshRate = value;
  49891. this.resetRefreshCounter();
  49892. },
  49893. enumerable: true,
  49894. configurable: true
  49895. });
  49896. ProceduralTexture.prototype._shouldRender = function () {
  49897. if (!this.isEnabled || !this.isReady() || !this._texture) {
  49898. return false;
  49899. }
  49900. if (this._fallbackTextureUsed) {
  49901. return false;
  49902. }
  49903. if (this._currentRefreshId === -1) {
  49904. this._currentRefreshId = 1;
  49905. return true;
  49906. }
  49907. if (this.refreshRate === this._currentRefreshId) {
  49908. this._currentRefreshId = 1;
  49909. return true;
  49910. }
  49911. this._currentRefreshId++;
  49912. return false;
  49913. };
  49914. ProceduralTexture.prototype.getRenderSize = function () {
  49915. return this._size;
  49916. };
  49917. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  49918. if (this._fallbackTextureUsed) {
  49919. return;
  49920. }
  49921. this.releaseInternalTexture();
  49922. this._texture = this.getScene().getEngine().createRenderTargetTexture(size, generateMipMaps);
  49923. };
  49924. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  49925. if (this._uniforms.indexOf(uniformName) === -1) {
  49926. this._uniforms.push(uniformName);
  49927. }
  49928. };
  49929. ProceduralTexture.prototype.setTexture = function (name, texture) {
  49930. if (this._samplers.indexOf(name) === -1) {
  49931. this._samplers.push(name);
  49932. }
  49933. this._textures[name] = texture;
  49934. return this;
  49935. };
  49936. ProceduralTexture.prototype.setFloat = function (name, value) {
  49937. this._checkUniform(name);
  49938. this._floats[name] = value;
  49939. return this;
  49940. };
  49941. ProceduralTexture.prototype.setFloats = function (name, value) {
  49942. this._checkUniform(name);
  49943. this._floatsArrays[name] = value;
  49944. return this;
  49945. };
  49946. ProceduralTexture.prototype.setColor3 = function (name, value) {
  49947. this._checkUniform(name);
  49948. this._colors3[name] = value;
  49949. return this;
  49950. };
  49951. ProceduralTexture.prototype.setColor4 = function (name, value) {
  49952. this._checkUniform(name);
  49953. this._colors4[name] = value;
  49954. return this;
  49955. };
  49956. ProceduralTexture.prototype.setVector2 = function (name, value) {
  49957. this._checkUniform(name);
  49958. this._vectors2[name] = value;
  49959. return this;
  49960. };
  49961. ProceduralTexture.prototype.setVector3 = function (name, value) {
  49962. this._checkUniform(name);
  49963. this._vectors3[name] = value;
  49964. return this;
  49965. };
  49966. ProceduralTexture.prototype.setMatrix = function (name, value) {
  49967. this._checkUniform(name);
  49968. this._matrices[name] = value;
  49969. return this;
  49970. };
  49971. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  49972. var scene = this.getScene();
  49973. var engine = scene.getEngine();
  49974. // Render
  49975. engine.enableEffect(this._effect);
  49976. engine.setState(false);
  49977. // Texture
  49978. for (var name in this._textures) {
  49979. this._effect.setTexture(name, this._textures[name]);
  49980. }
  49981. // Float
  49982. for (name in this._floats) {
  49983. this._effect.setFloat(name, this._floats[name]);
  49984. }
  49985. // Floats
  49986. for (name in this._floatsArrays) {
  49987. this._effect.setArray(name, this._floatsArrays[name]);
  49988. }
  49989. // Color3
  49990. for (name in this._colors3) {
  49991. this._effect.setColor3(name, this._colors3[name]);
  49992. }
  49993. // Color4
  49994. for (name in this._colors4) {
  49995. var color = this._colors4[name];
  49996. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  49997. }
  49998. // Vector2
  49999. for (name in this._vectors2) {
  50000. this._effect.setVector2(name, this._vectors2[name]);
  50001. }
  50002. // Vector3
  50003. for (name in this._vectors3) {
  50004. this._effect.setVector3(name, this._vectors3[name]);
  50005. }
  50006. // Matrix
  50007. for (name in this._matrices) {
  50008. this._effect.setMatrix(name, this._matrices[name]);
  50009. }
  50010. if (this.isCube) {
  50011. for (var face = 0; face < 6; face++) {
  50012. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  50013. // VBOs
  50014. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50015. this._effect.setFloat("face", face);
  50016. // Clear
  50017. engine.clear(scene.clearColor, true, true, true);
  50018. // Draw order
  50019. engine.draw(true, 0, 6);
  50020. // Mipmaps
  50021. if (face === 5) {
  50022. engine.generateMipMapsForCubemap(this._texture);
  50023. }
  50024. }
  50025. }
  50026. else {
  50027. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  50028. // VBOs
  50029. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  50030. // Clear
  50031. engine.clear(scene.clearColor, true, true, true);
  50032. // Draw order
  50033. engine.draw(true, 0, 6);
  50034. }
  50035. // Unbind
  50036. engine.unBindFramebuffer(this._texture, this.isCube);
  50037. if (this.onGenerated) {
  50038. this.onGenerated();
  50039. }
  50040. };
  50041. ProceduralTexture.prototype.clone = function () {
  50042. var textureSize = this.getSize();
  50043. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  50044. // Base texture
  50045. newTexture.hasAlpha = this.hasAlpha;
  50046. newTexture.level = this.level;
  50047. // RenderTarget Texture
  50048. newTexture.coordinatesMode = this.coordinatesMode;
  50049. return newTexture;
  50050. };
  50051. ProceduralTexture.prototype.dispose = function () {
  50052. var index = this.getScene()._proceduralTextures.indexOf(this);
  50053. if (index >= 0) {
  50054. this.getScene()._proceduralTextures.splice(index, 1);
  50055. }
  50056. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  50057. if (vertexBuffer) {
  50058. vertexBuffer.dispose();
  50059. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  50060. }
  50061. if (this._indexBuffer && this.getScene().getEngine()._releaseBuffer(this._indexBuffer)) {
  50062. this._indexBuffer = null;
  50063. }
  50064. _super.prototype.dispose.call(this);
  50065. };
  50066. return ProceduralTexture;
  50067. }(BABYLON.Texture));
  50068. BABYLON.ProceduralTexture = ProceduralTexture;
  50069. })(BABYLON || (BABYLON = {}));
  50070. //# sourceMappingURL=babylon.proceduralTexture.js.map
  50071. /// <reference path="babylon.proceduralTexture.ts" />
  50072. var BABYLON;
  50073. (function (BABYLON) {
  50074. var CustomProceduralTexture = (function (_super) {
  50075. __extends(CustomProceduralTexture, _super);
  50076. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  50077. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  50078. _this._animate = true;
  50079. _this._time = 0;
  50080. _this._texturePath = texturePath;
  50081. //Try to load json
  50082. _this.loadJson(texturePath);
  50083. _this.refreshRate = 1;
  50084. return _this;
  50085. }
  50086. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  50087. var _this = this;
  50088. var that = this;
  50089. function noConfigFile() {
  50090. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  50091. try {
  50092. that.setFragment(that._texturePath);
  50093. }
  50094. catch (ex) {
  50095. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  50096. }
  50097. }
  50098. var configFileUrl = jsonUrl + "/config.json";
  50099. var xhr = new XMLHttpRequest();
  50100. xhr.open("GET", configFileUrl, true);
  50101. xhr.addEventListener("load", function () {
  50102. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  50103. try {
  50104. _this._config = JSON.parse(xhr.response);
  50105. _this.updateShaderUniforms();
  50106. _this.updateTextures();
  50107. _this.setFragment(_this._texturePath + "/custom");
  50108. _this._animate = _this._config.animate;
  50109. _this.refreshRate = _this._config.refreshrate;
  50110. }
  50111. catch (ex) {
  50112. noConfigFile();
  50113. }
  50114. }
  50115. else {
  50116. noConfigFile();
  50117. }
  50118. }, false);
  50119. xhr.addEventListener("error", function () {
  50120. noConfigFile();
  50121. }, false);
  50122. try {
  50123. xhr.send();
  50124. }
  50125. catch (ex) {
  50126. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  50127. }
  50128. };
  50129. CustomProceduralTexture.prototype.isReady = function () {
  50130. if (!_super.prototype.isReady.call(this)) {
  50131. return false;
  50132. }
  50133. for (var name in this._textures) {
  50134. var texture = this._textures[name];
  50135. if (!texture.isReady()) {
  50136. return false;
  50137. }
  50138. }
  50139. return true;
  50140. };
  50141. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  50142. if (this._animate) {
  50143. this._time += this.getScene().getAnimationRatio() * 0.03;
  50144. this.updateShaderUniforms();
  50145. }
  50146. _super.prototype.render.call(this, useCameraPostProcess);
  50147. };
  50148. CustomProceduralTexture.prototype.updateTextures = function () {
  50149. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  50150. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  50151. }
  50152. };
  50153. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  50154. if (this._config) {
  50155. for (var j = 0; j < this._config.uniforms.length; j++) {
  50156. var uniform = this._config.uniforms[j];
  50157. switch (uniform.type) {
  50158. case "float":
  50159. this.setFloat(uniform.name, uniform.value);
  50160. break;
  50161. case "color3":
  50162. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  50163. break;
  50164. case "color4":
  50165. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  50166. break;
  50167. case "vector2":
  50168. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  50169. break;
  50170. case "vector3":
  50171. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  50172. break;
  50173. }
  50174. }
  50175. }
  50176. this.setFloat("time", this._time);
  50177. };
  50178. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  50179. get: function () {
  50180. return this._animate;
  50181. },
  50182. set: function (value) {
  50183. this._animate = value;
  50184. },
  50185. enumerable: true,
  50186. configurable: true
  50187. });
  50188. return CustomProceduralTexture;
  50189. }(BABYLON.ProceduralTexture));
  50190. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  50191. })(BABYLON || (BABYLON = {}));
  50192. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  50193. var BABYLON;
  50194. (function (BABYLON) {
  50195. var FreeCameraGamepadInput = (function () {
  50196. function FreeCameraGamepadInput() {
  50197. this.gamepadAngularSensibility = 200;
  50198. this.gamepadMoveSensibility = 40;
  50199. // private members
  50200. this._cameraTransform = BABYLON.Matrix.Identity();
  50201. this._deltaTransform = BABYLON.Vector3.Zero();
  50202. this._vector3 = BABYLON.Vector3.Zero();
  50203. this._vector2 = BABYLON.Vector2.Zero();
  50204. }
  50205. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50206. var _this = this;
  50207. var manager = this.camera.getScene().gamepadManager;
  50208. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50209. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50210. // prioritize XBOX gamepads.
  50211. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50212. _this.gamepad = gamepad;
  50213. }
  50214. }
  50215. });
  50216. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50217. if (_this.gamepad === gamepad) {
  50218. _this.gamepad = null;
  50219. }
  50220. });
  50221. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50222. };
  50223. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  50224. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50225. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50226. this.gamepad = null;
  50227. };
  50228. FreeCameraGamepadInput.prototype.checkInputs = function () {
  50229. if (this.gamepad && this.gamepad.leftStick) {
  50230. var camera = this.camera;
  50231. var LSValues = this.gamepad.leftStick;
  50232. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  50233. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50234. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  50235. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  50236. var RSValues = this.gamepad.rightStick;
  50237. if (RSValues) {
  50238. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  50239. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  50240. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  50241. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  50242. }
  50243. else {
  50244. RSValues = { x: 0, y: 0 };
  50245. }
  50246. if (!camera.rotationQuaternion) {
  50247. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  50248. }
  50249. else {
  50250. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  50251. }
  50252. var speed = camera._computeLocalCameraSpeed() * 50.0;
  50253. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  50254. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  50255. camera.cameraDirection.addInPlace(this._deltaTransform);
  50256. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  50257. camera.cameraRotation.addInPlace(this._vector2);
  50258. }
  50259. };
  50260. FreeCameraGamepadInput.prototype.getClassName = function () {
  50261. return "FreeCameraGamepadInput";
  50262. };
  50263. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  50264. return "gamepad";
  50265. };
  50266. __decorate([
  50267. BABYLON.serialize()
  50268. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  50269. __decorate([
  50270. BABYLON.serialize()
  50271. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50272. return FreeCameraGamepadInput;
  50273. }());
  50274. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  50275. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  50276. })(BABYLON || (BABYLON = {}));
  50277. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  50278. var BABYLON;
  50279. (function (BABYLON) {
  50280. var ArcRotateCameraGamepadInput = (function () {
  50281. function ArcRotateCameraGamepadInput() {
  50282. this.gamepadRotationSensibility = 80;
  50283. this.gamepadMoveSensibility = 40;
  50284. }
  50285. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  50286. var _this = this;
  50287. var manager = this.camera.getScene().gamepadManager;
  50288. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  50289. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  50290. // prioritize XBOX gamepads.
  50291. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  50292. _this.gamepad = gamepad;
  50293. }
  50294. }
  50295. });
  50296. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  50297. if (_this.gamepad === gamepad) {
  50298. _this.gamepad = null;
  50299. }
  50300. });
  50301. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  50302. };
  50303. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  50304. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  50305. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  50306. this.gamepad = null;
  50307. };
  50308. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  50309. if (this.gamepad) {
  50310. var camera = this.camera;
  50311. var RSValues = this.gamepad.rightStick;
  50312. if (RSValues) {
  50313. if (RSValues.x != 0) {
  50314. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  50315. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  50316. camera.inertialAlphaOffset += normalizedRX;
  50317. }
  50318. }
  50319. if (RSValues.y != 0) {
  50320. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  50321. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  50322. camera.inertialBetaOffset += normalizedRY;
  50323. }
  50324. }
  50325. }
  50326. var LSValues = this.gamepad.leftStick;
  50327. if (LSValues && LSValues.y != 0) {
  50328. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  50329. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  50330. this.camera.inertialRadiusOffset -= normalizedLY;
  50331. }
  50332. }
  50333. }
  50334. };
  50335. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  50336. return "ArcRotateCameraGamepadInput";
  50337. };
  50338. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  50339. return "gamepad";
  50340. };
  50341. __decorate([
  50342. BABYLON.serialize()
  50343. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  50344. __decorate([
  50345. BABYLON.serialize()
  50346. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  50347. return ArcRotateCameraGamepadInput;
  50348. }());
  50349. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  50350. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  50351. })(BABYLON || (BABYLON = {}));
  50352. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  50353. var BABYLON;
  50354. (function (BABYLON) {
  50355. var GamepadManager = (function () {
  50356. function GamepadManager() {
  50357. var _this = this;
  50358. this._babylonGamepads = [];
  50359. this._oneGamepadConnected = false;
  50360. this._isMonitoring = false;
  50361. this._gamepadEventSupported = 'GamepadEvent' in window;
  50362. this._gamepadSupport = (navigator.getGamepads ||
  50363. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  50364. this.onGamepadConnectedObservable = new BABYLON.Observable();
  50365. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  50366. this._onGamepadConnectedEvent = function (evt) {
  50367. var gamepad = evt.gamepad;
  50368. // Protection code for Chrome which has a very buggy gamepad implementation...
  50369. // And raises a connected event on disconnection for instance
  50370. if (gamepad.index in _this._babylonGamepads) {
  50371. return;
  50372. }
  50373. var newGamepad = _this._addNewGamepad(gamepad);
  50374. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50375. _this._startMonitoringGamepads();
  50376. };
  50377. this._onGamepadDisconnectedEvent = function (evt) {
  50378. var gamepad = evt.gamepad;
  50379. // Remove the gamepad from the list of gamepads to monitor.
  50380. for (var i in _this._babylonGamepads) {
  50381. if (_this._babylonGamepads[i].index === gamepad.index) {
  50382. var gamepadToRemove = _this._babylonGamepads[i];
  50383. _this._babylonGamepads[i] = null;
  50384. _this.onGamepadDisconnectedObservable.notifyObservers(gamepadToRemove);
  50385. gamepadToRemove.dispose();
  50386. break;
  50387. }
  50388. }
  50389. };
  50390. if (this._gamepadSupport) {
  50391. //first add already-connected gamepads
  50392. this._updateGamepadObjects();
  50393. if (this._babylonGamepads.length) {
  50394. this._startMonitoringGamepads();
  50395. }
  50396. // Checking if the gamepad connected event is supported (like in Firefox)
  50397. if (this._gamepadEventSupported) {
  50398. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  50399. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  50400. }
  50401. else {
  50402. this._startMonitoringGamepads();
  50403. }
  50404. }
  50405. }
  50406. GamepadManager.prototype.getGamepadByType = function (type) {
  50407. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  50408. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  50409. var gamepad = _a[_i];
  50410. if (gamepad && gamepad.type === type) {
  50411. return gamepad;
  50412. }
  50413. }
  50414. return null;
  50415. };
  50416. GamepadManager.prototype.dispose = function () {
  50417. if (this._gamepadEventSupported) {
  50418. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  50419. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  50420. this._onGamepadConnectedEvent = null;
  50421. this._onGamepadDisconnectedEvent = null;
  50422. }
  50423. this._oneGamepadConnected = false;
  50424. this._stopMonitoringGamepads();
  50425. this._babylonGamepads = [];
  50426. };
  50427. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  50428. if (!this._oneGamepadConnected) {
  50429. this._oneGamepadConnected = true;
  50430. }
  50431. var newGamepad;
  50432. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  50433. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  50434. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  50435. }
  50436. else if (gamepad.pose) {
  50437. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  50438. }
  50439. else {
  50440. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  50441. }
  50442. this._babylonGamepads[newGamepad.index] = newGamepad;
  50443. return newGamepad;
  50444. };
  50445. GamepadManager.prototype._startMonitoringGamepads = function () {
  50446. if (!this._isMonitoring) {
  50447. this._isMonitoring = true;
  50448. this._checkGamepadsStatus();
  50449. }
  50450. };
  50451. GamepadManager.prototype._stopMonitoringGamepads = function () {
  50452. this._isMonitoring = false;
  50453. };
  50454. GamepadManager.prototype._checkGamepadsStatus = function () {
  50455. var _this = this;
  50456. // Hack to be compatible Chrome
  50457. this._updateGamepadObjects();
  50458. for (var i in this._babylonGamepads) {
  50459. var gamepad = this._babylonGamepads[i];
  50460. if (!gamepad) {
  50461. continue;
  50462. }
  50463. gamepad.update();
  50464. }
  50465. if (this._isMonitoring) {
  50466. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  50467. }
  50468. };
  50469. // This function is called only on Chrome, which does not properly support
  50470. // connection/disconnection events and forces you to recopy again the gamepad object
  50471. GamepadManager.prototype._updateGamepadObjects = function () {
  50472. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  50473. for (var i = 0; i < gamepads.length; i++) {
  50474. if (gamepads[i]) {
  50475. if (!this._babylonGamepads[gamepads[i].index]) {
  50476. var newGamepad = this._addNewGamepad(gamepads[i]);
  50477. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  50478. }
  50479. else {
  50480. // Forced to copy again this object for Chrome for unknown reason
  50481. this._babylonGamepads[i].browserGamepad = gamepads[i];
  50482. }
  50483. }
  50484. }
  50485. };
  50486. return GamepadManager;
  50487. }());
  50488. BABYLON.GamepadManager = GamepadManager;
  50489. })(BABYLON || (BABYLON = {}));
  50490. //# sourceMappingURL=babylon.gamepadManager.js.map
  50491. var BABYLON;
  50492. (function (BABYLON) {
  50493. var StickValues = (function () {
  50494. function StickValues(x, y) {
  50495. this.x = x;
  50496. this.y = y;
  50497. }
  50498. return StickValues;
  50499. }());
  50500. BABYLON.StickValues = StickValues;
  50501. var Gamepad = (function () {
  50502. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  50503. if (leftStickX === void 0) { leftStickX = 0; }
  50504. if (leftStickY === void 0) { leftStickY = 1; }
  50505. if (rightStickX === void 0) { rightStickX = 2; }
  50506. if (rightStickY === void 0) { rightStickY = 3; }
  50507. this.id = id;
  50508. this.index = index;
  50509. this.browserGamepad = browserGamepad;
  50510. this.type = Gamepad.GAMEPAD;
  50511. this._leftStickAxisX = leftStickX;
  50512. this._leftStickAxisY = leftStickY;
  50513. this._rightStickAxisX = rightStickX;
  50514. this._rightStickAxisY = rightStickY;
  50515. if (this.browserGamepad.axes.length >= 2) {
  50516. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50517. }
  50518. if (this.browserGamepad.axes.length >= 4) {
  50519. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50520. }
  50521. }
  50522. Gamepad.prototype.onleftstickchanged = function (callback) {
  50523. this._onleftstickchanged = callback;
  50524. };
  50525. Gamepad.prototype.onrightstickchanged = function (callback) {
  50526. this._onrightstickchanged = callback;
  50527. };
  50528. Object.defineProperty(Gamepad.prototype, "leftStick", {
  50529. get: function () {
  50530. return this._leftStick;
  50531. },
  50532. set: function (newValues) {
  50533. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  50534. this._onleftstickchanged(newValues);
  50535. }
  50536. this._leftStick = newValues;
  50537. },
  50538. enumerable: true,
  50539. configurable: true
  50540. });
  50541. Object.defineProperty(Gamepad.prototype, "rightStick", {
  50542. get: function () {
  50543. return this._rightStick;
  50544. },
  50545. set: function (newValues) {
  50546. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  50547. this._onrightstickchanged(newValues);
  50548. }
  50549. this._rightStick = newValues;
  50550. },
  50551. enumerable: true,
  50552. configurable: true
  50553. });
  50554. Gamepad.prototype.update = function () {
  50555. if (this._leftStick) {
  50556. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  50557. }
  50558. if (this._rightStick) {
  50559. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  50560. }
  50561. };
  50562. Gamepad.prototype.dispose = function () {
  50563. };
  50564. Gamepad.GAMEPAD = 0;
  50565. Gamepad.GENERIC = 1;
  50566. Gamepad.XBOX = 2;
  50567. Gamepad.POSE_ENABLED = 3;
  50568. return Gamepad;
  50569. }());
  50570. BABYLON.Gamepad = Gamepad;
  50571. var GenericPad = (function (_super) {
  50572. __extends(GenericPad, _super);
  50573. function GenericPad(id, index, browserGamepad) {
  50574. var _this = _super.call(this, id, index, browserGamepad) || this;
  50575. _this.type = Gamepad.GENERIC;
  50576. _this._buttons = new Array(browserGamepad.buttons.length);
  50577. return _this;
  50578. }
  50579. GenericPad.prototype.onbuttondown = function (callback) {
  50580. this._onbuttondown = callback;
  50581. };
  50582. GenericPad.prototype.onbuttonup = function (callback) {
  50583. this._onbuttonup = callback;
  50584. };
  50585. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  50586. if (newValue !== currentValue) {
  50587. if (this._onbuttondown && newValue === 1) {
  50588. this._onbuttondown(buttonIndex);
  50589. }
  50590. if (this._onbuttonup && newValue === 0) {
  50591. this._onbuttonup(buttonIndex);
  50592. }
  50593. }
  50594. return newValue;
  50595. };
  50596. GenericPad.prototype.update = function () {
  50597. _super.prototype.update.call(this);
  50598. for (var index = 0; index < this._buttons.length; index++) {
  50599. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  50600. }
  50601. };
  50602. return GenericPad;
  50603. }(Gamepad));
  50604. BABYLON.GenericPad = GenericPad;
  50605. })(BABYLON || (BABYLON = {}));
  50606. //# sourceMappingURL=babylon.gamepad.js.map
  50607. var BABYLON;
  50608. (function (BABYLON) {
  50609. var Xbox360Button;
  50610. (function (Xbox360Button) {
  50611. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  50612. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  50613. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  50614. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  50615. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  50616. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  50617. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  50618. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  50619. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  50620. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  50621. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  50622. var Xbox360Dpad;
  50623. (function (Xbox360Dpad) {
  50624. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  50625. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  50626. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  50627. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  50628. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  50629. var Xbox360Pad = (function (_super) {
  50630. __extends(Xbox360Pad, _super);
  50631. function Xbox360Pad(id, index, gamepad, xboxOne) {
  50632. if (xboxOne === void 0) { xboxOne = false; }
  50633. var _this = _super.call(this, id, index, gamepad, 0, 1, (xboxOne ? 3 : 2), (xboxOne ? 4 : 3)) || this;
  50634. _this._leftTrigger = 0;
  50635. _this._rightTrigger = 0;
  50636. _this._buttonA = 0;
  50637. _this._buttonB = 0;
  50638. _this._buttonX = 0;
  50639. _this._buttonY = 0;
  50640. _this._buttonBack = 0;
  50641. _this._buttonStart = 0;
  50642. _this._buttonLB = 0;
  50643. _this._buttonRB = 0;
  50644. _this._buttonLeftStick = 0;
  50645. _this._buttonRightStick = 0;
  50646. _this._dPadUp = 0;
  50647. _this._dPadDown = 0;
  50648. _this._dPadLeft = 0;
  50649. _this._dPadRight = 0;
  50650. _this._isXboxOnePad = false;
  50651. _this.type = BABYLON.Gamepad.XBOX;
  50652. _this._isXboxOnePad = xboxOne;
  50653. return _this;
  50654. }
  50655. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  50656. this._onlefttriggerchanged = callback;
  50657. };
  50658. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  50659. this._onrighttriggerchanged = callback;
  50660. };
  50661. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  50662. get: function () {
  50663. return this._leftTrigger;
  50664. },
  50665. set: function (newValue) {
  50666. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  50667. this._onlefttriggerchanged(newValue);
  50668. }
  50669. this._leftTrigger = newValue;
  50670. },
  50671. enumerable: true,
  50672. configurable: true
  50673. });
  50674. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  50675. get: function () {
  50676. return this._rightTrigger;
  50677. },
  50678. set: function (newValue) {
  50679. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  50680. this._onrighttriggerchanged(newValue);
  50681. }
  50682. this._rightTrigger = newValue;
  50683. },
  50684. enumerable: true,
  50685. configurable: true
  50686. });
  50687. Xbox360Pad.prototype.onbuttondown = function (callback) {
  50688. this._onbuttondown = callback;
  50689. };
  50690. Xbox360Pad.prototype.onbuttonup = function (callback) {
  50691. this._onbuttonup = callback;
  50692. };
  50693. Xbox360Pad.prototype.ondpaddown = function (callback) {
  50694. this._ondpaddown = callback;
  50695. };
  50696. Xbox360Pad.prototype.ondpadup = function (callback) {
  50697. this._ondpadup = callback;
  50698. };
  50699. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  50700. if (newValue !== currentValue) {
  50701. if (this._onbuttondown && newValue === 1) {
  50702. this._onbuttondown(buttonType);
  50703. }
  50704. if (this._onbuttonup && newValue === 0) {
  50705. this._onbuttonup(buttonType);
  50706. }
  50707. }
  50708. return newValue;
  50709. };
  50710. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  50711. if (newValue !== currentValue) {
  50712. if (this._ondpaddown && newValue === 1) {
  50713. this._ondpaddown(buttonType);
  50714. }
  50715. if (this._ondpadup && newValue === 0) {
  50716. this._ondpadup(buttonType);
  50717. }
  50718. }
  50719. return newValue;
  50720. };
  50721. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  50722. get: function () {
  50723. return this._buttonA;
  50724. },
  50725. set: function (value) {
  50726. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  50727. },
  50728. enumerable: true,
  50729. configurable: true
  50730. });
  50731. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  50732. get: function () {
  50733. return this._buttonB;
  50734. },
  50735. set: function (value) {
  50736. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  50737. },
  50738. enumerable: true,
  50739. configurable: true
  50740. });
  50741. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  50742. get: function () {
  50743. return this._buttonX;
  50744. },
  50745. set: function (value) {
  50746. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  50747. },
  50748. enumerable: true,
  50749. configurable: true
  50750. });
  50751. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  50752. get: function () {
  50753. return this._buttonY;
  50754. },
  50755. set: function (value) {
  50756. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  50757. },
  50758. enumerable: true,
  50759. configurable: true
  50760. });
  50761. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  50762. get: function () {
  50763. return this._buttonStart;
  50764. },
  50765. set: function (value) {
  50766. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  50767. },
  50768. enumerable: true,
  50769. configurable: true
  50770. });
  50771. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  50772. get: function () {
  50773. return this._buttonBack;
  50774. },
  50775. set: function (value) {
  50776. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  50777. },
  50778. enumerable: true,
  50779. configurable: true
  50780. });
  50781. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  50782. get: function () {
  50783. return this._buttonLB;
  50784. },
  50785. set: function (value) {
  50786. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  50787. },
  50788. enumerable: true,
  50789. configurable: true
  50790. });
  50791. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  50792. get: function () {
  50793. return this._buttonRB;
  50794. },
  50795. set: function (value) {
  50796. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  50797. },
  50798. enumerable: true,
  50799. configurable: true
  50800. });
  50801. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  50802. get: function () {
  50803. return this._buttonLeftStick;
  50804. },
  50805. set: function (value) {
  50806. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  50807. },
  50808. enumerable: true,
  50809. configurable: true
  50810. });
  50811. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  50812. get: function () {
  50813. return this._buttonRightStick;
  50814. },
  50815. set: function (value) {
  50816. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  50817. },
  50818. enumerable: true,
  50819. configurable: true
  50820. });
  50821. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  50822. get: function () {
  50823. return this._dPadUp;
  50824. },
  50825. set: function (value) {
  50826. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  50827. },
  50828. enumerable: true,
  50829. configurable: true
  50830. });
  50831. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  50832. get: function () {
  50833. return this._dPadDown;
  50834. },
  50835. set: function (value) {
  50836. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  50837. },
  50838. enumerable: true,
  50839. configurable: true
  50840. });
  50841. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  50842. get: function () {
  50843. return this._dPadLeft;
  50844. },
  50845. set: function (value) {
  50846. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  50847. },
  50848. enumerable: true,
  50849. configurable: true
  50850. });
  50851. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  50852. get: function () {
  50853. return this._dPadRight;
  50854. },
  50855. set: function (value) {
  50856. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  50857. },
  50858. enumerable: true,
  50859. configurable: true
  50860. });
  50861. Xbox360Pad.prototype.update = function () {
  50862. _super.prototype.update.call(this);
  50863. if (this._isXboxOnePad) {
  50864. this.buttonA = this.browserGamepad.buttons[0].value;
  50865. this.buttonB = this.browserGamepad.buttons[1].value;
  50866. this.buttonX = this.browserGamepad.buttons[2].value;
  50867. this.buttonY = this.browserGamepad.buttons[3].value;
  50868. this.buttonLB = this.browserGamepad.buttons[4].value;
  50869. this.buttonRB = this.browserGamepad.buttons[5].value;
  50870. this.leftTrigger = this.browserGamepad.axes[2];
  50871. this.rightTrigger = this.browserGamepad.axes[5];
  50872. this.buttonBack = this.browserGamepad.buttons[9].value;
  50873. this.buttonStart = this.browserGamepad.buttons[8].value;
  50874. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  50875. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  50876. this.dPadUp = this.browserGamepad.buttons[11].value;
  50877. this.dPadDown = this.browserGamepad.buttons[12].value;
  50878. this.dPadLeft = this.browserGamepad.buttons[13].value;
  50879. this.dPadRight = this.browserGamepad.buttons[14].value;
  50880. }
  50881. else {
  50882. this.buttonA = this.browserGamepad.buttons[0].value;
  50883. this.buttonB = this.browserGamepad.buttons[1].value;
  50884. this.buttonX = this.browserGamepad.buttons[2].value;
  50885. this.buttonY = this.browserGamepad.buttons[3].value;
  50886. this.buttonLB = this.browserGamepad.buttons[4].value;
  50887. this.buttonRB = this.browserGamepad.buttons[5].value;
  50888. this.leftTrigger = this.browserGamepad.buttons[6].value;
  50889. this.rightTrigger = this.browserGamepad.buttons[7].value;
  50890. this.buttonBack = this.browserGamepad.buttons[8].value;
  50891. this.buttonStart = this.browserGamepad.buttons[9].value;
  50892. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  50893. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  50894. this.dPadUp = this.browserGamepad.buttons[12].value;
  50895. this.dPadDown = this.browserGamepad.buttons[13].value;
  50896. this.dPadLeft = this.browserGamepad.buttons[14].value;
  50897. this.dPadRight = this.browserGamepad.buttons[15].value;
  50898. }
  50899. };
  50900. return Xbox360Pad;
  50901. }(BABYLON.Gamepad));
  50902. BABYLON.Xbox360Pad = Xbox360Pad;
  50903. })(BABYLON || (BABYLON = {}));
  50904. //# sourceMappingURL=babylon.xboxGamepad.js.map
  50905. var BABYLON;
  50906. (function (BABYLON) {
  50907. var PoseEnabledControllerType;
  50908. (function (PoseEnabledControllerType) {
  50909. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  50910. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  50911. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  50912. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 3] = "GENERIC";
  50913. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  50914. var PoseEnabledControllerHelper = (function () {
  50915. function PoseEnabledControllerHelper() {
  50916. }
  50917. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  50918. // Oculus Touch
  50919. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  50920. return new BABYLON.OculusTouchController(vrGamepad);
  50921. }
  50922. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  50923. return new BABYLON.ViveController(vrGamepad);
  50924. }
  50925. else {
  50926. return new BABYLON.GenericController(vrGamepad);
  50927. }
  50928. };
  50929. return PoseEnabledControllerHelper;
  50930. }());
  50931. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  50932. var PoseEnabledController = (function (_super) {
  50933. __extends(PoseEnabledController, _super);
  50934. function PoseEnabledController(vrGamepad) {
  50935. var _this = _super.call(this, vrGamepad.id, vrGamepad.index, vrGamepad) || this;
  50936. _this.vrGamepad = vrGamepad;
  50937. _this.deviceScaleFactor = 1;
  50938. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  50939. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  50940. _this.controllerType = PoseEnabledControllerType.GENERIC;
  50941. _this.position = BABYLON.Vector3.Zero();
  50942. _this.rotationQuaternion = new BABYLON.Quaternion();
  50943. _this.devicePosition = BABYLON.Vector3.Zero();
  50944. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  50945. _this._calculatedPosition = BABYLON.Vector3.Zero();
  50946. _this._calculatedRotation = new BABYLON.Quaternion();
  50947. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  50948. return _this;
  50949. }
  50950. PoseEnabledController.prototype.update = function () {
  50951. _super.prototype.update.call(this);
  50952. var pose = this.vrGamepad.pose;
  50953. this.updateFromDevice(pose);
  50954. if (this._mesh) {
  50955. this._mesh.position.copyFrom(this._calculatedPosition);
  50956. this._mesh.rotationQuaternion.copyFrom(this._calculatedRotation);
  50957. }
  50958. };
  50959. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  50960. if (poseData) {
  50961. this.rawPose = poseData;
  50962. if (poseData.position) {
  50963. this.devicePosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  50964. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  50965. this.devicePosition.z *= -1;
  50966. }
  50967. this.devicePosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  50968. this._calculatedPosition.addInPlace(this.position);
  50969. }
  50970. if (poseData.orientation) {
  50971. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  50972. if (this._mesh) {
  50973. if (this._mesh.getScene().useRightHandedSystem) {
  50974. this.deviceRotationQuaternion.z *= -1;
  50975. this.deviceRotationQuaternion.w *= -1;
  50976. }
  50977. else {
  50978. this.deviceRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this.deviceRotationQuaternion);
  50979. }
  50980. }
  50981. // if the camera is set, rotate to the camera's rotation
  50982. this.deviceRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  50983. }
  50984. }
  50985. };
  50986. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  50987. if (this._mesh) {
  50988. this._mesh.parent = undefined;
  50989. }
  50990. this._mesh = mesh;
  50991. if (this._poseControlledCamera) {
  50992. this._mesh.parent = this._poseControlledCamera;
  50993. }
  50994. if (!this._mesh.rotationQuaternion) {
  50995. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  50996. }
  50997. };
  50998. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  50999. this._poseControlledCamera = camera;
  51000. if (this._mesh) {
  51001. this._mesh.parent = this._poseControlledCamera;
  51002. }
  51003. };
  51004. PoseEnabledController.prototype.dispose = function () {
  51005. if (this._mesh) {
  51006. this._mesh.dispose();
  51007. }
  51008. this._mesh = undefined;
  51009. _super.prototype.dispose.call(this);
  51010. };
  51011. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  51012. get: function () {
  51013. return this._mesh;
  51014. },
  51015. enumerable: true,
  51016. configurable: true
  51017. });
  51018. PoseEnabledController.prototype.getForwardRay = function (length) {
  51019. if (length === void 0) { length = 100; }
  51020. if (!this.mesh) {
  51021. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  51022. }
  51023. var m = this.mesh.getWorldMatrix();
  51024. var origin = m.getTranslation();
  51025. var forward = new BABYLON.Vector3(0, 0, -1);
  51026. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  51027. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  51028. return new BABYLON.Ray(origin, direction, length);
  51029. };
  51030. return PoseEnabledController;
  51031. }(BABYLON.Gamepad));
  51032. BABYLON.PoseEnabledController = PoseEnabledController;
  51033. })(BABYLON || (BABYLON = {}));
  51034. //# sourceMappingURL=babylon.poseEnabledController.js.map
  51035. var BABYLON;
  51036. (function (BABYLON) {
  51037. var WebVRController = (function (_super) {
  51038. __extends(WebVRController, _super);
  51039. function WebVRController(vrGamepad) {
  51040. var _this = _super.call(this, vrGamepad) || this;
  51041. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  51042. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  51043. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  51044. _this.onPadStateChangedObservable = new BABYLON.Observable();
  51045. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  51046. _this.pad = { x: 0, y: 0 };
  51047. // avoid GC, store state in a tmp object
  51048. _this._changes = {
  51049. pressChanged: false,
  51050. touchChanged: false,
  51051. valueChanged: false,
  51052. changed: false
  51053. };
  51054. _this._buttons = new Array(vrGamepad.buttons.length);
  51055. _this.hand = vrGamepad.hand;
  51056. return _this;
  51057. }
  51058. WebVRController.prototype.onButtonStateChange = function (callback) {
  51059. this._onButtonStateChange = callback;
  51060. };
  51061. WebVRController.prototype.update = function () {
  51062. _super.prototype.update.call(this);
  51063. for (var index = 0; index < this._buttons.length; index++) {
  51064. this._setButtonValue(this.vrGamepad.buttons[index], this._buttons[index], index);
  51065. }
  51066. ;
  51067. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  51068. this.pad.x = this.leftStick.x;
  51069. this.pad.y = this.leftStick.y;
  51070. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  51071. }
  51072. };
  51073. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  51074. if (!newState) {
  51075. newState = {
  51076. pressed: false,
  51077. touched: false,
  51078. value: 0
  51079. };
  51080. }
  51081. if (!currentState) {
  51082. this._buttons[buttonIndex] = {
  51083. pressed: newState.pressed,
  51084. touched: newState.touched,
  51085. value: newState.value
  51086. };
  51087. return;
  51088. }
  51089. this._checkChanges(newState, currentState);
  51090. if (this._changes.changed) {
  51091. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  51092. this.handleButtonChange(buttonIndex, newState, this._changes);
  51093. }
  51094. this._buttons[buttonIndex].pressed = newState.pressed;
  51095. this._buttons[buttonIndex].touched = newState.touched;
  51096. // oculus triggers are never 0, thou not touched.
  51097. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  51098. };
  51099. WebVRController.prototype._checkChanges = function (newState, currentState) {
  51100. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  51101. this._changes.touchChanged = newState.touched !== currentState.touched;
  51102. this._changes.valueChanged = newState.value !== currentState.value;
  51103. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  51104. return this._changes;
  51105. };
  51106. return WebVRController;
  51107. }(BABYLON.PoseEnabledController));
  51108. BABYLON.WebVRController = WebVRController;
  51109. })(BABYLON || (BABYLON = {}));
  51110. //# sourceMappingURL=babylon.webVRController.js.map
  51111. var BABYLON;
  51112. (function (BABYLON) {
  51113. var OculusTouchController = (function (_super) {
  51114. __extends(OculusTouchController, _super);
  51115. function OculusTouchController(vrGamepad) {
  51116. var _this = _super.call(this, vrGamepad) || this;
  51117. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  51118. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  51119. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  51120. return _this;
  51121. }
  51122. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51123. var _this = this;
  51124. var meshName = this.hand === 'right' ? 'RightTouch.babylon' : 'LeftTouch.babylon';
  51125. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", meshName, scene, function (newMeshes) {
  51126. /*
  51127. Parent Mesh name: oculus_touch_left
  51128. - body
  51129. - trigger
  51130. - thumbstick
  51131. - grip
  51132. - button_y
  51133. - button_x
  51134. - button_enter
  51135. */
  51136. _this._defaultModel = newMeshes[1];
  51137. if (meshLoaded) {
  51138. meshLoaded(_this._defaultModel);
  51139. }
  51140. _this.attachToMesh(_this._defaultModel);
  51141. });
  51142. };
  51143. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  51144. // helper getters for left and right hand.
  51145. get: function () {
  51146. if (this.hand === 'right') {
  51147. return this.onMainButtonStateChangedObservable;
  51148. }
  51149. else {
  51150. throw new Error('No A button on left hand');
  51151. }
  51152. },
  51153. enumerable: true,
  51154. configurable: true
  51155. });
  51156. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  51157. get: function () {
  51158. if (this.hand === 'right') {
  51159. return this.onSecondaryButtonStateChangedObservable;
  51160. }
  51161. else {
  51162. throw new Error('No B button on left hand');
  51163. }
  51164. },
  51165. enumerable: true,
  51166. configurable: true
  51167. });
  51168. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  51169. get: function () {
  51170. if (this.hand === 'left') {
  51171. return this.onMainButtonStateChangedObservable;
  51172. }
  51173. else {
  51174. throw new Error('No X button on right hand');
  51175. }
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  51181. get: function () {
  51182. if (this.hand === 'left') {
  51183. return this.onSecondaryButtonStateChangedObservable;
  51184. }
  51185. else {
  51186. throw new Error('No Y button on right hand');
  51187. }
  51188. },
  51189. enumerable: true,
  51190. configurable: true
  51191. });
  51192. /*
  51193. 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  51194. 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  51195. 2) secondary trigger (same)
  51196. 3) A (right) X (left), touch, pressed = value
  51197. 4) B / Y
  51198. 5) thumb rest
  51199. */
  51200. OculusTouchController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51201. var notifyObject = state; //{ state: state, changes: changes };
  51202. var triggerDirection = this.hand === 'right' ? -1 : 1;
  51203. switch (buttonIdx) {
  51204. case 0:
  51205. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51206. return;
  51207. case 1:// index trigger
  51208. if (this._defaultModel) {
  51209. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  51210. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  51211. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  51212. }
  51213. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51214. return;
  51215. case 2:// secondary trigger
  51216. if (this._defaultModel) {
  51217. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  51218. }
  51219. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  51220. return;
  51221. case 3:
  51222. if (this._defaultModel) {
  51223. if (notifyObject.pressed) {
  51224. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  51225. }
  51226. else {
  51227. (this._defaultModel.getChildren()[1]).position.y = 0;
  51228. }
  51229. }
  51230. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51231. return;
  51232. case 4:
  51233. if (this._defaultModel) {
  51234. if (notifyObject.pressed) {
  51235. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51236. }
  51237. else {
  51238. (this._defaultModel.getChildren()[2]).position.y = 0;
  51239. }
  51240. }
  51241. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51242. return;
  51243. case 5:
  51244. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  51245. return;
  51246. }
  51247. };
  51248. return OculusTouchController;
  51249. }(BABYLON.WebVRController));
  51250. BABYLON.OculusTouchController = OculusTouchController;
  51251. })(BABYLON || (BABYLON = {}));
  51252. //# sourceMappingURL=babylon.oculusTouchController.js.map
  51253. var BABYLON;
  51254. (function (BABYLON) {
  51255. var ViveController = (function (_super) {
  51256. __extends(ViveController, _super);
  51257. function ViveController(vrGamepad) {
  51258. var _this = _super.call(this, vrGamepad) || this;
  51259. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  51260. return _this;
  51261. }
  51262. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51263. var _this = this;
  51264. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "ViveWand.babylon", scene, function (newMeshes) {
  51265. /*
  51266. Parent Mesh name: ViveWand
  51267. - body
  51268. - r_gripper
  51269. - l_gripper
  51270. - menu_button
  51271. - system_button
  51272. - trackpad
  51273. - trigger
  51274. - LED
  51275. */
  51276. _this._defaultModel = newMeshes[1];
  51277. if (meshLoaded) {
  51278. meshLoaded(_this._defaultModel);
  51279. }
  51280. _this.attachToMesh(_this._defaultModel);
  51281. });
  51282. };
  51283. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  51284. get: function () {
  51285. return this.onMainButtonStateChangedObservable;
  51286. },
  51287. enumerable: true,
  51288. configurable: true
  51289. });
  51290. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  51291. get: function () {
  51292. return this.onMainButtonStateChangedObservable;
  51293. },
  51294. enumerable: true,
  51295. configurable: true
  51296. });
  51297. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  51298. get: function () {
  51299. return this.onSecondaryButtonStateChangedObservable;
  51300. },
  51301. enumerable: true,
  51302. configurable: true
  51303. });
  51304. /**
  51305. * Vive mapping:
  51306. * 0: touchpad
  51307. * 1: trigger
  51308. * 2: left AND right buttons
  51309. * 3: menu button
  51310. */
  51311. ViveController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51312. var notifyObject = state; //{ state: state, changes: changes };
  51313. switch (buttonIdx) {
  51314. case 0:
  51315. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  51316. return;
  51317. case 1:// index trigger
  51318. if (this._defaultModel) {
  51319. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  51320. }
  51321. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  51322. return;
  51323. case 2:// left AND right button
  51324. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  51325. return;
  51326. case 3:
  51327. if (this._defaultModel) {
  51328. if (notifyObject.pressed) {
  51329. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  51330. }
  51331. else {
  51332. (this._defaultModel.getChildren()[2]).position.y = 0;
  51333. }
  51334. }
  51335. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  51336. return;
  51337. }
  51338. };
  51339. return ViveController;
  51340. }(BABYLON.WebVRController));
  51341. BABYLON.ViveController = ViveController;
  51342. })(BABYLON || (BABYLON = {}));
  51343. //# sourceMappingURL=babylon.viveController.js.map
  51344. var BABYLON;
  51345. (function (BABYLON) {
  51346. var GenericController = (function (_super) {
  51347. __extends(GenericController, _super);
  51348. function GenericController(vrGamepad) {
  51349. return _super.call(this, vrGamepad) || this;
  51350. }
  51351. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  51352. var _this = this;
  51353. BABYLON.SceneLoader.ImportMesh("", "http://yoda.blob.core.windows.net/models/", "genericvrcontroller.babylon", scene, function (newMeshes) {
  51354. _this._defaultModel = newMeshes[1];
  51355. if (meshLoaded) {
  51356. meshLoaded(_this._defaultModel);
  51357. }
  51358. _this.attachToMesh(_this._defaultModel);
  51359. });
  51360. };
  51361. GenericController.prototype.handleButtonChange = function (buttonIdx, state, changes) {
  51362. console.log("Button id: " + buttonIdx + "state: ");
  51363. console.dir(state);
  51364. };
  51365. return GenericController;
  51366. }(BABYLON.WebVRController));
  51367. BABYLON.GenericController = GenericController;
  51368. })(BABYLON || (BABYLON = {}));
  51369. //# sourceMappingURL=babylon.genericController.js.map
  51370. /// <reference path="babylon.targetCamera.ts" />
  51371. var BABYLON;
  51372. (function (BABYLON) {
  51373. var FollowCamera = (function (_super) {
  51374. __extends(FollowCamera, _super);
  51375. function FollowCamera(name, position, scene, lockedTarget) {
  51376. var _this = _super.call(this, name, position, scene) || this;
  51377. _this.radius = 12;
  51378. _this.rotationOffset = 0;
  51379. _this.heightOffset = 4;
  51380. _this.cameraAcceleration = 0.05;
  51381. _this.maxCameraSpeed = 20;
  51382. _this.lockedTarget = lockedTarget;
  51383. return _this;
  51384. }
  51385. FollowCamera.prototype.getRadians = function (degrees) {
  51386. return degrees * Math.PI / 180;
  51387. };
  51388. FollowCamera.prototype.follow = function (cameraTarget) {
  51389. if (!cameraTarget)
  51390. return;
  51391. var yRotation;
  51392. if (cameraTarget.rotationQuaternion) {
  51393. var rotMatrix = new BABYLON.Matrix();
  51394. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  51395. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  51396. }
  51397. else {
  51398. yRotation = cameraTarget.rotation.y;
  51399. }
  51400. var radians = this.getRadians(this.rotationOffset) + yRotation;
  51401. var targetPosition = cameraTarget.getAbsolutePosition();
  51402. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  51403. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  51404. var dx = targetX - this.position.x;
  51405. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  51406. var dz = (targetZ) - this.position.z;
  51407. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  51408. var vy = dy * this.cameraAcceleration;
  51409. var vz = dz * this.cameraAcceleration * 2;
  51410. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  51411. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51412. }
  51413. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  51414. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51415. }
  51416. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  51417. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  51418. }
  51419. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  51420. this.setTarget(targetPosition);
  51421. };
  51422. FollowCamera.prototype._checkInputs = function () {
  51423. _super.prototype._checkInputs.call(this);
  51424. this.follow(this.lockedTarget);
  51425. };
  51426. FollowCamera.prototype.getClassName = function () {
  51427. return "FollowCamera";
  51428. };
  51429. __decorate([
  51430. BABYLON.serialize()
  51431. ], FollowCamera.prototype, "radius", void 0);
  51432. __decorate([
  51433. BABYLON.serialize()
  51434. ], FollowCamera.prototype, "rotationOffset", void 0);
  51435. __decorate([
  51436. BABYLON.serialize()
  51437. ], FollowCamera.prototype, "heightOffset", void 0);
  51438. __decorate([
  51439. BABYLON.serialize()
  51440. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  51441. __decorate([
  51442. BABYLON.serialize()
  51443. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  51444. __decorate([
  51445. BABYLON.serializeAsMeshReference("lockedTargetId")
  51446. ], FollowCamera.prototype, "lockedTarget", void 0);
  51447. return FollowCamera;
  51448. }(BABYLON.TargetCamera));
  51449. BABYLON.FollowCamera = FollowCamera;
  51450. var ArcFollowCamera = (function (_super) {
  51451. __extends(ArcFollowCamera, _super);
  51452. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  51453. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  51454. _this.alpha = alpha;
  51455. _this.beta = beta;
  51456. _this.radius = radius;
  51457. _this.target = target;
  51458. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  51459. _this.follow();
  51460. return _this;
  51461. }
  51462. ArcFollowCamera.prototype.follow = function () {
  51463. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  51464. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  51465. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  51466. var targetPosition = this.target.getAbsolutePosition();
  51467. this.position = targetPosition.add(this._cartesianCoordinates);
  51468. this.setTarget(targetPosition);
  51469. };
  51470. ArcFollowCamera.prototype._checkInputs = function () {
  51471. _super.prototype._checkInputs.call(this);
  51472. this.follow();
  51473. };
  51474. ArcFollowCamera.prototype.getClassName = function () {
  51475. return "ArcFollowCamera";
  51476. };
  51477. return ArcFollowCamera;
  51478. }(BABYLON.TargetCamera));
  51479. BABYLON.ArcFollowCamera = ArcFollowCamera;
  51480. })(BABYLON || (BABYLON = {}));
  51481. //# sourceMappingURL=babylon.followCamera.js.map
  51482. /// <reference path="babylon.touchCamera.ts" />
  51483. var BABYLON;
  51484. (function (BABYLON) {
  51485. // We're mainly based on the logic defined into the FreeCamera code
  51486. var UniversalCamera = (function (_super) {
  51487. __extends(UniversalCamera, _super);
  51488. //-- end properties for backward compatibility for inputs
  51489. function UniversalCamera(name, position, scene) {
  51490. var _this = _super.call(this, name, position, scene) || this;
  51491. _this.inputs.addGamepad();
  51492. return _this;
  51493. }
  51494. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  51495. //-- Begin properties for backward compatibility for inputs
  51496. get: function () {
  51497. var gamepad = this.inputs.attached["gamepad"];
  51498. if (gamepad)
  51499. return gamepad.gamepadAngularSensibility;
  51500. },
  51501. set: function (value) {
  51502. var gamepad = this.inputs.attached["gamepad"];
  51503. if (gamepad)
  51504. gamepad.gamepadAngularSensibility = value;
  51505. },
  51506. enumerable: true,
  51507. configurable: true
  51508. });
  51509. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  51510. get: function () {
  51511. var gamepad = this.inputs.attached["gamepad"];
  51512. if (gamepad)
  51513. return gamepad.gamepadMoveSensibility;
  51514. },
  51515. set: function (value) {
  51516. var gamepad = this.inputs.attached["gamepad"];
  51517. if (gamepad)
  51518. gamepad.gamepadMoveSensibility = value;
  51519. },
  51520. enumerable: true,
  51521. configurable: true
  51522. });
  51523. UniversalCamera.prototype.getClassName = function () {
  51524. return "UniversalCamera";
  51525. };
  51526. return UniversalCamera;
  51527. }(BABYLON.TouchCamera));
  51528. BABYLON.UniversalCamera = UniversalCamera;
  51529. })(BABYLON || (BABYLON = {}));
  51530. //# sourceMappingURL=babylon.universalCamera.js.map
  51531. /// <reference path="babylon.universalCamera.ts" />
  51532. var BABYLON;
  51533. (function (BABYLON) {
  51534. // We're mainly based on the logic defined into the FreeCamera code
  51535. var GamepadCamera = (function (_super) {
  51536. __extends(GamepadCamera, _super);
  51537. //-- end properties for backward compatibility for inputs
  51538. function GamepadCamera(name, position, scene) {
  51539. return _super.call(this, name, position, scene) || this;
  51540. }
  51541. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  51542. //-- Begin properties for backward compatibility for inputs
  51543. get: function () {
  51544. var gamepad = this.inputs.attached["gamepad"];
  51545. if (gamepad)
  51546. return gamepad.gamepadAngularSensibility;
  51547. },
  51548. set: function (value) {
  51549. var gamepad = this.inputs.attached["gamepad"];
  51550. if (gamepad)
  51551. gamepad.gamepadAngularSensibility = value;
  51552. },
  51553. enumerable: true,
  51554. configurable: true
  51555. });
  51556. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  51557. get: function () {
  51558. var gamepad = this.inputs.attached["gamepad"];
  51559. if (gamepad)
  51560. return gamepad.gamepadMoveSensibility;
  51561. },
  51562. set: function (value) {
  51563. var gamepad = this.inputs.attached["gamepad"];
  51564. if (gamepad)
  51565. gamepad.gamepadMoveSensibility = value;
  51566. },
  51567. enumerable: true,
  51568. configurable: true
  51569. });
  51570. GamepadCamera.prototype.getClassName = function () {
  51571. return "GamepadCamera";
  51572. };
  51573. return GamepadCamera;
  51574. }(BABYLON.UniversalCamera));
  51575. BABYLON.GamepadCamera = GamepadCamera;
  51576. })(BABYLON || (BABYLON = {}));
  51577. //# sourceMappingURL=babylon.gamepadCamera.js.map
  51578. var BABYLON;
  51579. (function (BABYLON) {
  51580. var PostProcessRenderPipelineManager = (function () {
  51581. function PostProcessRenderPipelineManager() {
  51582. this._renderPipelines = {};
  51583. }
  51584. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  51585. this._renderPipelines[renderPipeline._name] = renderPipeline;
  51586. };
  51587. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  51588. var renderPipeline = this._renderPipelines[renderPipelineName];
  51589. if (!renderPipeline) {
  51590. return;
  51591. }
  51592. renderPipeline._attachCameras(cameras, unique);
  51593. };
  51594. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  51595. var renderPipeline = this._renderPipelines[renderPipelineName];
  51596. if (!renderPipeline) {
  51597. return;
  51598. }
  51599. renderPipeline._detachCameras(cameras);
  51600. };
  51601. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51602. var renderPipeline = this._renderPipelines[renderPipelineName];
  51603. if (!renderPipeline) {
  51604. return;
  51605. }
  51606. renderPipeline._enableEffect(renderEffectName, cameras);
  51607. };
  51608. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  51609. var renderPipeline = this._renderPipelines[renderPipelineName];
  51610. if (!renderPipeline) {
  51611. return;
  51612. }
  51613. renderPipeline._disableEffect(renderEffectName, cameras);
  51614. };
  51615. PostProcessRenderPipelineManager.prototype.enableDisplayOnlyPassInPipeline = function (renderPipelineName, passName, cameras) {
  51616. var renderPipeline = this._renderPipelines[renderPipelineName];
  51617. if (!renderPipeline) {
  51618. return;
  51619. }
  51620. renderPipeline._enableDisplayOnlyPass(passName, cameras);
  51621. };
  51622. PostProcessRenderPipelineManager.prototype.disableDisplayOnlyPassInPipeline = function (renderPipelineName, cameras) {
  51623. var renderPipeline = this._renderPipelines[renderPipelineName];
  51624. if (!renderPipeline) {
  51625. return;
  51626. }
  51627. renderPipeline._disableDisplayOnlyPass(cameras);
  51628. };
  51629. PostProcessRenderPipelineManager.prototype.update = function () {
  51630. for (var renderPipelineName in this._renderPipelines) {
  51631. var pipeline = this._renderPipelines[renderPipelineName];
  51632. if (!pipeline.isSupported) {
  51633. pipeline.dispose();
  51634. delete this._renderPipelines[renderPipelineName];
  51635. }
  51636. else {
  51637. pipeline._update();
  51638. }
  51639. }
  51640. };
  51641. return PostProcessRenderPipelineManager;
  51642. }());
  51643. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  51644. })(BABYLON || (BABYLON = {}));
  51645. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  51646. var BABYLON;
  51647. (function (BABYLON) {
  51648. var PostProcessRenderPass = (function () {
  51649. function PostProcessRenderPass(scene, name, size, renderList, beforeRender, afterRender) {
  51650. this._enabled = true;
  51651. this._refCount = 0;
  51652. this._name = name;
  51653. this._renderTexture = new BABYLON.RenderTargetTexture(name, size, scene);
  51654. this.setRenderList(renderList);
  51655. this._renderTexture.onBeforeRenderObservable.add(beforeRender);
  51656. this._renderTexture.onAfterRenderObservable.add(afterRender);
  51657. this._scene = scene;
  51658. this._renderList = renderList;
  51659. }
  51660. // private
  51661. PostProcessRenderPass.prototype._incRefCount = function () {
  51662. if (this._refCount === 0) {
  51663. this._scene.customRenderTargets.push(this._renderTexture);
  51664. }
  51665. return ++this._refCount;
  51666. };
  51667. PostProcessRenderPass.prototype._decRefCount = function () {
  51668. this._refCount--;
  51669. if (this._refCount <= 0) {
  51670. this._scene.customRenderTargets.splice(this._scene.customRenderTargets.indexOf(this._renderTexture), 1);
  51671. }
  51672. return this._refCount;
  51673. };
  51674. PostProcessRenderPass.prototype._update = function () {
  51675. this.setRenderList(this._renderList);
  51676. };
  51677. // public
  51678. PostProcessRenderPass.prototype.setRenderList = function (renderList) {
  51679. this._renderTexture.renderList = renderList;
  51680. };
  51681. PostProcessRenderPass.prototype.getRenderTexture = function () {
  51682. return this._renderTexture;
  51683. };
  51684. return PostProcessRenderPass;
  51685. }());
  51686. BABYLON.PostProcessRenderPass = PostProcessRenderPass;
  51687. })(BABYLON || (BABYLON = {}));
  51688. //# sourceMappingURL=babylon.postProcessRenderPass.js.map
  51689. var BABYLON;
  51690. (function (BABYLON) {
  51691. var PostProcessRenderEffect = (function () {
  51692. function PostProcessRenderEffect(engine, name, getPostProcess, singleInstance) {
  51693. this._engine = engine;
  51694. this._name = name;
  51695. this._singleInstance = singleInstance || true;
  51696. this._getPostProcess = getPostProcess;
  51697. this._cameras = [];
  51698. this._indicesForCamera = [];
  51699. this._postProcesses = {};
  51700. this._renderPasses = {};
  51701. this._renderEffectAsPasses = {};
  51702. }
  51703. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  51704. get: function () {
  51705. for (var index in this._postProcesses) {
  51706. if (!this._postProcesses[index].isSupported) {
  51707. return false;
  51708. }
  51709. }
  51710. return true;
  51711. },
  51712. enumerable: true,
  51713. configurable: true
  51714. });
  51715. PostProcessRenderEffect.prototype._update = function () {
  51716. for (var renderPassName in this._renderPasses) {
  51717. this._renderPasses[renderPassName]._update();
  51718. }
  51719. };
  51720. PostProcessRenderEffect.prototype.addPass = function (renderPass) {
  51721. this._renderPasses[renderPass._name] = renderPass;
  51722. this._linkParameters();
  51723. };
  51724. PostProcessRenderEffect.prototype.removePass = function (renderPass) {
  51725. delete this._renderPasses[renderPass._name];
  51726. this._linkParameters();
  51727. };
  51728. PostProcessRenderEffect.prototype.addRenderEffectAsPass = function (renderEffect) {
  51729. this._renderEffectAsPasses[renderEffect._name] = renderEffect;
  51730. this._linkParameters();
  51731. };
  51732. PostProcessRenderEffect.prototype.getPass = function (passName) {
  51733. for (var renderPassName in this._renderPasses) {
  51734. if (renderPassName === passName) {
  51735. return this._renderPasses[passName];
  51736. }
  51737. }
  51738. };
  51739. PostProcessRenderEffect.prototype.emptyPasses = function () {
  51740. this._renderPasses = {};
  51741. this._linkParameters();
  51742. };
  51743. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  51744. var cameraKey;
  51745. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51746. for (var i = 0; i < _cam.length; i++) {
  51747. var camera = _cam[i];
  51748. var cameraName = camera.name;
  51749. if (this._singleInstance) {
  51750. cameraKey = 0;
  51751. }
  51752. else {
  51753. cameraKey = cameraName;
  51754. }
  51755. this._postProcesses[cameraKey] = this._postProcesses[cameraKey] || this._getPostProcess();
  51756. var index = camera.attachPostProcess(this._postProcesses[cameraKey]);
  51757. if (!this._indicesForCamera[cameraName]) {
  51758. this._indicesForCamera[cameraName] = [];
  51759. }
  51760. this._indicesForCamera[cameraName].push(index);
  51761. if (this._cameras.indexOf(camera) === -1) {
  51762. this._cameras[cameraName] = camera;
  51763. }
  51764. for (var passName in this._renderPasses) {
  51765. this._renderPasses[passName]._incRefCount();
  51766. }
  51767. }
  51768. this._linkParameters();
  51769. };
  51770. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  51771. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51772. for (var i = 0; i < _cam.length; i++) {
  51773. var camera = _cam[i];
  51774. var cameraName = camera.name;
  51775. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51776. var index = this._cameras.indexOf(cameraName);
  51777. this._indicesForCamera.splice(index, 1);
  51778. this._cameras.splice(index, 1);
  51779. for (var passName in this._renderPasses) {
  51780. this._renderPasses[passName]._decRefCount();
  51781. }
  51782. }
  51783. };
  51784. PostProcessRenderEffect.prototype._enable = function (cameras) {
  51785. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51786. for (var i = 0; i < _cam.length; i++) {
  51787. var camera = _cam[i];
  51788. var cameraName = camera.name;
  51789. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  51790. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined) {
  51791. cameras[i].attachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName][j]);
  51792. }
  51793. }
  51794. for (var passName in this._renderPasses) {
  51795. this._renderPasses[passName]._incRefCount();
  51796. }
  51797. }
  51798. };
  51799. PostProcessRenderEffect.prototype._disable = function (cameras) {
  51800. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51801. for (var i = 0; i < _cam.length; i++) {
  51802. var camera = _cam[i];
  51803. var cameraName = camera.Name;
  51804. camera.detachPostProcess(this._postProcesses[this._singleInstance ? 0 : cameraName], this._indicesForCamera[cameraName]);
  51805. for (var passName in this._renderPasses) {
  51806. this._renderPasses[passName]._decRefCount();
  51807. }
  51808. }
  51809. };
  51810. PostProcessRenderEffect.prototype.getPostProcess = function (camera) {
  51811. if (this._singleInstance) {
  51812. return this._postProcesses[0];
  51813. }
  51814. else {
  51815. return this._postProcesses[camera.name];
  51816. }
  51817. };
  51818. PostProcessRenderEffect.prototype._linkParameters = function () {
  51819. var _this = this;
  51820. for (var index in this._postProcesses) {
  51821. if (this.applyParameters) {
  51822. this.applyParameters(this._postProcesses[index]);
  51823. }
  51824. this._postProcesses[index].onBeforeRenderObservable.add(function (effect) {
  51825. _this._linkTextures(effect);
  51826. });
  51827. }
  51828. };
  51829. PostProcessRenderEffect.prototype._linkTextures = function (effect) {
  51830. for (var renderPassName in this._renderPasses) {
  51831. effect.setTexture(renderPassName, this._renderPasses[renderPassName].getRenderTexture());
  51832. }
  51833. for (var renderEffectName in this._renderEffectAsPasses) {
  51834. effect.setTextureFromPostProcess(renderEffectName + "Sampler", this._renderEffectAsPasses[renderEffectName].getPostProcess());
  51835. }
  51836. };
  51837. return PostProcessRenderEffect;
  51838. }());
  51839. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  51840. })(BABYLON || (BABYLON = {}));
  51841. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  51842. var BABYLON;
  51843. (function (BABYLON) {
  51844. var PostProcessRenderPipeline = (function () {
  51845. function PostProcessRenderPipeline(engine, name) {
  51846. this._engine = engine;
  51847. this._name = name;
  51848. this._renderEffects = new Array();
  51849. this._renderEffectsForIsolatedPass = new Array();
  51850. this._cameras = [];
  51851. }
  51852. PostProcessRenderPipeline.prototype.getClassName = function () {
  51853. return "PostProcessRenderPipeline";
  51854. };
  51855. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  51856. get: function () {
  51857. for (var renderEffectName in this._renderEffects) {
  51858. if (!this._renderEffects[renderEffectName].isSupported) {
  51859. return false;
  51860. }
  51861. }
  51862. return true;
  51863. },
  51864. enumerable: true,
  51865. configurable: true
  51866. });
  51867. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  51868. this._renderEffects[renderEffect._name] = renderEffect;
  51869. };
  51870. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  51871. var renderEffects = this._renderEffects[renderEffectName];
  51872. if (!renderEffects) {
  51873. return;
  51874. }
  51875. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51876. };
  51877. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  51878. var renderEffects = this._renderEffects[renderEffectName];
  51879. if (!renderEffects) {
  51880. return;
  51881. }
  51882. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  51883. };
  51884. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  51885. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51886. var indicesToDelete = [];
  51887. var i;
  51888. for (i = 0; i < _cam.length; i++) {
  51889. var camera = _cam[i];
  51890. var cameraName = camera.name;
  51891. if (this._cameras.indexOf(camera) === -1) {
  51892. this._cameras[cameraName] = camera;
  51893. }
  51894. else if (unique) {
  51895. indicesToDelete.push(i);
  51896. }
  51897. }
  51898. for (i = 0; i < indicesToDelete.length; i++) {
  51899. cameras.splice(indicesToDelete[i], 1);
  51900. }
  51901. for (var renderEffectName in this._renderEffects) {
  51902. this._renderEffects[renderEffectName]._attachCameras(_cam);
  51903. }
  51904. };
  51905. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  51906. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51907. for (var renderEffectName in this._renderEffects) {
  51908. this._renderEffects[renderEffectName]._detachCameras(_cam);
  51909. }
  51910. for (var i = 0; i < _cam.length; i++) {
  51911. this._cameras.splice(this._cameras.indexOf(_cam[i]), 1);
  51912. }
  51913. };
  51914. PostProcessRenderPipeline.prototype._enableDisplayOnlyPass = function (passName, cameras) {
  51915. var _this = this;
  51916. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51917. var pass = null;
  51918. var renderEffectName;
  51919. for (renderEffectName in this._renderEffects) {
  51920. pass = this._renderEffects[renderEffectName].getPass(passName);
  51921. if (pass != null) {
  51922. break;
  51923. }
  51924. }
  51925. if (pass === null) {
  51926. return;
  51927. }
  51928. for (renderEffectName in this._renderEffects) {
  51929. this._renderEffects[renderEffectName]._disable(_cam);
  51930. }
  51931. pass._name = PostProcessRenderPipeline.PASS_SAMPLER_NAME;
  51932. for (var i = 0; i < _cam.length; i++) {
  51933. var camera = _cam[i];
  51934. var cameraName = camera.name;
  51935. 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); });
  51936. this._renderEffectsForIsolatedPass[cameraName].emptyPasses();
  51937. this._renderEffectsForIsolatedPass[cameraName].addPass(pass);
  51938. this._renderEffectsForIsolatedPass[cameraName]._attachCameras(camera);
  51939. }
  51940. };
  51941. PostProcessRenderPipeline.prototype._disableDisplayOnlyPass = function (cameras) {
  51942. var _this = this;
  51943. var _cam = BABYLON.Tools.MakeArray(cameras || this._cameras);
  51944. for (var i = 0; i < _cam.length; i++) {
  51945. var camera = _cam[i];
  51946. var cameraName = camera.name;
  51947. 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); });
  51948. this._renderEffectsForIsolatedPass[cameraName]._disable(camera);
  51949. }
  51950. for (var renderEffectName in this._renderEffects) {
  51951. this._renderEffects[renderEffectName]._enable(_cam);
  51952. }
  51953. };
  51954. PostProcessRenderPipeline.prototype._update = function () {
  51955. for (var renderEffectName in this._renderEffects) {
  51956. this._renderEffects[renderEffectName]._update();
  51957. }
  51958. for (var i = 0; i < this._cameras.length; i++) {
  51959. var cameraName = this._cameras[i].name;
  51960. if (this._renderEffectsForIsolatedPass[cameraName]) {
  51961. this._renderEffectsForIsolatedPass[cameraName]._update();
  51962. }
  51963. }
  51964. };
  51965. PostProcessRenderPipeline.prototype._reset = function () {
  51966. this._renderEffects = new Array();
  51967. this._renderEffectsForIsolatedPass = new Array();
  51968. };
  51969. PostProcessRenderPipeline.prototype.dispose = function () {
  51970. // Must be implemented by children
  51971. };
  51972. PostProcessRenderPipeline.PASS_EFFECT_NAME = "passEffect";
  51973. PostProcessRenderPipeline.PASS_SAMPLER_NAME = "passSampler";
  51974. __decorate([
  51975. BABYLON.serialize()
  51976. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  51977. return PostProcessRenderPipeline;
  51978. }());
  51979. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  51980. })(BABYLON || (BABYLON = {}));
  51981. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  51982. var BABYLON;
  51983. (function (BABYLON) {
  51984. var DepthRenderer = (function () {
  51985. function DepthRenderer(scene, type) {
  51986. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  51987. var _this = this;
  51988. this._viewMatrix = BABYLON.Matrix.Zero();
  51989. this._projectionMatrix = BABYLON.Matrix.Zero();
  51990. this._transformMatrix = BABYLON.Matrix.Zero();
  51991. this._worldViewProjection = BABYLON.Matrix.Zero();
  51992. this._scene = scene;
  51993. var engine = scene.getEngine();
  51994. // Render target
  51995. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  51996. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51997. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  51998. this._depthMap.refreshRate = 1;
  51999. this._depthMap.renderParticles = false;
  52000. this._depthMap.renderList = null;
  52001. // set default depth value to 1.0 (far away)
  52002. this._depthMap.onClearObservable.add(function (engine) {
  52003. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  52004. });
  52005. // Custom render function
  52006. var renderSubMesh = function (subMesh) {
  52007. var mesh = subMesh.getRenderingMesh();
  52008. var scene = _this._scene;
  52009. var engine = scene.getEngine();
  52010. // Culling
  52011. engine.setState(subMesh.getMaterial().backFaceCulling);
  52012. // Managing instances
  52013. var batch = mesh._getInstancesRenderList(subMesh._id);
  52014. if (batch.mustReturn) {
  52015. return;
  52016. }
  52017. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  52018. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  52019. engine.enableEffect(_this._effect);
  52020. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  52021. var material = subMesh.getMaterial();
  52022. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  52023. _this._effect.setFloat2("depthValues", scene.activeCamera.minZ, scene.activeCamera.minZ + scene.activeCamera.maxZ);
  52024. // Alpha test
  52025. if (material && material.needAlphaTesting()) {
  52026. var alphaTexture = material.getAlphaTestTexture();
  52027. _this._effect.setTexture("diffuseSampler", alphaTexture);
  52028. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  52029. }
  52030. // Bones
  52031. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52032. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  52033. }
  52034. // Draw
  52035. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  52036. }
  52037. };
  52038. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  52039. var index;
  52040. for (index = 0; index < opaqueSubMeshes.length; index++) {
  52041. renderSubMesh(opaqueSubMeshes.data[index]);
  52042. }
  52043. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  52044. renderSubMesh(alphaTestSubMeshes.data[index]);
  52045. }
  52046. };
  52047. }
  52048. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  52049. var material = subMesh.getMaterial();
  52050. if (material.disableDepthWrite) {
  52051. return false;
  52052. }
  52053. var defines = [];
  52054. var attribs = [BABYLON.VertexBuffer.PositionKind];
  52055. var mesh = subMesh.getMesh();
  52056. var scene = mesh.getScene();
  52057. // Alpha test
  52058. if (material && material.needAlphaTesting()) {
  52059. defines.push("#define ALPHATEST");
  52060. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  52061. attribs.push(BABYLON.VertexBuffer.UVKind);
  52062. defines.push("#define UV1");
  52063. }
  52064. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  52065. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  52066. defines.push("#define UV2");
  52067. }
  52068. }
  52069. // Bones
  52070. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  52071. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  52072. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  52073. if (mesh.numBoneInfluencers > 4) {
  52074. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  52075. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  52076. }
  52077. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  52078. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  52079. }
  52080. else {
  52081. defines.push("#define NUM_BONE_INFLUENCERS 0");
  52082. }
  52083. // Instances
  52084. if (useInstances) {
  52085. defines.push("#define INSTANCES");
  52086. attribs.push("world0");
  52087. attribs.push("world1");
  52088. attribs.push("world2");
  52089. attribs.push("world3");
  52090. }
  52091. // Get correct effect
  52092. var join = defines.join("\n");
  52093. if (this._cachedDefines !== join) {
  52094. this._cachedDefines = join;
  52095. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  52096. }
  52097. return this._effect.isReady();
  52098. };
  52099. DepthRenderer.prototype.getDepthMap = function () {
  52100. return this._depthMap;
  52101. };
  52102. // Methods
  52103. DepthRenderer.prototype.dispose = function () {
  52104. this._depthMap.dispose();
  52105. };
  52106. return DepthRenderer;
  52107. }());
  52108. BABYLON.DepthRenderer = DepthRenderer;
  52109. })(BABYLON || (BABYLON = {}));
  52110. //# sourceMappingURL=babylon.depthRenderer.js.map
  52111. var BABYLON;
  52112. (function (BABYLON) {
  52113. var SSAORenderingPipeline = (function (_super) {
  52114. __extends(SSAORenderingPipeline, _super);
  52115. /**
  52116. * @constructor
  52117. * @param {string} name - The rendering pipeline name
  52118. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52119. * @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 }
  52120. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52121. */
  52122. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  52123. var _this = _super.call(this, scene.getEngine(), name) || this;
  52124. // Members
  52125. /**
  52126. * The PassPostProcess id in the pipeline that contains the original scene color
  52127. * @type {string}
  52128. */
  52129. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52130. /**
  52131. * The SSAO PostProcess id in the pipeline
  52132. * @type {string}
  52133. */
  52134. _this.SSAORenderEffect = "SSAORenderEffect";
  52135. /**
  52136. * The horizontal blur PostProcess id in the pipeline
  52137. * @type {string}
  52138. */
  52139. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52140. /**
  52141. * The vertical blur PostProcess id in the pipeline
  52142. * @type {string}
  52143. */
  52144. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52145. /**
  52146. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52147. * @type {string}
  52148. */
  52149. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52150. /**
  52151. * The output strength of the SSAO post-process. Default value is 1.0.
  52152. * @type {number}
  52153. */
  52154. _this.totalStrength = 1.0;
  52155. /**
  52156. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  52157. * @type {number}
  52158. */
  52159. _this.radius = 0.0001;
  52160. /**
  52161. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  52162. * Must not be equal to fallOff and superior to fallOff.
  52163. * Default value is 0.975
  52164. * @type {number}
  52165. */
  52166. _this.area = 0.0075;
  52167. /**
  52168. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  52169. * Must not be equal to area and inferior to area.
  52170. * Default value is 0.0
  52171. * @type {number}
  52172. */
  52173. _this.fallOff = 0.000001;
  52174. /**
  52175. * The base color of the SSAO post-process
  52176. * The final result is "base + ssao" between [0, 1]
  52177. * @type {number}
  52178. */
  52179. _this.base = 0.5;
  52180. _this._firstUpdate = true;
  52181. _this._scene = scene;
  52182. // Set up assets
  52183. _this._createRandomTexture();
  52184. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52185. var ssaoRatio = ratio.ssaoRatio || ratio;
  52186. var combineRatio = ratio.combineRatio || ratio;
  52187. _this._ratio = {
  52188. ssaoRatio: ssaoRatio,
  52189. combineRatio: combineRatio
  52190. };
  52191. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52192. _this._createSSAOPostProcess(ssaoRatio);
  52193. _this._createBlurPostProcess(ssaoRatio);
  52194. _this._createSSAOCombinePostProcess(combineRatio);
  52195. // Set up pipeline
  52196. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52197. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52198. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52199. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52200. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52201. // Finish
  52202. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52203. if (cameras)
  52204. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52205. return _this;
  52206. }
  52207. // Public Methods
  52208. /**
  52209. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52210. */
  52211. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52212. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52213. for (var i = 0; i < this._scene.cameras.length; i++) {
  52214. var camera = this._scene.cameras[i];
  52215. this._originalColorPostProcess.dispose(camera);
  52216. this._ssaoPostProcess.dispose(camera);
  52217. this._blurHPostProcess.dispose(camera);
  52218. this._blurVPostProcess.dispose(camera);
  52219. this._ssaoCombinePostProcess.dispose(camera);
  52220. }
  52221. this._randomTexture.dispose();
  52222. if (disableDepthRender)
  52223. this._scene.disableDepthRenderer();
  52224. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52225. _super.prototype.dispose.call(this);
  52226. };
  52227. // Private Methods
  52228. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  52229. var _this = this;
  52230. /*
  52231. var samplerOffsets = [
  52232. -8.0, -6.0, -4.0, -2.0,
  52233. 0.0,
  52234. 2.0, 4.0, 6.0, 8.0
  52235. ];
  52236. */
  52237. var samples = 16;
  52238. var samplerOffsets = [];
  52239. for (var i = -8; i < 8; i++) {
  52240. samplerOffsets.push(i * 2);
  52241. }
  52242. 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");
  52243. this._blurHPostProcess.onApply = function (effect) {
  52244. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52245. effect.setTexture("depthSampler", _this._depthTexture);
  52246. if (_this._firstUpdate) {
  52247. effect.setArray("samplerOffsets", samplerOffsets);
  52248. }
  52249. };
  52250. 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");
  52251. this._blurVPostProcess.onApply = function (effect) {
  52252. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52253. effect.setTexture("depthSampler", _this._depthTexture);
  52254. if (_this._firstUpdate) {
  52255. effect.setArray("samplerOffsets", samplerOffsets);
  52256. _this._firstUpdate = false;
  52257. }
  52258. };
  52259. };
  52260. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52261. var _this = this;
  52262. var numSamples = 16;
  52263. var sampleSphere = [
  52264. 0.5381, 0.1856, -0.4319,
  52265. 0.1379, 0.2486, 0.4430,
  52266. 0.3371, 0.5679, -0.0057,
  52267. -0.6999, -0.0451, -0.0019,
  52268. 0.0689, -0.1598, -0.8547,
  52269. 0.0560, 0.0069, -0.1843,
  52270. -0.0146, 0.1402, 0.0762,
  52271. 0.0100, -0.1924, -0.0344,
  52272. -0.3577, -0.5301, -0.4358,
  52273. -0.3169, 0.1063, 0.0158,
  52274. 0.0103, -0.5869, 0.0046,
  52275. -0.0897, -0.4940, 0.3287,
  52276. 0.7119, -0.0154, -0.0918,
  52277. -0.0533, 0.0596, -0.5411,
  52278. 0.0352, -0.0631, 0.5460,
  52279. -0.4776, 0.2847, -0.0271
  52280. ];
  52281. var samplesFactor = 1.0 / numSamples;
  52282. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  52283. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52284. "area", "fallOff", "base", "range", "viewport"
  52285. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52286. var viewport = new BABYLON.Vector2(0, 0);
  52287. this._ssaoPostProcess.onApply = function (effect) {
  52288. if (_this._firstUpdate) {
  52289. effect.setArray3("sampleSphere", sampleSphere);
  52290. effect.setFloat("samplesFactor", samplesFactor);
  52291. effect.setFloat("randTextureTiles", 4.0);
  52292. }
  52293. effect.setFloat("totalStrength", _this.totalStrength);
  52294. effect.setFloat("radius", _this.radius);
  52295. effect.setFloat("area", _this.area);
  52296. effect.setFloat("fallOff", _this.fallOff);
  52297. effect.setFloat("base", _this.base);
  52298. effect.setTexture("textureSampler", _this._depthTexture);
  52299. effect.setTexture("randomSampler", _this._randomTexture);
  52300. };
  52301. };
  52302. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52303. var _this = this;
  52304. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52305. this._ssaoCombinePostProcess.onApply = function (effect) {
  52306. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52307. };
  52308. };
  52309. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  52310. var size = 512;
  52311. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52312. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52313. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52314. var context = this._randomTexture.getContext();
  52315. var rand = function (min, max) {
  52316. return Math.random() * (max - min) + min;
  52317. };
  52318. var randVector = BABYLON.Vector3.Zero();
  52319. for (var x = 0; x < size; x++) {
  52320. for (var y = 0; y < size; y++) {
  52321. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  52322. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  52323. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  52324. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52325. context.fillRect(x, y, 1, 1);
  52326. }
  52327. }
  52328. this._randomTexture.update(false);
  52329. };
  52330. __decorate([
  52331. BABYLON.serialize()
  52332. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  52333. __decorate([
  52334. BABYLON.serialize()
  52335. ], SSAORenderingPipeline.prototype, "radius", void 0);
  52336. __decorate([
  52337. BABYLON.serialize()
  52338. ], SSAORenderingPipeline.prototype, "area", void 0);
  52339. __decorate([
  52340. BABYLON.serialize()
  52341. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  52342. __decorate([
  52343. BABYLON.serialize()
  52344. ], SSAORenderingPipeline.prototype, "base", void 0);
  52345. __decorate([
  52346. BABYLON.serialize()
  52347. ], SSAORenderingPipeline.prototype, "_ratio", void 0);
  52348. return SSAORenderingPipeline;
  52349. }(BABYLON.PostProcessRenderPipeline));
  52350. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  52351. })(BABYLON || (BABYLON = {}));
  52352. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  52353. var BABYLON;
  52354. (function (BABYLON) {
  52355. var SSAO2RenderingPipeline = (function (_super) {
  52356. __extends(SSAO2RenderingPipeline, _super);
  52357. /**
  52358. * @constructor
  52359. * @param {string} name - The rendering pipeline name
  52360. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52361. * @param {any} ratio - The size of the postprocesses. Can be a number shared between passes or an object for more precision: { ssaoRatio: 0.5, blurRatio: 1.0 }
  52362. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52363. */
  52364. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  52365. var _this = _super.call(this, scene.getEngine(), name) || this;
  52366. // Members
  52367. /**
  52368. * The PassPostProcess id in the pipeline that contains the original scene color
  52369. * @type {string}
  52370. */
  52371. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  52372. /**
  52373. * The SSAO PostProcess id in the pipeline
  52374. * @type {string}
  52375. */
  52376. _this.SSAORenderEffect = "SSAORenderEffect";
  52377. /**
  52378. * The horizontal blur PostProcess id in the pipeline
  52379. * @type {string}
  52380. */
  52381. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  52382. /**
  52383. * The vertical blur PostProcess id in the pipeline
  52384. * @type {string}
  52385. */
  52386. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  52387. /**
  52388. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  52389. * @type {string}
  52390. */
  52391. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  52392. /**
  52393. * The output strength of the SSAO post-process. Default value is 1.0.
  52394. * @type {number}
  52395. */
  52396. _this.totalStrength = 1.0;
  52397. /**
  52398. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  52399. * @type {number}
  52400. */
  52401. _this.maxZ = 100.0;
  52402. /**
  52403. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  52404. * @type {number}
  52405. */
  52406. _this.minZAspect = 0.2;
  52407. /**
  52408. * Number of samples used for the SSAO calculations. Default value is 8
  52409. * @type {number}
  52410. */
  52411. _this._samples = 8;
  52412. /**
  52413. * Are we using bilateral blur ?
  52414. * @type {boolean}
  52415. */
  52416. _this._expensiveBlur = true;
  52417. /**
  52418. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  52419. * @type {number}
  52420. */
  52421. _this.radius = 2.0;
  52422. /**
  52423. * The base color of the SSAO post-process
  52424. * The final result is "base + ssao" between [0, 1]
  52425. * @type {number}
  52426. */
  52427. _this.base = 0.1;
  52428. _this._firstUpdate = true;
  52429. _this._scene = scene;
  52430. if (!_this.isSupported) {
  52431. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  52432. return _this;
  52433. }
  52434. var ssaoRatio = ratio.ssaoRatio || ratio;
  52435. var blurRatio = ratio.blurRatio || ratio;
  52436. _this._ratio = {
  52437. ssaoRatio: ssaoRatio,
  52438. blurRatio: blurRatio
  52439. };
  52440. // Set up assets
  52441. _this._createRandomTexture();
  52442. _this._depthTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[0];
  52443. _this._normalTexture = scene.enableGeometryBufferRenderer().getGBuffer().textures[1];
  52444. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  52445. _this._createSSAOPostProcess(1.0);
  52446. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  52447. _this._createSSAOCombinePostProcess(blurRatio);
  52448. // Set up pipeline
  52449. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  52450. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  52451. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  52452. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  52453. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  52454. // Finish
  52455. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52456. if (cameras)
  52457. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52458. return _this;
  52459. }
  52460. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  52461. get: function () {
  52462. return this._samples;
  52463. },
  52464. set: function (n) {
  52465. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  52466. this._samples = n;
  52467. this._sampleSphere = this._generateHemisphere();
  52468. this._firstUpdate = true;
  52469. },
  52470. enumerable: true,
  52471. configurable: true
  52472. });
  52473. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  52474. get: function () {
  52475. return this._expensiveBlur;
  52476. },
  52477. set: function (b) {
  52478. this._blurHPostProcess.updateEffect("#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52479. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  52480. this._expensiveBlur = b;
  52481. this._firstUpdate = true;
  52482. },
  52483. enumerable: true,
  52484. configurable: true
  52485. });
  52486. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  52487. /**
  52488. * Support test.
  52489. * @type {boolean}
  52490. */
  52491. get: function () {
  52492. var engine = BABYLON.Engine.LastCreatedEngine;
  52493. return engine.webGLVersion > 1;
  52494. },
  52495. enumerable: true,
  52496. configurable: true
  52497. });
  52498. // Public Methods
  52499. /**
  52500. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  52501. */
  52502. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  52503. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  52504. for (var i = 0; i < this._scene.cameras.length; i++) {
  52505. var camera = this._scene.cameras[i];
  52506. this._originalColorPostProcess.dispose(camera);
  52507. this._ssaoPostProcess.dispose(camera);
  52508. this._blurHPostProcess.dispose(camera);
  52509. this._blurVPostProcess.dispose(camera);
  52510. this._ssaoCombinePostProcess.dispose(camera);
  52511. }
  52512. this._randomTexture.dispose();
  52513. if (disableGeometryBufferRenderer)
  52514. this._scene.disableGeometryBufferRenderer();
  52515. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52516. _super.prototype.dispose.call(this);
  52517. };
  52518. // Private Methods
  52519. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  52520. var _this = this;
  52521. var samples = 16;
  52522. this._samplerOffsets = [];
  52523. var expensive = this.expensiveBlur;
  52524. for (var i = -8; i < 8; i++) {
  52525. this._samplerOffsets.push(i * 2 + 0.5);
  52526. }
  52527. this._blurHPostProcess = new BABYLON.PostProcess("BlurH", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], ssaoRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_H\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  52528. this._blurHPostProcess.onApply = function (effect) {
  52529. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width);
  52530. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52531. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52532. effect.setFloat("radius", _this.radius);
  52533. effect.setTexture("depthSampler", _this._depthTexture);
  52534. if (_this._firstUpdate) {
  52535. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52536. }
  52537. };
  52538. this._blurVPostProcess = new BABYLON.PostProcess("BlurV", "ssao2", ["outSize", "samplerOffsets", "near", "far", "radius"], ["depthSampler"], blurRatio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define BILATERAL_BLUR\n#define BILATERAL_BLUR_V\n#define SAMPLES 16\n#define EXPENSIVE " + (expensive ? "1" : "0") + "\n");
  52539. this._blurVPostProcess.onApply = function (effect) {
  52540. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height);
  52541. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52542. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52543. effect.setFloat("radius", _this.radius);
  52544. effect.setTexture("depthSampler", _this._depthTexture);
  52545. if (_this._firstUpdate) {
  52546. effect.setArray("samplerOffsets", _this._samplerOffsets);
  52547. _this._firstUpdate = false;
  52548. }
  52549. };
  52550. };
  52551. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  52552. var numSamples = this.samples;
  52553. var result = [];
  52554. var vector, scale;
  52555. var rand = function (min, max) {
  52556. return Math.random() * (max - min) + min;
  52557. };
  52558. var lerp = function (start, end, percent) {
  52559. return (start + percent * (end - start));
  52560. };
  52561. var i = 0;
  52562. var normal = new BABYLON.Vector3(0, 0, 1);
  52563. while (i < numSamples) {
  52564. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  52565. vector.normalize();
  52566. scale = i / numSamples;
  52567. scale = lerp(0.1, 1.0, scale * scale);
  52568. vector.scaleInPlace(scale);
  52569. result.push(vector.x, vector.y, vector.z);
  52570. i++;
  52571. }
  52572. return result;
  52573. };
  52574. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  52575. var _this = this;
  52576. var numSamples = this.samples;
  52577. this._sampleSphere = this._generateHemisphere();
  52578. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  52579. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  52580. "base", "range", "projection", "near", "far", "texelSize",
  52581. "xViewport", "yViewport", "maxZ", "minZAspect"
  52582. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  52583. this._ssaoPostProcess.onApply = function (effect) {
  52584. if (_this._firstUpdate) {
  52585. effect.setArray3("sampleSphere", _this._sampleSphere);
  52586. effect.setFloat("randTextureTiles", 4.0);
  52587. }
  52588. effect.setFloat("samplesFactor", 1 / _this.samples);
  52589. effect.setFloat("totalStrength", _this.totalStrength);
  52590. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  52591. effect.setFloat("radius", _this.radius);
  52592. effect.setFloat("maxZ", _this.maxZ);
  52593. effect.setFloat("minZAspect", _this.minZAspect);
  52594. effect.setFloat("base", _this.base);
  52595. effect.setFloat("near", _this._scene.activeCamera.minZ);
  52596. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  52597. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  52598. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  52599. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  52600. effect.setTexture("textureSampler", _this._depthTexture);
  52601. effect.setTexture("normalSampler", _this._normalTexture);
  52602. effect.setTexture("randomSampler", _this._randomTexture);
  52603. };
  52604. };
  52605. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  52606. var _this = this;
  52607. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52608. this._ssaoCombinePostProcess.onApply = function (effect) {
  52609. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  52610. };
  52611. };
  52612. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  52613. var size = 512;
  52614. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  52615. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52616. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52617. var context = this._randomTexture.getContext();
  52618. var rand = function (min, max) {
  52619. return Math.random() * (max - min) + min;
  52620. };
  52621. var randVector = BABYLON.Vector3.Zero();
  52622. for (var x = 0; x < size; x++) {
  52623. for (var y = 0; y < size; y++) {
  52624. randVector.x = rand(0.0, 1.0);
  52625. randVector.y = rand(0.0, 1.0);
  52626. randVector.z = 0.0;
  52627. randVector.normalize();
  52628. randVector.scaleInPlace(255);
  52629. randVector.x = Math.floor(randVector.x);
  52630. randVector.y = Math.floor(randVector.y);
  52631. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  52632. context.fillRect(x, y, 1, 1);
  52633. }
  52634. }
  52635. this._randomTexture.update(false);
  52636. };
  52637. __decorate([
  52638. BABYLON.serialize()
  52639. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  52640. __decorate([
  52641. BABYLON.serialize()
  52642. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  52643. __decorate([
  52644. BABYLON.serialize()
  52645. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  52646. __decorate([
  52647. BABYLON.serialize("samples")
  52648. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  52649. __decorate([
  52650. BABYLON.serialize("expensiveBlur")
  52651. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  52652. __decorate([
  52653. BABYLON.serialize()
  52654. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  52655. __decorate([
  52656. BABYLON.serialize()
  52657. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  52658. __decorate([
  52659. BABYLON.serialize()
  52660. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  52661. return SSAO2RenderingPipeline;
  52662. }(BABYLON.PostProcessRenderPipeline));
  52663. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  52664. })(BABYLON || (BABYLON = {}));
  52665. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  52666. // BABYLON.JS Chromatic Aberration GLSL Shader
  52667. // Author: Olivier Guyot
  52668. // Separates very slightly R, G and B colors on the edges of the screen
  52669. // Inspired by Francois Tarlier & Martins Upitis
  52670. var BABYLON;
  52671. (function (BABYLON) {
  52672. var LensRenderingPipeline = (function (_super) {
  52673. __extends(LensRenderingPipeline, _super);
  52674. /**
  52675. * @constructor
  52676. *
  52677. * Effect parameters are as follow:
  52678. * {
  52679. * chromatic_aberration: number; // from 0 to x (1 for realism)
  52680. * edge_blur: number; // from 0 to x (1 for realism)
  52681. * distortion: number; // from 0 to x (1 for realism)
  52682. * grain_amount: number; // from 0 to 1
  52683. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  52684. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  52685. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  52686. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  52687. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  52688. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  52689. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  52690. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  52691. * }
  52692. * Note: if an effect parameter is unset, effect is disabled
  52693. *
  52694. * @param {string} name - The rendering pipeline name
  52695. * @param {object} parameters - An object containing all parameters (see above)
  52696. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52697. * @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)
  52698. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52699. */
  52700. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  52701. if (ratio === void 0) { ratio = 1.0; }
  52702. var _this = _super.call(this, scene.getEngine(), name) || this;
  52703. // Lens effects can be of the following:
  52704. // - chromatic aberration (slight shift of RGB colors)
  52705. // - blur on the edge of the lens
  52706. // - lens distortion
  52707. // - depth-of-field blur & highlights enhancing
  52708. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  52709. // - grain effect (noise or custom texture)
  52710. // Two additional texture samplers are needed:
  52711. // - depth map (for depth-of-field)
  52712. // - grain texture
  52713. /**
  52714. * The chromatic aberration PostProcess id in the pipeline
  52715. * @type {string}
  52716. */
  52717. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  52718. /**
  52719. * The highlights enhancing PostProcess id in the pipeline
  52720. * @type {string}
  52721. */
  52722. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  52723. /**
  52724. * The depth-of-field PostProcess id in the pipeline
  52725. * @type {string}
  52726. */
  52727. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  52728. _this._scene = scene;
  52729. // Fetch texture samplers
  52730. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  52731. if (parameters.grain_texture) {
  52732. _this._grainTexture = parameters.grain_texture;
  52733. }
  52734. else {
  52735. _this._createGrainTexture();
  52736. }
  52737. // save parameters
  52738. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  52739. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  52740. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  52741. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  52742. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  52743. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  52744. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  52745. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  52746. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  52747. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  52748. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  52749. // Create effects
  52750. _this._createChromaticAberrationPostProcess(ratio);
  52751. _this._createHighlightsPostProcess(ratio);
  52752. _this._createDepthOfFieldPostProcess(ratio / 4);
  52753. // Set up pipeline
  52754. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  52755. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  52756. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  52757. if (_this._highlightsGain === -1) {
  52758. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  52759. }
  52760. // Finish
  52761. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52762. if (cameras) {
  52763. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  52764. }
  52765. return _this;
  52766. }
  52767. // public methods (self explanatory)
  52768. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  52769. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  52770. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  52771. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  52772. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  52773. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  52774. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  52775. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  52776. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  52777. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  52778. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  52779. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  52780. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  52781. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  52782. };
  52783. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  52784. this._highlightsPostProcess.updateEffect();
  52785. };
  52786. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  52787. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  52788. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  52789. this._highlightsGain = amount;
  52790. };
  52791. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  52792. if (this._highlightsGain === -1) {
  52793. this._highlightsGain = 1.0;
  52794. }
  52795. this._highlightsThreshold = amount;
  52796. };
  52797. LensRenderingPipeline.prototype.disableHighlights = function () {
  52798. this._highlightsGain = -1;
  52799. };
  52800. /**
  52801. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  52802. */
  52803. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  52804. if (disableDepthRender === void 0) { disableDepthRender = false; }
  52805. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  52806. this._chromaticAberrationPostProcess = undefined;
  52807. this._highlightsPostProcess = undefined;
  52808. this._depthOfFieldPostProcess = undefined;
  52809. this._grainTexture.dispose();
  52810. if (disableDepthRender)
  52811. this._scene.disableDepthRenderer();
  52812. };
  52813. // colors shifting and distortion
  52814. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  52815. var _this = this;
  52816. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height"], // uniforms
  52817. [], // samplers
  52818. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52819. this._chromaticAberrationPostProcess.onApply = function (effect) {
  52820. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  52821. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52822. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52823. };
  52824. };
  52825. // highlights enhancing
  52826. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  52827. var _this = this;
  52828. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  52829. [], // samplers
  52830. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  52831. this._highlightsPostProcess.onApply = function (effect) {
  52832. effect.setFloat('gain', _this._highlightsGain);
  52833. effect.setFloat('threshold', _this._highlightsThreshold);
  52834. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  52835. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52836. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52837. };
  52838. };
  52839. // colors shifting and distortion
  52840. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  52841. var _this = this;
  52842. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  52843. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  52844. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  52845. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  52846. this._depthOfFieldPostProcess.onApply = function (effect) {
  52847. effect.setTexture("depthSampler", _this._depthTexture);
  52848. effect.setTexture("grainSampler", _this._grainTexture);
  52849. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  52850. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  52851. effect.setFloat('grain_amount', _this._grainAmount);
  52852. effect.setBool('blur_noise', _this._blurNoise);
  52853. effect.setFloat('screen_width', _this._scene.getEngine().getRenderingCanvas().width);
  52854. effect.setFloat('screen_height', _this._scene.getEngine().getRenderingCanvas().height);
  52855. effect.setFloat('distortion', _this._distortion);
  52856. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  52857. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  52858. effect.setFloat('aperture', _this._dofAperture);
  52859. effect.setFloat('darken', _this._dofDarken);
  52860. effect.setFloat('edge_blur', _this._edgeBlur);
  52861. effect.setBool('highlights', (_this._highlightsGain !== -1));
  52862. effect.setFloat('near', _this._scene.activeCamera.minZ);
  52863. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  52864. };
  52865. };
  52866. // creates a black and white random noise texture, 512x512
  52867. LensRenderingPipeline.prototype._createGrainTexture = function () {
  52868. var size = 512;
  52869. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  52870. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  52871. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  52872. var context = this._grainTexture.getContext();
  52873. var rand = function (min, max) {
  52874. return Math.random() * (max - min) + min;
  52875. };
  52876. var value;
  52877. for (var x = 0; x < size; x++) {
  52878. for (var y = 0; y < size; y++) {
  52879. value = Math.floor(rand(0.42, 0.58) * 255);
  52880. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  52881. context.fillRect(x, y, 1, 1);
  52882. }
  52883. }
  52884. this._grainTexture.update(false);
  52885. };
  52886. return LensRenderingPipeline;
  52887. }(BABYLON.PostProcessRenderPipeline));
  52888. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  52889. })(BABYLON || (BABYLON = {}));
  52890. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  52891. var BABYLON;
  52892. (function (BABYLON) {
  52893. var StandardRenderingPipeline = (function (_super) {
  52894. __extends(StandardRenderingPipeline, _super);
  52895. /**
  52896. * @constructor
  52897. * @param {string} name - The rendering pipeline name
  52898. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  52899. * @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)
  52900. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  52901. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  52902. */
  52903. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  52904. if (originalPostProcess === void 0) { originalPostProcess = null; }
  52905. var _this = _super.call(this, scene.getEngine(), name) || this;
  52906. _this.downSampleX4PostProcess = null;
  52907. _this.brightPassPostProcess = null;
  52908. _this.blurHPostProcesses = [];
  52909. _this.blurVPostProcesses = [];
  52910. _this.textureAdderPostProcess = null;
  52911. _this.volumetricLightPostProcess = null;
  52912. _this.volumetricLightSmoothXPostProcess = null;
  52913. _this.volumetricLightSmoothYPostProcess = null;
  52914. _this.volumetricLightMergePostProces = null;
  52915. _this.volumetricLightFinalPostProcess = null;
  52916. _this.luminancePostProcess = null;
  52917. _this.luminanceDownSamplePostProcesses = [];
  52918. _this.hdrPostProcess = null;
  52919. _this.textureAdderFinalPostProcess = null;
  52920. _this.lensFlareFinalPostProcess = null;
  52921. _this.hdrFinalPostProcess = null;
  52922. _this.lensFlarePostProcess = null;
  52923. _this.lensFlareComposePostProcess = null;
  52924. _this.motionBlurPostProcess = null;
  52925. _this.depthOfFieldPostProcess = null;
  52926. // Values
  52927. _this.brightThreshold = 1.0;
  52928. _this.blurWidth = 512.0;
  52929. _this.horizontalBlur = false;
  52930. _this.exposure = 1.0;
  52931. _this.lensTexture = null;
  52932. _this.volumetricLightCoefficient = 0.2;
  52933. _this.volumetricLightPower = 4.0;
  52934. _this.volumetricLightBlurScale = 64.0;
  52935. _this.sourceLight = null;
  52936. _this.hdrMinimumLuminance = 1.0;
  52937. _this.hdrDecreaseRate = 0.5;
  52938. _this.hdrIncreaseRate = 0.5;
  52939. _this.lensColorTexture = null;
  52940. _this.lensFlareStrength = 20.0;
  52941. _this.lensFlareGhostDispersal = 1.4;
  52942. _this.lensFlareHaloWidth = 0.7;
  52943. _this.lensFlareDistortionStrength = 16.0;
  52944. _this.lensStarTexture = null;
  52945. _this.lensFlareDirtTexture = null;
  52946. _this.depthOfFieldDistance = 10.0;
  52947. _this.depthOfFieldBlurWidth = 64.0;
  52948. _this.motionStrength = 1.0;
  52949. // IAnimatable
  52950. _this.animations = [];
  52951. _this._currentDepthOfFieldSource = null;
  52952. _this._hdrCurrentLuminance = 1.0;
  52953. // Getters and setters
  52954. _this._bloomEnabled = true;
  52955. _this._depthOfFieldEnabled = false;
  52956. _this._vlsEnabled = false;
  52957. _this._lensFlareEnabled = false;
  52958. _this._hdrEnabled = false;
  52959. _this._motionBlurEnabled = false;
  52960. _this._motionBlurSamples = 64.0;
  52961. _this._volumetricLightStepsCount = 50.0;
  52962. _this._cameras = cameras || [];
  52963. // Initialize
  52964. _this._scene = scene;
  52965. _this._basePostProcess = originalPostProcess;
  52966. _this._ratio = ratio;
  52967. // Misc
  52968. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  52969. // Finish
  52970. scene.postProcessRenderPipelineManager.addPipeline(_this);
  52971. _this._buildPipeline();
  52972. return _this;
  52973. }
  52974. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  52975. get: function () {
  52976. return this._bloomEnabled;
  52977. },
  52978. set: function (enabled) {
  52979. if (this._bloomEnabled === enabled) {
  52980. return;
  52981. }
  52982. this._bloomEnabled = enabled;
  52983. this._buildPipeline();
  52984. },
  52985. enumerable: true,
  52986. configurable: true
  52987. });
  52988. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  52989. get: function () {
  52990. return this._depthOfFieldEnabled;
  52991. },
  52992. set: function (enabled) {
  52993. if (this._depthOfFieldEnabled === enabled) {
  52994. return;
  52995. }
  52996. this._depthOfFieldEnabled = enabled;
  52997. this._buildPipeline();
  52998. },
  52999. enumerable: true,
  53000. configurable: true
  53001. });
  53002. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  53003. get: function () {
  53004. return this._lensFlareEnabled;
  53005. },
  53006. set: function (enabled) {
  53007. if (this._lensFlareEnabled === enabled) {
  53008. return;
  53009. }
  53010. this._lensFlareEnabled = enabled;
  53011. this._buildPipeline();
  53012. },
  53013. enumerable: true,
  53014. configurable: true
  53015. });
  53016. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  53017. get: function () {
  53018. return this._hdrEnabled;
  53019. },
  53020. set: function (enabled) {
  53021. if (this._hdrEnabled === enabled) {
  53022. return;
  53023. }
  53024. this._hdrEnabled = enabled;
  53025. this._buildPipeline();
  53026. },
  53027. enumerable: true,
  53028. configurable: true
  53029. });
  53030. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  53031. get: function () {
  53032. return this._vlsEnabled;
  53033. },
  53034. set: function (enabled) {
  53035. if (this._vlsEnabled === enabled) {
  53036. return;
  53037. }
  53038. if (enabled) {
  53039. var geometry = this._scene.enableGeometryBufferRenderer();
  53040. if (!geometry) {
  53041. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  53042. return;
  53043. }
  53044. }
  53045. this._vlsEnabled = enabled;
  53046. this._buildPipeline();
  53047. },
  53048. enumerable: true,
  53049. configurable: true
  53050. });
  53051. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  53052. get: function () {
  53053. return this._motionBlurEnabled;
  53054. },
  53055. set: function (enabled) {
  53056. if (this._motionBlurEnabled === enabled) {
  53057. return;
  53058. }
  53059. this._motionBlurEnabled = enabled;
  53060. this._buildPipeline();
  53061. },
  53062. enumerable: true,
  53063. configurable: true
  53064. });
  53065. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  53066. get: function () {
  53067. return this._volumetricLightStepsCount;
  53068. },
  53069. set: function (count) {
  53070. if (this.volumetricLightPostProcess) {
  53071. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  53072. }
  53073. this._volumetricLightStepsCount = count;
  53074. },
  53075. enumerable: true,
  53076. configurable: true
  53077. });
  53078. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  53079. get: function () {
  53080. return this._motionBlurSamples;
  53081. },
  53082. set: function (samples) {
  53083. if (this.motionBlurPostProcess) {
  53084. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  53085. }
  53086. this._motionBlurSamples = samples;
  53087. },
  53088. enumerable: true,
  53089. configurable: true
  53090. });
  53091. StandardRenderingPipeline.prototype._buildPipeline = function () {
  53092. var _this = this;
  53093. var ratio = this._ratio;
  53094. var scene = this._scene;
  53095. this._disposePostProcesses();
  53096. this._reset();
  53097. // Create pass post-process
  53098. if (!this._basePostProcess) {
  53099. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  53100. this.originalPostProcess.onApply = function (effect) {
  53101. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  53102. };
  53103. }
  53104. else {
  53105. this.originalPostProcess = this._basePostProcess;
  53106. }
  53107. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  53108. this._currentDepthOfFieldSource = this.originalPostProcess;
  53109. if (this._vlsEnabled) {
  53110. // Create volumetric light
  53111. this._createVolumetricLightPostProcess(scene, ratio);
  53112. // Create volumetric light final post-process
  53113. this.volumetricLightFinalPostProcess = new BABYLON.PostProcess("HDRVLSFinal", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53114. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  53115. }
  53116. if (this._bloomEnabled) {
  53117. // Create down sample X4 post-process
  53118. this._createDownSampleX4PostProcess(scene, ratio / 2);
  53119. // Create bright pass post-process
  53120. this._createBrightPassPostProcess(scene, ratio / 2);
  53121. // Create gaussian blur post-processes (down sampling blurs)
  53122. this._createBlurPostProcesses(scene, ratio / 4, 1);
  53123. // Create texture adder post-process
  53124. this._createTextureAdderPostProcess(scene, ratio);
  53125. // Create depth-of-field source post-process
  53126. this.textureAdderFinalPostProcess = new BABYLON.PostProcess("HDRDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53127. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  53128. }
  53129. if (this._lensFlareEnabled) {
  53130. // Create lens flare post-process
  53131. this._createLensFlarePostProcess(scene, ratio);
  53132. // Create depth-of-field source post-process post lens-flare and disable it now
  53133. this.lensFlareFinalPostProcess = new BABYLON.PostProcess("HDRPostLensFlareDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53134. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  53135. }
  53136. if (this._hdrEnabled) {
  53137. // Create luminance
  53138. this._createLuminancePostProcesses(scene, this._floatTextureType);
  53139. // Create HDR
  53140. this._createHdrPostProcess(scene, ratio);
  53141. // Create depth-of-field source post-process post hdr and disable it now
  53142. this.hdrFinalPostProcess = new BABYLON.PostProcess("HDRPostHDReDepthOfFieldSource", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53143. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  53144. }
  53145. if (this._depthOfFieldEnabled) {
  53146. // Create gaussian blur used by depth-of-field
  53147. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  53148. // Create depth-of-field post-process
  53149. this._createDepthOfFieldPostProcess(scene, ratio);
  53150. }
  53151. if (this._motionBlurEnabled) {
  53152. // Create motion blur post-process
  53153. this._createMotionBlurPostProcess(scene, ratio);
  53154. }
  53155. if (this._cameras !== null) {
  53156. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53157. }
  53158. };
  53159. // Down Sample X4 Post-Processs
  53160. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  53161. var _this = this;
  53162. var downSampleX4Offsets = new Array(32);
  53163. 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);
  53164. this.downSampleX4PostProcess.onApply = function (effect) {
  53165. var id = 0;
  53166. for (var i = -2; i < 2; i++) {
  53167. for (var j = -2; j < 2; j++) {
  53168. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / _this.downSampleX4PostProcess.width);
  53169. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / _this.downSampleX4PostProcess.height);
  53170. id += 2;
  53171. }
  53172. }
  53173. effect.setArray2("dsOffsets", downSampleX4Offsets);
  53174. };
  53175. // Add to pipeline
  53176. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  53177. };
  53178. // Brightpass Post-Process
  53179. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  53180. var _this = this;
  53181. var brightOffsets = new Array(8);
  53182. 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);
  53183. this.brightPassPostProcess.onApply = function (effect) {
  53184. var sU = (1.0 / _this.brightPassPostProcess.width);
  53185. var sV = (1.0 / _this.brightPassPostProcess.height);
  53186. brightOffsets[0] = -0.5 * sU;
  53187. brightOffsets[1] = 0.5 * sV;
  53188. brightOffsets[2] = 0.5 * sU;
  53189. brightOffsets[3] = 0.5 * sV;
  53190. brightOffsets[4] = -0.5 * sU;
  53191. brightOffsets[5] = -0.5 * sV;
  53192. brightOffsets[6] = 0.5 * sU;
  53193. brightOffsets[7] = -0.5 * sV;
  53194. effect.setArray2("dsOffsets", brightOffsets);
  53195. effect.setFloat("brightThreshold", _this.brightThreshold);
  53196. };
  53197. // Add to pipeline
  53198. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  53199. };
  53200. // Create blur H&V post-processes
  53201. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  53202. var _this = this;
  53203. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  53204. var engine = scene.getEngine();
  53205. var blurX = new BABYLON.BlurPostProcess("HDRBlurH" + "_" + indice, new BABYLON.Vector2(1, 0), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53206. var blurY = new BABYLON.BlurPostProcess("HDRBlurV" + "_" + indice, new BABYLON.Vector2(0, 1), this[blurWidthKey], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53207. blurX.onActivateObservable.add(function () {
  53208. var dw = blurX.width / engine.getRenderingCanvas().width;
  53209. blurX.kernel = _this[blurWidthKey] * dw;
  53210. });
  53211. blurY.onActivateObservable.add(function () {
  53212. var dw = blurY.height / engine.getRenderingCanvas().height;
  53213. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  53214. });
  53215. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  53216. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  53217. this.blurHPostProcesses.push(blurX);
  53218. this.blurVPostProcesses.push(blurY);
  53219. };
  53220. // Create texture adder post-process
  53221. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  53222. var _this = this;
  53223. 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);
  53224. this.textureAdderPostProcess.onApply = function (effect) {
  53225. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  53226. effect.setTexture("lensSampler", _this.lensTexture);
  53227. effect.setFloat("exposure", _this.exposure);
  53228. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  53229. };
  53230. // Add to pipeline
  53231. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  53232. };
  53233. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  53234. var _this = this;
  53235. var geometryRenderer = scene.enableGeometryBufferRenderer();
  53236. geometryRenderer.enablePosition = true;
  53237. var geometry = geometryRenderer.getGBuffer();
  53238. // Base post-process
  53239. this.volumetricLightPostProcess = new BABYLON.PostProcess("HDRVLS", "standard", ["shadowViewProjection", "cameraPosition", "sunDirection", "sunColor", "scatteringCoefficient", "scatteringPower", "depthValues"], ["shadowMapSampler", "positionSampler"], ratio / 8, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLS\n#define NB_STEPS " + this._volumetricLightStepsCount.toFixed(1));
  53240. var depthValues = BABYLON.Vector2.Zero();
  53241. this.volumetricLightPostProcess.onApply = function (effect) {
  53242. if (_this.sourceLight && _this.sourceLight.getShadowGenerator()) {
  53243. var generator = _this.sourceLight.getShadowGenerator();
  53244. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  53245. effect.setTexture("positionSampler", geometry.textures[2]);
  53246. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  53247. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  53248. effect.setVector3("cameraPosition", scene.activeCamera.globalPosition);
  53249. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  53250. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  53251. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  53252. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  53253. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  53254. effect.setVector2("depthValues", depthValues);
  53255. }
  53256. };
  53257. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  53258. // Smooth
  53259. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  53260. // Merge
  53261. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  53262. this.volumetricLightMergePostProces.onApply = function (effect) {
  53263. effect.setTextureFromPostProcess("originalSampler", _this.originalPostProcess);
  53264. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  53265. };
  53266. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  53267. };
  53268. // Create luminance
  53269. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  53270. var _this = this;
  53271. // Create luminance
  53272. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  53273. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  53274. var offsets = [];
  53275. this.luminancePostProcess.onApply = function (effect) {
  53276. var sU = (1.0 / _this.luminancePostProcess.width);
  53277. var sV = (1.0 / _this.luminancePostProcess.height);
  53278. offsets[0] = -0.5 * sU;
  53279. offsets[1] = 0.5 * sV;
  53280. offsets[2] = 0.5 * sU;
  53281. offsets[3] = 0.5 * sV;
  53282. offsets[4] = -0.5 * sU;
  53283. offsets[5] = -0.5 * sV;
  53284. offsets[6] = 0.5 * sU;
  53285. offsets[7] = -0.5 * sV;
  53286. effect.setArray2("lumOffsets", offsets);
  53287. };
  53288. // Add to pipeline
  53289. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  53290. // Create down sample luminance
  53291. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  53292. var size = Math.pow(3, i);
  53293. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  53294. if (i === 0) {
  53295. defines += "#define FINAL_DOWN_SAMPLER";
  53296. }
  53297. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  53298. this.luminanceDownSamplePostProcesses.push(postProcess);
  53299. }
  53300. // Create callbacks and add effects
  53301. var lastLuminance = this.luminancePostProcess;
  53302. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  53303. var downSampleOffsets = new Array(18);
  53304. pp.onApply = function (effect) {
  53305. var id = 0;
  53306. for (var x = -1; x < 2; x++) {
  53307. for (var y = -1; y < 2; y++) {
  53308. downSampleOffsets[id] = x / lastLuminance.width;
  53309. downSampleOffsets[id + 1] = y / lastLuminance.height;
  53310. id += 2;
  53311. }
  53312. }
  53313. effect.setArray2("dsOffsets", downSampleOffsets);
  53314. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  53315. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53316. lastLuminance = _this.luminancePostProcess;
  53317. }
  53318. else {
  53319. lastLuminance = pp;
  53320. }
  53321. };
  53322. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  53323. pp.onAfterRender = function (effect) {
  53324. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  53325. 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);
  53326. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  53327. };
  53328. }
  53329. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  53330. });
  53331. };
  53332. // Create HDR post-process
  53333. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  53334. var _this = this;
  53335. this.hdrPostProcess = new BABYLON.PostProcess("HDR", "standard", ["averageLuminance"], ["textureAdderSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define HDR", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53336. var outputLiminance = 1;
  53337. var time = 0;
  53338. var lastTime = 0;
  53339. this.hdrPostProcess.onApply = function (effect) {
  53340. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  53341. time += scene.getEngine().getDeltaTime();
  53342. if (outputLiminance < 0) {
  53343. outputLiminance = _this._hdrCurrentLuminance;
  53344. }
  53345. else {
  53346. var dt = (lastTime - time) / 1000.0;
  53347. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  53348. outputLiminance += _this.hdrDecreaseRate * dt;
  53349. }
  53350. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  53351. outputLiminance -= _this.hdrIncreaseRate * dt;
  53352. }
  53353. else {
  53354. outputLiminance = _this._hdrCurrentLuminance;
  53355. }
  53356. }
  53357. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  53358. effect.setFloat("averageLuminance", outputLiminance);
  53359. lastTime = time;
  53360. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  53361. };
  53362. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  53363. };
  53364. // Create lens flare post-process
  53365. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  53366. var _this = this;
  53367. this.lensFlarePostProcess = new BABYLON.PostProcess("HDRLensFlare", "standard", ["strength", "ghostDispersal", "haloWidth", "resolution", "distortionStrength"], ["lensColorSampler"], ratio / 2, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LENS_FLARE", BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53368. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  53369. this._createBlurPostProcesses(scene, ratio / 4, 2);
  53370. 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);
  53371. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  53372. var resolution = new BABYLON.Vector2(0, 0);
  53373. // Lens flare
  53374. this.lensFlarePostProcess.onApply = function (effect) {
  53375. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  53376. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  53377. effect.setFloat("strength", _this.lensFlareStrength);
  53378. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  53379. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  53380. // Shift
  53381. resolution.x = _this.lensFlarePostProcess.width;
  53382. resolution.y = _this.lensFlarePostProcess.height;
  53383. effect.setVector2("resolution", resolution);
  53384. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  53385. };
  53386. // Compose
  53387. 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);
  53388. 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);
  53389. this.lensFlareComposePostProcess.onApply = function (effect) {
  53390. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53391. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  53392. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  53393. // Lens start rotation matrix
  53394. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  53395. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  53396. 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));
  53397. camRot *= 4.0;
  53398. 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);
  53399. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  53400. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  53401. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  53402. };
  53403. };
  53404. // Create depth-of-field post-process
  53405. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  53406. var _this = this;
  53407. 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);
  53408. this.depthOfFieldPostProcess.onApply = function (effect) {
  53409. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  53410. effect.setTexture("depthSampler", _this._getDepthTexture());
  53411. effect.setFloat("distance", _this.depthOfFieldDistance);
  53412. };
  53413. // Add to pipeline
  53414. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  53415. };
  53416. // Create motion blur post-process
  53417. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  53418. var _this = this;
  53419. this.motionBlurPostProcess = new BABYLON.PostProcess("HDRMotionBlur", "standard", ["inverseViewProjection", "prevViewProjection", "screenSize", "motionScale", "motionStrength"], ["depthSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + this.motionBlurSamples.toFixed(1), BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  53420. var motionScale = 0;
  53421. var prevViewProjection = BABYLON.Matrix.Identity();
  53422. var invViewProjection = BABYLON.Matrix.Identity();
  53423. var viewProjection = BABYLON.Matrix.Identity();
  53424. var screenSize = BABYLON.Vector2.Zero();
  53425. this.motionBlurPostProcess.onApply = function (effect) {
  53426. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  53427. viewProjection.invertToRef(invViewProjection);
  53428. effect.setMatrix("inverseViewProjection", invViewProjection);
  53429. effect.setMatrix("prevViewProjection", prevViewProjection);
  53430. prevViewProjection = viewProjection;
  53431. screenSize.x = _this.motionBlurPostProcess.width;
  53432. screenSize.y = _this.motionBlurPostProcess.height;
  53433. effect.setVector2("screenSize", screenSize);
  53434. motionScale = scene.getEngine().getFps() / 60.0;
  53435. effect.setFloat("motionScale", motionScale);
  53436. effect.setFloat("motionStrength", _this.motionStrength);
  53437. effect.setTexture("depthSampler", _this._getDepthTexture());
  53438. };
  53439. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  53440. };
  53441. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  53442. var geometry = this._scene.enableGeometryBufferRenderer();
  53443. if (geometry) {
  53444. return geometry.getGBuffer().textures[0];
  53445. }
  53446. return this._scene.enableDepthRenderer().getDepthMap();
  53447. };
  53448. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  53449. for (var i = 0; i < this._cameras.length; i++) {
  53450. var camera = this._cameras[i];
  53451. if (this.originalPostProcess) {
  53452. this.originalPostProcess.dispose(camera);
  53453. }
  53454. if (this.downSampleX4PostProcess) {
  53455. this.downSampleX4PostProcess.dispose(camera);
  53456. }
  53457. if (this.brightPassPostProcess) {
  53458. this.brightPassPostProcess.dispose(camera);
  53459. }
  53460. if (this.textureAdderPostProcess) {
  53461. this.textureAdderPostProcess.dispose(camera);
  53462. }
  53463. if (this.textureAdderFinalPostProcess) {
  53464. this.textureAdderFinalPostProcess.dispose(camera);
  53465. }
  53466. if (this.volumetricLightPostProcess) {
  53467. this.volumetricLightPostProcess.dispose(camera);
  53468. }
  53469. if (this.volumetricLightSmoothXPostProcess) {
  53470. this.volumetricLightSmoothXPostProcess.dispose(camera);
  53471. }
  53472. if (this.volumetricLightSmoothYPostProcess) {
  53473. this.volumetricLightSmoothYPostProcess.dispose(camera);
  53474. }
  53475. if (this.volumetricLightMergePostProces) {
  53476. this.volumetricLightMergePostProces.dispose(camera);
  53477. }
  53478. if (this.volumetricLightFinalPostProcess) {
  53479. this.volumetricLightFinalPostProcess.dispose(camera);
  53480. }
  53481. if (this.lensFlarePostProcess) {
  53482. this.lensFlarePostProcess.dispose(camera);
  53483. }
  53484. if (this.lensFlareComposePostProcess) {
  53485. this.lensFlareComposePostProcess.dispose(camera);
  53486. }
  53487. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  53488. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  53489. }
  53490. if (this.luminancePostProcess) {
  53491. this.luminancePostProcess.dispose(camera);
  53492. }
  53493. if (this.hdrPostProcess) {
  53494. this.hdrPostProcess.dispose(camera);
  53495. }
  53496. if (this.hdrFinalPostProcess) {
  53497. this.hdrFinalPostProcess.dispose(camera);
  53498. }
  53499. if (this.depthOfFieldPostProcess) {
  53500. this.depthOfFieldPostProcess.dispose(camera);
  53501. }
  53502. if (this.motionBlurPostProcess) {
  53503. this.motionBlurPostProcess.dispose(camera);
  53504. }
  53505. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  53506. this.blurHPostProcesses[j].dispose(camera);
  53507. }
  53508. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  53509. this.blurVPostProcesses[j].dispose(camera);
  53510. }
  53511. }
  53512. this.originalPostProcess = null;
  53513. this.downSampleX4PostProcess = null;
  53514. this.brightPassPostProcess = null;
  53515. this.textureAdderPostProcess = null;
  53516. this.textureAdderFinalPostProcess = null;
  53517. this.volumetricLightPostProcess = null;
  53518. this.volumetricLightSmoothXPostProcess = null;
  53519. this.volumetricLightSmoothYPostProcess = null;
  53520. this.volumetricLightMergePostProces = null;
  53521. this.volumetricLightFinalPostProcess = null;
  53522. this.lensFlarePostProcess = null;
  53523. this.lensFlareComposePostProcess = null;
  53524. this.luminancePostProcess = null;
  53525. this.hdrPostProcess = null;
  53526. this.hdrFinalPostProcess = null;
  53527. this.depthOfFieldPostProcess = null;
  53528. this.motionBlurPostProcess = null;
  53529. this.luminanceDownSamplePostProcesses = [];
  53530. this.blurHPostProcesses = [];
  53531. this.blurVPostProcesses = [];
  53532. };
  53533. // Dispose
  53534. StandardRenderingPipeline.prototype.dispose = function () {
  53535. this._disposePostProcesses();
  53536. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53537. _super.prototype.dispose.call(this);
  53538. };
  53539. // Serialize rendering pipeline
  53540. StandardRenderingPipeline.prototype.serialize = function () {
  53541. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53542. serializationObject.customType = "StandardRenderingPipeline";
  53543. return serializationObject;
  53544. };
  53545. /**
  53546. * Static members
  53547. */
  53548. // Parse serialized pipeline
  53549. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53550. return BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  53551. };
  53552. // Luminance steps
  53553. StandardRenderingPipeline.LuminanceSteps = 6;
  53554. __decorate([
  53555. BABYLON.serialize()
  53556. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  53557. __decorate([
  53558. BABYLON.serialize()
  53559. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  53560. __decorate([
  53561. BABYLON.serialize()
  53562. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  53563. __decorate([
  53564. BABYLON.serialize()
  53565. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  53566. __decorate([
  53567. BABYLON.serializeAsTexture("lensTexture")
  53568. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  53569. __decorate([
  53570. BABYLON.serialize()
  53571. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  53572. __decorate([
  53573. BABYLON.serialize()
  53574. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  53575. __decorate([
  53576. BABYLON.serialize()
  53577. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  53578. __decorate([
  53579. BABYLON.serialize()
  53580. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  53581. __decorate([
  53582. BABYLON.serialize()
  53583. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  53584. __decorate([
  53585. BABYLON.serialize()
  53586. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  53587. __decorate([
  53588. BABYLON.serializeAsTexture("lensColorTexture")
  53589. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  53590. __decorate([
  53591. BABYLON.serialize()
  53592. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  53593. __decorate([
  53594. BABYLON.serialize()
  53595. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  53596. __decorate([
  53597. BABYLON.serialize()
  53598. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  53599. __decorate([
  53600. BABYLON.serialize()
  53601. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  53602. __decorate([
  53603. BABYLON.serializeAsTexture("lensStarTexture")
  53604. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  53605. __decorate([
  53606. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  53607. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  53608. __decorate([
  53609. BABYLON.serialize()
  53610. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  53611. __decorate([
  53612. BABYLON.serialize()
  53613. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  53614. __decorate([
  53615. BABYLON.serialize()
  53616. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  53617. __decorate([
  53618. BABYLON.serialize()
  53619. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  53620. __decorate([
  53621. BABYLON.serialize()
  53622. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  53623. __decorate([
  53624. BABYLON.serialize()
  53625. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  53626. __decorate([
  53627. BABYLON.serialize()
  53628. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  53629. __decorate([
  53630. BABYLON.serialize()
  53631. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  53632. __decorate([
  53633. BABYLON.serialize()
  53634. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  53635. __decorate([
  53636. BABYLON.serialize()
  53637. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  53638. __decorate([
  53639. BABYLON.serialize()
  53640. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  53641. return StandardRenderingPipeline;
  53642. }(BABYLON.PostProcessRenderPipeline));
  53643. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  53644. })(BABYLON || (BABYLON = {}));
  53645. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  53646. var BABYLON;
  53647. (function (BABYLON) {
  53648. var FxaaPostProcess = (function (_super) {
  53649. __extends(FxaaPostProcess, _super);
  53650. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  53651. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  53652. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa") || this;
  53653. _this.onApplyObservable.add(function (effect) {
  53654. var texelSize = _this.texelSize;
  53655. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  53656. });
  53657. return _this;
  53658. }
  53659. return FxaaPostProcess;
  53660. }(BABYLON.PostProcess));
  53661. BABYLON.FxaaPostProcess = FxaaPostProcess;
  53662. })(BABYLON || (BABYLON = {}));
  53663. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  53664. var BABYLON;
  53665. (function (BABYLON) {
  53666. var DefaultRenderingPipeline = (function (_super) {
  53667. __extends(DefaultRenderingPipeline, _super);
  53668. /**
  53669. * @constructor
  53670. * @param {string} name - The rendering pipeline name
  53671. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  53672. * @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)
  53673. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  53674. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  53675. */
  53676. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  53677. if (automaticBuild === void 0) { automaticBuild = true; }
  53678. var _this = _super.call(this, scene.getEngine(), name) || this;
  53679. _this.PassPostProcessId = "PassPostProcessEffect";
  53680. _this.HighLightsPostProcessId = "HighLightsPostProcessEffect";
  53681. _this.BlurXPostProcessId = "BlurXPostProcessEffect";
  53682. _this.BlurYPostProcessId = "BlurYPostProcessEffect";
  53683. _this.CopyBackPostProcessId = "CopyBackPostProcessEffect";
  53684. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  53685. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  53686. _this.FinalMergePostProcessId = "FinalMergePostProcessEffect";
  53687. // IAnimatable
  53688. _this.animations = [];
  53689. // Values
  53690. _this._bloomEnabled = false;
  53691. _this._fxaaEnabled = false;
  53692. _this._imageProcessingEnabled = true;
  53693. _this._bloomScale = 0.6;
  53694. _this._buildAllowed = true;
  53695. /**
  53696. * Specifies the size of the bloom blur kernel, relative to the final output size
  53697. */
  53698. _this.bloomKernel = 64;
  53699. /**
  53700. * Specifies the weight of the bloom in the final rendering
  53701. */
  53702. _this._bloomWeight = 0.15;
  53703. _this._cameras = cameras || [];
  53704. _this._buildAllowed = automaticBuild;
  53705. // Initialize
  53706. _this._scene = scene;
  53707. var caps = _this._scene.getEngine().getCaps();
  53708. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  53709. // Misc
  53710. if (_this._hdr) {
  53711. if (caps.textureHalfFloatRender) {
  53712. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  53713. }
  53714. else if (caps.textureFloatRender) {
  53715. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  53716. }
  53717. }
  53718. else {
  53719. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  53720. }
  53721. // Attach
  53722. scene.postProcessRenderPipelineManager.addPipeline(_this);
  53723. _this._buildPipeline();
  53724. return _this;
  53725. }
  53726. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  53727. get: function () {
  53728. return this._bloomWeight;
  53729. },
  53730. set: function (value) {
  53731. if (this._bloomWeight === value) {
  53732. return;
  53733. }
  53734. this._bloomWeight = value;
  53735. if (this._hdr && this.copyBack) {
  53736. this.copyBack.alphaConstants = new BABYLON.Color4(value, value, value, value);
  53737. }
  53738. },
  53739. enumerable: true,
  53740. configurable: true
  53741. });
  53742. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  53743. get: function () {
  53744. return this._bloomScale;
  53745. },
  53746. set: function (value) {
  53747. if (this._bloomScale === value) {
  53748. return;
  53749. }
  53750. this._bloomScale = value;
  53751. this._buildPipeline();
  53752. },
  53753. enumerable: true,
  53754. configurable: true
  53755. });
  53756. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  53757. get: function () {
  53758. return this._bloomEnabled;
  53759. },
  53760. set: function (enabled) {
  53761. if (this._bloomEnabled === enabled) {
  53762. return;
  53763. }
  53764. this._bloomEnabled = enabled;
  53765. this._buildPipeline();
  53766. },
  53767. enumerable: true,
  53768. configurable: true
  53769. });
  53770. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  53771. get: function () {
  53772. return this._fxaaEnabled;
  53773. },
  53774. set: function (enabled) {
  53775. if (this._fxaaEnabled === enabled) {
  53776. return;
  53777. }
  53778. this._fxaaEnabled = enabled;
  53779. this._buildPipeline();
  53780. },
  53781. enumerable: true,
  53782. configurable: true
  53783. });
  53784. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  53785. get: function () {
  53786. return this._imageProcessingEnabled;
  53787. },
  53788. set: function (enabled) {
  53789. if (this._imageProcessingEnabled === enabled) {
  53790. return;
  53791. }
  53792. this._imageProcessingEnabled = enabled;
  53793. this._buildPipeline();
  53794. },
  53795. enumerable: true,
  53796. configurable: true
  53797. });
  53798. /**
  53799. * Force the compilation of the entire pipeline.
  53800. */
  53801. DefaultRenderingPipeline.prototype.prepare = function () {
  53802. var previousState = this._buildAllowed;
  53803. this._buildAllowed = true;
  53804. this._buildPipeline();
  53805. this._buildAllowed = previousState;
  53806. };
  53807. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  53808. var _this = this;
  53809. if (!this._buildAllowed) {
  53810. return;
  53811. }
  53812. var engine = this._scene.getEngine();
  53813. this._disposePostProcesses();
  53814. this._reset();
  53815. if (this.bloomEnabled) {
  53816. this.pass = new BABYLON.PassPostProcess("sceneRenderTarget", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53817. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.PassPostProcessId, function () { return _this.pass; }, true));
  53818. if (!this._hdr) {
  53819. this.highlights = new BABYLON.HighlightsPostProcess("highlights", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53820. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.HighLightsPostProcessId, function () { return _this.highlights; }, true));
  53821. this.highlights.autoClear = false;
  53822. this.highlights.alwaysForcePOT = true;
  53823. }
  53824. this.blurX = new BABYLON.BlurPostProcess("horizontal blur", new BABYLON.Vector2(1.0, 0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53825. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurXPostProcessId, function () { return _this.blurX; }, true));
  53826. this.blurX.alwaysForcePOT = true;
  53827. this.blurX.autoClear = false;
  53828. this.blurX.onActivateObservable.add(function () {
  53829. var dw = _this.blurX.width / engine.getRenderingCanvas().width;
  53830. _this.blurX.kernel = _this.bloomKernel * dw;
  53831. });
  53832. this.blurY = new BABYLON.BlurPostProcess("vertical blur", new BABYLON.Vector2(0, 1.0), 10.0, this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53833. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.BlurYPostProcessId, function () { return _this.blurY; }, true));
  53834. this.blurY.alwaysForcePOT = true;
  53835. this.blurY.autoClear = false;
  53836. this.blurY.onActivateObservable.add(function () {
  53837. var dh = _this.blurY.height / engine.getRenderingCanvas().height;
  53838. _this.blurY.kernel = _this.bloomKernel * dh;
  53839. });
  53840. this.copyBack = new BABYLON.PassPostProcess("bloomBlendBlit", this.bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53841. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.CopyBackPostProcessId, function () { return _this.copyBack; }, true));
  53842. this.copyBack.alwaysForcePOT = true;
  53843. if (this._hdr) {
  53844. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_INTERPOLATE;
  53845. var w = this.bloomWeight;
  53846. this.copyBack.alphaConstants = new BABYLON.Color4(w, w, w, w);
  53847. }
  53848. else {
  53849. this.copyBack.alphaMode = BABYLON.Engine.ALPHA_SCREENMODE;
  53850. }
  53851. this.copyBack.autoClear = false;
  53852. }
  53853. if (this._imageProcessingEnabled) {
  53854. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53855. if (this._hdr) {
  53856. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  53857. }
  53858. }
  53859. if (this.fxaaEnabled) {
  53860. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53861. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  53862. this.fxaa.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53863. }
  53864. else {
  53865. this.finalMerge = new BABYLON.PassPostProcess("finalMerge", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  53866. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FinalMergePostProcessId, function () { return _this.finalMerge; }, true));
  53867. this.finalMerge.autoClear = !this.bloomEnabled && (!this._hdr || !this.imageProcessing);
  53868. }
  53869. if (this.bloomEnabled) {
  53870. if (this._hdr) {
  53871. this.copyBack.shareOutputWith(this.blurX);
  53872. if (this.imageProcessing) {
  53873. this.imageProcessing.shareOutputWith(this.pass);
  53874. this.imageProcessing.autoClear = false;
  53875. }
  53876. else if (this.fxaa) {
  53877. this.fxaa.shareOutputWith(this.pass);
  53878. }
  53879. else {
  53880. this.finalMerge.shareOutputWith(this.pass);
  53881. }
  53882. }
  53883. else {
  53884. if (this.fxaa) {
  53885. this.fxaa.shareOutputWith(this.pass);
  53886. }
  53887. else {
  53888. this.finalMerge.shareOutputWith(this.pass);
  53889. }
  53890. }
  53891. }
  53892. if (this._cameras !== null) {
  53893. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  53894. }
  53895. };
  53896. DefaultRenderingPipeline.prototype._disposePostProcesses = function () {
  53897. for (var i = 0; i < this._cameras.length; i++) {
  53898. var camera = this._cameras[i];
  53899. if (this.pass) {
  53900. this.pass.dispose(camera);
  53901. }
  53902. if (this.highlights) {
  53903. this.highlights.dispose(camera);
  53904. }
  53905. if (this.blurX) {
  53906. this.blurX.dispose(camera);
  53907. }
  53908. if (this.blurY) {
  53909. this.blurY.dispose(camera);
  53910. }
  53911. if (this.copyBack) {
  53912. this.copyBack.dispose(camera);
  53913. }
  53914. if (this.imageProcessing) {
  53915. this.imageProcessing.dispose(camera);
  53916. }
  53917. if (this.fxaa) {
  53918. this.fxaa.dispose(camera);
  53919. }
  53920. if (this.finalMerge) {
  53921. this.finalMerge.dispose(camera);
  53922. }
  53923. }
  53924. this.pass = null;
  53925. this.highlights = null;
  53926. this.blurX = null;
  53927. this.blurY = null;
  53928. this.copyBack = null;
  53929. this.imageProcessing = null;
  53930. this.fxaa = null;
  53931. this.finalMerge = null;
  53932. };
  53933. // Dispose
  53934. DefaultRenderingPipeline.prototype.dispose = function () {
  53935. this._disposePostProcesses();
  53936. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  53937. _super.prototype.dispose.call(this);
  53938. };
  53939. // Serialize rendering pipeline
  53940. DefaultRenderingPipeline.prototype.serialize = function () {
  53941. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  53942. serializationObject.customType = "DefaultRenderingPipeline";
  53943. return serializationObject;
  53944. };
  53945. // Parse serialized pipeline
  53946. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  53947. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  53948. };
  53949. __decorate([
  53950. BABYLON.serialize()
  53951. ], DefaultRenderingPipeline.prototype, "bloomKernel", void 0);
  53952. __decorate([
  53953. BABYLON.serialize()
  53954. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  53955. __decorate([
  53956. BABYLON.serialize()
  53957. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  53958. __decorate([
  53959. BABYLON.serialize()
  53960. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  53961. __decorate([
  53962. BABYLON.serialize()
  53963. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  53964. __decorate([
  53965. BABYLON.serialize()
  53966. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  53967. __decorate([
  53968. BABYLON.serialize()
  53969. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  53970. __decorate([
  53971. BABYLON.serialize()
  53972. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  53973. return DefaultRenderingPipeline;
  53974. }(BABYLON.PostProcessRenderPipeline));
  53975. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  53976. })(BABYLON || (BABYLON = {}));
  53977. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  53978. var BABYLON;
  53979. (function (BABYLON) {
  53980. var GeometryBufferRenderer = (function () {
  53981. function GeometryBufferRenderer(scene, ratio) {
  53982. if (ratio === void 0) { ratio = 1; }
  53983. this._viewMatrix = BABYLON.Matrix.Zero();
  53984. this._projectionMatrix = BABYLON.Matrix.Zero();
  53985. this._transformMatrix = BABYLON.Matrix.Zero();
  53986. this._worldViewProjection = BABYLON.Matrix.Zero();
  53987. this._enablePosition = false;
  53988. this._scene = scene;
  53989. this._ratio = ratio;
  53990. // Render target
  53991. this._createRenderTargets();
  53992. }
  53993. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  53994. set: function (meshes) {
  53995. this._multiRenderTarget.renderList = meshes;
  53996. },
  53997. enumerable: true,
  53998. configurable: true
  53999. });
  54000. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  54001. get: function () {
  54002. return this._multiRenderTarget.isSupported;
  54003. },
  54004. enumerable: true,
  54005. configurable: true
  54006. });
  54007. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  54008. get: function () {
  54009. return this._enablePosition;
  54010. },
  54011. set: function (enable) {
  54012. this._enablePosition = enable;
  54013. this.dispose();
  54014. this._createRenderTargets();
  54015. },
  54016. enumerable: true,
  54017. configurable: true
  54018. });
  54019. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  54020. var material = subMesh.getMaterial();
  54021. if (material && material.disableDepthWrite) {
  54022. return false;
  54023. }
  54024. var defines = [];
  54025. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  54026. var mesh = subMesh.getMesh();
  54027. var scene = mesh.getScene();
  54028. // Alpha test
  54029. if (material && material.needAlphaTesting()) {
  54030. defines.push("#define ALPHATEST");
  54031. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54032. attribs.push(BABYLON.VertexBuffer.UVKind);
  54033. defines.push("#define UV1");
  54034. }
  54035. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54036. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54037. defines.push("#define UV2");
  54038. }
  54039. }
  54040. // Buffers
  54041. if (this._enablePosition) {
  54042. defines.push("#define POSITION");
  54043. }
  54044. // Bones
  54045. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54046. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54047. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54048. if (mesh.numBoneInfluencers > 4) {
  54049. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  54050. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  54051. }
  54052. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54053. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54054. }
  54055. else {
  54056. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54057. }
  54058. // Instances
  54059. if (useInstances) {
  54060. defines.push("#define INSTANCES");
  54061. attribs.push("world0");
  54062. attribs.push("world1");
  54063. attribs.push("world2");
  54064. attribs.push("world3");
  54065. }
  54066. // Get correct effect
  54067. var join = defines.join("\n");
  54068. if (this._cachedDefines !== join) {
  54069. this._cachedDefines = join;
  54070. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join);
  54071. }
  54072. return this._effect.isReady();
  54073. };
  54074. GeometryBufferRenderer.prototype.getGBuffer = function () {
  54075. return this._multiRenderTarget;
  54076. };
  54077. // Methods
  54078. GeometryBufferRenderer.prototype.dispose = function () {
  54079. this.getGBuffer().dispose();
  54080. };
  54081. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  54082. var _this = this;
  54083. var engine = this._scene.getEngine();
  54084. var count = this._enablePosition ? 3 : 2;
  54085. this._multiRenderTarget = new BABYLON.MultiRenderTarget("gBuffer", { width: engine.getRenderWidth() * this._ratio, height: engine.getRenderHeight() * this._ratio }, count, this._scene, { generateMipMaps: false, generateDepthTexture: true });
  54086. if (!this.isSupported) {
  54087. return null;
  54088. }
  54089. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54090. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54091. this._multiRenderTarget.refreshRate = 1;
  54092. this._multiRenderTarget.renderParticles = false;
  54093. this._multiRenderTarget.renderList = null;
  54094. // set default depth value to 1.0 (far away)
  54095. this._multiRenderTarget.onClearObservable.add(function (engine) {
  54096. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  54097. });
  54098. // Custom render function
  54099. var renderSubMesh = function (subMesh) {
  54100. var mesh = subMesh.getRenderingMesh();
  54101. var scene = _this._scene;
  54102. var engine = scene.getEngine();
  54103. // Culling
  54104. engine.setState(subMesh.getMaterial().backFaceCulling);
  54105. // Managing instances
  54106. var batch = mesh._getInstancesRenderList(subMesh._id);
  54107. if (batch.mustReturn) {
  54108. return;
  54109. }
  54110. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54111. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54112. engine.enableEffect(_this._effect);
  54113. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  54114. var material = subMesh.getMaterial();
  54115. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  54116. _this._effect.setMatrix("view", scene.getViewMatrix());
  54117. // Alpha test
  54118. if (material && material.needAlphaTesting()) {
  54119. var alphaTexture = material.getAlphaTestTexture();
  54120. _this._effect.setTexture("diffuseSampler", alphaTexture);
  54121. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54122. }
  54123. // Bones
  54124. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54125. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54126. }
  54127. // Draw
  54128. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  54129. }
  54130. };
  54131. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes) {
  54132. var index;
  54133. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54134. renderSubMesh(opaqueSubMeshes.data[index]);
  54135. }
  54136. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54137. renderSubMesh(alphaTestSubMeshes.data[index]);
  54138. }
  54139. };
  54140. };
  54141. return GeometryBufferRenderer;
  54142. }());
  54143. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  54144. })(BABYLON || (BABYLON = {}));
  54145. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  54146. var BABYLON;
  54147. (function (BABYLON) {
  54148. var RefractionPostProcess = (function (_super) {
  54149. __extends(RefractionPostProcess, _super);
  54150. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  54151. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  54152. _this.color = color;
  54153. _this.depth = depth;
  54154. _this.colorLevel = colorLevel;
  54155. _this.onActivateObservable.add(function (cam) {
  54156. _this._refRexture = _this._refRexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  54157. });
  54158. _this.onApplyObservable.add(function (effect) {
  54159. effect.setColor3("baseColor", _this.color);
  54160. effect.setFloat("depth", _this.depth);
  54161. effect.setFloat("colorLevel", _this.colorLevel);
  54162. effect.setTexture("refractionSampler", _this._refRexture);
  54163. });
  54164. return _this;
  54165. }
  54166. // Methods
  54167. RefractionPostProcess.prototype.dispose = function (camera) {
  54168. if (this._refRexture) {
  54169. this._refRexture.dispose();
  54170. }
  54171. _super.prototype.dispose.call(this, camera);
  54172. };
  54173. return RefractionPostProcess;
  54174. }(BABYLON.PostProcess));
  54175. BABYLON.RefractionPostProcess = RefractionPostProcess;
  54176. })(BABYLON || (BABYLON = {}));
  54177. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  54178. var BABYLON;
  54179. (function (BABYLON) {
  54180. var BlackAndWhitePostProcess = (function (_super) {
  54181. __extends(BlackAndWhitePostProcess, _super);
  54182. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  54183. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  54184. _this.degree = 1;
  54185. _this.onApplyObservable.add(function (effect) {
  54186. effect.setFloat("degree", _this.degree);
  54187. });
  54188. return _this;
  54189. }
  54190. return BlackAndWhitePostProcess;
  54191. }(BABYLON.PostProcess));
  54192. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  54193. })(BABYLON || (BABYLON = {}));
  54194. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  54195. var BABYLON;
  54196. (function (BABYLON) {
  54197. var ConvolutionPostProcess = (function (_super) {
  54198. __extends(ConvolutionPostProcess, _super);
  54199. function ConvolutionPostProcess(name, kernel, options, camera, samplingMode, engine, reusable) {
  54200. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable) || this;
  54201. _this.kernel = kernel;
  54202. _this.onApply = function (effect) {
  54203. effect.setFloat2("screenSize", _this.width, _this.height);
  54204. effect.setArray("kernel", _this.kernel);
  54205. };
  54206. return _this;
  54207. }
  54208. // Statics
  54209. // Based on http://en.wikipedia.org/wiki/Kernel_(image_processing)
  54210. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  54211. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  54212. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  54213. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  54214. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  54215. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  54216. return ConvolutionPostProcess;
  54217. }(BABYLON.PostProcess));
  54218. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  54219. })(BABYLON || (BABYLON = {}));
  54220. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  54221. var BABYLON;
  54222. (function (BABYLON) {
  54223. var FilterPostProcess = (function (_super) {
  54224. __extends(FilterPostProcess, _super);
  54225. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  54226. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  54227. _this.kernelMatrix = kernelMatrix;
  54228. _this.onApply = function (effect) {
  54229. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  54230. };
  54231. return _this;
  54232. }
  54233. return FilterPostProcess;
  54234. }(BABYLON.PostProcess));
  54235. BABYLON.FilterPostProcess = FilterPostProcess;
  54236. })(BABYLON || (BABYLON = {}));
  54237. //# sourceMappingURL=babylon.filterPostProcess.js.map
  54238. var BABYLON;
  54239. (function (BABYLON) {
  54240. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  54241. var VolumetricLightScatteringPostProcess = (function (_super) {
  54242. __extends(VolumetricLightScatteringPostProcess, _super);
  54243. /**
  54244. * @constructor
  54245. * @param {string} name - The post-process name
  54246. * @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)
  54247. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  54248. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  54249. * @param {number} samples - The post-process quality, default 100
  54250. * @param {number} samplingMode - The post-process filtering mode
  54251. * @param {BABYLON.Engine} engine - The babylon engine
  54252. * @param {boolean} reusable - If the post-process is reusable
  54253. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  54254. */
  54255. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  54256. if (samples === void 0) { samples = 100; }
  54257. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54258. 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;
  54259. _this._screenCoordinates = BABYLON.Vector2.Zero();
  54260. /**
  54261. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  54262. * @type {Vector3}
  54263. */
  54264. _this.customMeshPosition = BABYLON.Vector3.Zero();
  54265. /**
  54266. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  54267. * @type {boolean}
  54268. */
  54269. _this.useCustomMeshPosition = false;
  54270. /**
  54271. * If the post-process should inverse the light scattering direction
  54272. * @type {boolean}
  54273. */
  54274. _this.invert = true;
  54275. /**
  54276. * Array containing the excluded meshes not rendered in the internal pass
  54277. */
  54278. _this.excludedMeshes = new Array();
  54279. /**
  54280. * Controls the overall intensity of the post-process
  54281. * @type {number}
  54282. */
  54283. _this.exposure = 0.3;
  54284. /**
  54285. * Dissipates each sample's contribution in range [0, 1]
  54286. * @type {number}
  54287. */
  54288. _this.decay = 0.96815;
  54289. /**
  54290. * Controls the overall intensity of each sample
  54291. * @type {number}
  54292. */
  54293. _this.weight = 0.58767;
  54294. /**
  54295. * Controls the density of each sample
  54296. * @type {number}
  54297. */
  54298. _this.density = 0.926;
  54299. scene = (camera === null) ? scene : camera.getScene(); // parameter "scene" can be null.
  54300. var engine = scene.getEngine();
  54301. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  54302. // Configure mesh
  54303. _this.mesh = (mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene);
  54304. // Configure
  54305. _this._createPass(scene, ratio.passRatio || ratio);
  54306. _this.onActivate = function (camera) {
  54307. if (!_this.isSupported) {
  54308. _this.dispose(camera);
  54309. }
  54310. _this.onActivate = null;
  54311. };
  54312. _this.onApplyObservable.add(function (effect) {
  54313. _this._updateMeshScreenCoordinates(scene);
  54314. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  54315. effect.setFloat("exposure", _this.exposure);
  54316. effect.setFloat("decay", _this.decay);
  54317. effect.setFloat("weight", _this.weight);
  54318. effect.setFloat("density", _this.density);
  54319. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  54320. });
  54321. return _this;
  54322. }
  54323. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  54324. get: function () {
  54325. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54326. return false;
  54327. },
  54328. set: function (useDiffuseColor) {
  54329. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  54330. },
  54331. enumerable: true,
  54332. configurable: true
  54333. });
  54334. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  54335. return "VolumetricLightScatteringPostProcess";
  54336. };
  54337. VolumetricLightScatteringPostProcess.prototype.isReady = function (subMesh, useInstances) {
  54338. var mesh = subMesh.getMesh();
  54339. // Render this.mesh as default
  54340. if (mesh === this.mesh) {
  54341. return mesh.material.isReady(mesh);
  54342. }
  54343. var defines = [];
  54344. var attribs = [BABYLON.VertexBuffer.PositionKind];
  54345. var material = subMesh.getMaterial();
  54346. var needUV = false;
  54347. // Alpha test
  54348. if (material) {
  54349. if (material.needAlphaTesting()) {
  54350. defines.push("#define ALPHATEST");
  54351. }
  54352. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54353. attribs.push(BABYLON.VertexBuffer.UVKind);
  54354. defines.push("#define UV1");
  54355. }
  54356. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  54357. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  54358. defines.push("#define UV2");
  54359. }
  54360. }
  54361. // Bones
  54362. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54363. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  54364. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  54365. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  54366. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  54367. }
  54368. else {
  54369. defines.push("#define NUM_BONE_INFLUENCERS 0");
  54370. }
  54371. // Instances
  54372. if (useInstances) {
  54373. defines.push("#define INSTANCES");
  54374. attribs.push("world0");
  54375. attribs.push("world1");
  54376. attribs.push("world2");
  54377. attribs.push("world3");
  54378. }
  54379. // Get correct effect
  54380. var join = defines.join("\n");
  54381. if (this._cachedDefines !== join) {
  54382. this._cachedDefines = join;
  54383. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  54384. }
  54385. return this._volumetricLightScatteringPass.isReady();
  54386. };
  54387. /**
  54388. * Sets the new light position for light scattering effect
  54389. * @param {BABYLON.Vector3} The new custom light position
  54390. */
  54391. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  54392. this.customMeshPosition = position;
  54393. };
  54394. /**
  54395. * Returns the light position for light scattering effect
  54396. * @return {BABYLON.Vector3} The custom light position
  54397. */
  54398. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  54399. return this.customMeshPosition;
  54400. };
  54401. /**
  54402. * Disposes the internal assets and detaches the post-process from the camera
  54403. */
  54404. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  54405. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  54406. if (rttIndex !== -1) {
  54407. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  54408. }
  54409. this._volumetricLightScatteringRTT.dispose();
  54410. _super.prototype.dispose.call(this, camera);
  54411. };
  54412. /**
  54413. * Returns the render target texture used by the post-process
  54414. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  54415. */
  54416. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  54417. return this._volumetricLightScatteringRTT;
  54418. };
  54419. // Private methods
  54420. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  54421. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  54422. return true;
  54423. }
  54424. return false;
  54425. };
  54426. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  54427. var _this = this;
  54428. var engine = scene.getEngine();
  54429. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  54430. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54431. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54432. this._volumetricLightScatteringRTT.renderList = null;
  54433. this._volumetricLightScatteringRTT.renderParticles = false;
  54434. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  54435. // Custom render function for submeshes
  54436. var renderSubMesh = function (subMesh) {
  54437. var mesh = subMesh.getRenderingMesh();
  54438. if (_this._meshExcluded(mesh)) {
  54439. return;
  54440. }
  54441. var scene = mesh.getScene();
  54442. var engine = scene.getEngine();
  54443. // Culling
  54444. engine.setState(subMesh.getMaterial().backFaceCulling);
  54445. // Managing instances
  54446. var batch = mesh._getInstancesRenderList(subMesh._id);
  54447. if (batch.mustReturn) {
  54448. return;
  54449. }
  54450. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  54451. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  54452. var effect = _this._volumetricLightScatteringPass;
  54453. if (mesh === _this.mesh) {
  54454. if (subMesh.effect) {
  54455. effect = subMesh.effect;
  54456. }
  54457. else {
  54458. effect = subMesh.getMaterial().getEffect();
  54459. }
  54460. }
  54461. engine.enableEffect(effect);
  54462. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  54463. if (mesh === _this.mesh) {
  54464. subMesh.getMaterial().bind(mesh.getWorldMatrix(), mesh);
  54465. }
  54466. else {
  54467. var material = subMesh.getMaterial();
  54468. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  54469. // Alpha test
  54470. if (material && material.needAlphaTesting()) {
  54471. var alphaTexture = material.getAlphaTestTexture();
  54472. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  54473. if (alphaTexture) {
  54474. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  54475. }
  54476. }
  54477. // Bones
  54478. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  54479. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  54480. }
  54481. }
  54482. // Draw
  54483. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  54484. }
  54485. };
  54486. // Render target texture callbacks
  54487. var savedSceneClearColor;
  54488. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  54489. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  54490. savedSceneClearColor = scene.clearColor;
  54491. scene.clearColor = sceneClearColor;
  54492. });
  54493. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  54494. scene.clearColor = savedSceneClearColor;
  54495. });
  54496. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  54497. var engine = scene.getEngine();
  54498. var index;
  54499. for (index = 0; index < opaqueSubMeshes.length; index++) {
  54500. renderSubMesh(opaqueSubMeshes.data[index]);
  54501. }
  54502. engine.setAlphaTesting(true);
  54503. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  54504. renderSubMesh(alphaTestSubMeshes.data[index]);
  54505. }
  54506. engine.setAlphaTesting(false);
  54507. if (transparentSubMeshes.length) {
  54508. // Sort sub meshes
  54509. for (index = 0; index < transparentSubMeshes.length; index++) {
  54510. var submesh = transparentSubMeshes.data[index];
  54511. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  54512. submesh._distanceToCamera = submesh.getBoundingInfo().boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  54513. }
  54514. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  54515. sortedArray.sort(function (a, b) {
  54516. // Alpha index first
  54517. if (a._alphaIndex > b._alphaIndex) {
  54518. return 1;
  54519. }
  54520. if (a._alphaIndex < b._alphaIndex) {
  54521. return -1;
  54522. }
  54523. // Then distance to camera
  54524. if (a._distanceToCamera < b._distanceToCamera) {
  54525. return 1;
  54526. }
  54527. if (a._distanceToCamera > b._distanceToCamera) {
  54528. return -1;
  54529. }
  54530. return 0;
  54531. });
  54532. // Render sub meshes
  54533. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54534. for (index = 0; index < sortedArray.length; index++) {
  54535. renderSubMesh(sortedArray[index]);
  54536. }
  54537. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54538. }
  54539. };
  54540. };
  54541. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  54542. var transform = scene.getTransformMatrix();
  54543. var meshPosition;
  54544. if (this.useCustomMeshPosition) {
  54545. meshPosition = this.customMeshPosition;
  54546. }
  54547. else if (this.attachedNode) {
  54548. meshPosition = this.attachedNode.position;
  54549. }
  54550. else {
  54551. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  54552. }
  54553. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  54554. this._screenCoordinates.x = pos.x / this._viewPort.width;
  54555. this._screenCoordinates.y = pos.y / this._viewPort.height;
  54556. if (this.invert)
  54557. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  54558. };
  54559. // Static methods
  54560. /**
  54561. * Creates a default mesh for the Volumeric Light Scattering post-process
  54562. * @param {string} The mesh name
  54563. * @param {BABYLON.Scene} The scene where to create the mesh
  54564. * @return {BABYLON.Mesh} the default mesh
  54565. */
  54566. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  54567. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  54568. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  54569. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  54570. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  54571. mesh.material = material;
  54572. return mesh;
  54573. };
  54574. __decorate([
  54575. BABYLON.serializeAsVector3()
  54576. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  54577. __decorate([
  54578. BABYLON.serialize()
  54579. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  54580. __decorate([
  54581. BABYLON.serialize()
  54582. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  54583. __decorate([
  54584. BABYLON.serializeAsMeshReference()
  54585. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  54586. __decorate([
  54587. BABYLON.serialize()
  54588. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  54589. __decorate([
  54590. BABYLON.serialize()
  54591. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  54592. __decorate([
  54593. BABYLON.serialize()
  54594. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  54595. __decorate([
  54596. BABYLON.serialize()
  54597. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  54598. __decorate([
  54599. BABYLON.serialize()
  54600. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  54601. return VolumetricLightScatteringPostProcess;
  54602. }(BABYLON.PostProcess));
  54603. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  54604. })(BABYLON || (BABYLON = {}));
  54605. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  54606. //
  54607. // This post-process allows the modification of rendered colors by using
  54608. // a 'look-up table' (LUT). This effect is also called Color Grading.
  54609. //
  54610. // The object needs to be provided an url to a texture containing the color
  54611. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  54612. // Use an image editing software to tweak the LUT to match your needs.
  54613. //
  54614. // For an example of a color LUT, see here:
  54615. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  54616. // For explanations on color grading, see here:
  54617. // http://udn.epicgames.com/Three/ColorGrading.html
  54618. //
  54619. var BABYLON;
  54620. (function (BABYLON) {
  54621. var ColorCorrectionPostProcess = (function (_super) {
  54622. __extends(ColorCorrectionPostProcess, _super);
  54623. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  54624. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  54625. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  54626. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  54627. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54628. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54629. _this.onApply = function (effect) {
  54630. effect.setTexture("colorTable", _this._colorTableTexture);
  54631. };
  54632. return _this;
  54633. }
  54634. return ColorCorrectionPostProcess;
  54635. }(BABYLON.PostProcess));
  54636. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  54637. })(BABYLON || (BABYLON = {}));
  54638. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  54639. var BABYLON;
  54640. (function (BABYLON) {
  54641. var TonemappingOperator;
  54642. (function (TonemappingOperator) {
  54643. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  54644. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  54645. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  54646. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  54647. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  54648. ;
  54649. var TonemapPostProcess = (function (_super) {
  54650. __extends(TonemapPostProcess, _super);
  54651. function TonemapPostProcess(name, _operator, exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  54652. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  54653. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54654. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, defines, textureFormat) || this;
  54655. _this._operator = _operator;
  54656. _this.exposureAdjustment = exposureAdjustment;
  54657. var defines = "#define ";
  54658. if (_this._operator === TonemappingOperator.Hable)
  54659. defines += "HABLE_TONEMAPPING";
  54660. else if (_this._operator === TonemappingOperator.Reinhard)
  54661. defines += "REINHARD_TONEMAPPING";
  54662. else if (_this._operator === TonemappingOperator.HejiDawson)
  54663. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  54664. else if (_this._operator === TonemappingOperator.Photographic)
  54665. defines += "PHOTOGRAPHIC_TONEMAPPING";
  54666. //sadly a second call to create the effect.
  54667. _this.updateEffect(defines);
  54668. _this.onApply = function (effect) {
  54669. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  54670. };
  54671. return _this;
  54672. }
  54673. return TonemapPostProcess;
  54674. }(BABYLON.PostProcess));
  54675. BABYLON.TonemapPostProcess = TonemapPostProcess;
  54676. })(BABYLON || (BABYLON = {}));
  54677. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  54678. var BABYLON;
  54679. (function (BABYLON) {
  54680. var DisplayPassPostProcess = (function (_super) {
  54681. __extends(DisplayPassPostProcess, _super);
  54682. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  54683. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  54684. }
  54685. return DisplayPassPostProcess;
  54686. }(BABYLON.PostProcess));
  54687. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  54688. })(BABYLON || (BABYLON = {}));
  54689. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  54690. var BABYLON;
  54691. (function (BABYLON) {
  54692. var HighlightsPostProcess = (function (_super) {
  54693. __extends(HighlightsPostProcess, _super);
  54694. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54695. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54696. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  54697. }
  54698. return HighlightsPostProcess;
  54699. }(BABYLON.PostProcess));
  54700. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  54701. })(BABYLON || (BABYLON = {}));
  54702. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  54703. var BABYLON;
  54704. (function (BABYLON) {
  54705. var ImageProcessingPostProcess = (function (_super) {
  54706. __extends(ImageProcessingPostProcess, _super);
  54707. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  54708. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  54709. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  54710. _this._fromLinearSpace = true;
  54711. /**
  54712. * Defines cache preventing GC.
  54713. */
  54714. _this._defines = {
  54715. IMAGEPROCESSING: false,
  54716. VIGNETTE: false,
  54717. VIGNETTEBLENDMODEMULTIPLY: false,
  54718. VIGNETTEBLENDMODEOPAQUE: false,
  54719. TONEMAPPING: false,
  54720. CONTRAST: false,
  54721. COLORCURVES: false,
  54722. COLORGRADING: false,
  54723. FROMLINEARSPACE: false,
  54724. SAMPLER3DGREENDEPTH: false,
  54725. SAMPLER3DBGRMAP: false,
  54726. IMAGEPROCESSINGPOSTPROCESS: false,
  54727. EXPOSURE: false,
  54728. };
  54729. // Setup the default processing configuration to the scene.
  54730. _this._attachImageProcessingConfiguration(null, true);
  54731. _this.imageProcessingConfiguration.applyByPostProcess = true;
  54732. _this.onApply = function (effect) {
  54733. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  54734. };
  54735. return _this;
  54736. }
  54737. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  54738. /**
  54739. * Gets the image processing configuration used either in this material.
  54740. */
  54741. get: function () {
  54742. return this._imageProcessingConfiguration;
  54743. },
  54744. /**
  54745. * Sets the Default image processing configuration used either in the this material.
  54746. *
  54747. * If sets to null, the scene one is in use.
  54748. */
  54749. set: function (value) {
  54750. this._attachImageProcessingConfiguration(value);
  54751. },
  54752. enumerable: true,
  54753. configurable: true
  54754. });
  54755. /**
  54756. * Attaches a new image processing configuration to the PBR Material.
  54757. * @param configuration
  54758. */
  54759. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  54760. var _this = this;
  54761. if (doNotBuild === void 0) { doNotBuild = false; }
  54762. if (configuration === this._imageProcessingConfiguration) {
  54763. return;
  54764. }
  54765. // Detaches observer.
  54766. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  54767. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  54768. }
  54769. // Pick the scene configuration if needed.
  54770. if (!configuration) {
  54771. var camera = this.getCamera();
  54772. var scene = camera ? camera.getScene() : BABYLON.Engine.LastCreatedScene;
  54773. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  54774. }
  54775. else {
  54776. this._imageProcessingConfiguration = configuration;
  54777. }
  54778. // Attaches observer.
  54779. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  54780. _this._updateParameters();
  54781. });
  54782. // Ensure the effect will be rebuilt.
  54783. if (!doNotBuild) {
  54784. this._updateParameters();
  54785. }
  54786. };
  54787. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  54788. /**
  54789. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54790. */
  54791. get: function () {
  54792. return this.imageProcessingConfiguration.colorCurves;
  54793. },
  54794. /**
  54795. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  54796. */
  54797. set: function (value) {
  54798. this.imageProcessingConfiguration.colorCurves = value;
  54799. },
  54800. enumerable: true,
  54801. configurable: true
  54802. });
  54803. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  54804. /**
  54805. * Gets wether the color curves effect is enabled.
  54806. */
  54807. get: function () {
  54808. return this.imageProcessingConfiguration.colorCurvesEnabled;
  54809. },
  54810. /**
  54811. * Sets wether the color curves effect is enabled.
  54812. */
  54813. set: function (value) {
  54814. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  54815. },
  54816. enumerable: true,
  54817. configurable: true
  54818. });
  54819. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  54820. /**
  54821. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54822. */
  54823. get: function () {
  54824. return this.imageProcessingConfiguration.colorGradingTexture;
  54825. },
  54826. /**
  54827. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  54828. */
  54829. set: function (value) {
  54830. this.imageProcessingConfiguration.colorGradingTexture = value;
  54831. },
  54832. enumerable: true,
  54833. configurable: true
  54834. });
  54835. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  54836. /**
  54837. * Gets wether the color grading effect is enabled.
  54838. */
  54839. get: function () {
  54840. return this.imageProcessingConfiguration.colorGradingEnabled;
  54841. },
  54842. /**
  54843. * Gets wether the color grading effect is enabled.
  54844. */
  54845. set: function (value) {
  54846. this.imageProcessingConfiguration.colorGradingEnabled = value;
  54847. },
  54848. enumerable: true,
  54849. configurable: true
  54850. });
  54851. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  54852. /**
  54853. * Gets exposure used in the effect.
  54854. */
  54855. get: function () {
  54856. return this.imageProcessingConfiguration.exposure;
  54857. },
  54858. /**
  54859. * Sets exposure used in the effect.
  54860. */
  54861. set: function (value) {
  54862. this.imageProcessingConfiguration.exposure = value;
  54863. },
  54864. enumerable: true,
  54865. configurable: true
  54866. });
  54867. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  54868. /**
  54869. * Gets wether tonemapping is enabled or not.
  54870. */
  54871. get: function () {
  54872. return this._imageProcessingConfiguration.toneMappingEnabled;
  54873. },
  54874. /**
  54875. * Sets wether tonemapping is enabled or not
  54876. */
  54877. set: function (value) {
  54878. this._imageProcessingConfiguration.toneMappingEnabled = value;
  54879. },
  54880. enumerable: true,
  54881. configurable: true
  54882. });
  54883. ;
  54884. ;
  54885. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  54886. /**
  54887. * Gets contrast used in the effect.
  54888. */
  54889. get: function () {
  54890. return this.imageProcessingConfiguration.contrast;
  54891. },
  54892. /**
  54893. * Sets contrast used in the effect.
  54894. */
  54895. set: function (value) {
  54896. this.imageProcessingConfiguration.contrast = value;
  54897. },
  54898. enumerable: true,
  54899. configurable: true
  54900. });
  54901. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  54902. /**
  54903. * Gets Vignette stretch size.
  54904. */
  54905. get: function () {
  54906. return this.imageProcessingConfiguration.vignetteStretch;
  54907. },
  54908. /**
  54909. * Sets Vignette stretch size.
  54910. */
  54911. set: function (value) {
  54912. this.imageProcessingConfiguration.vignetteStretch = value;
  54913. },
  54914. enumerable: true,
  54915. configurable: true
  54916. });
  54917. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  54918. /**
  54919. * Gets Vignette centre X Offset.
  54920. */
  54921. get: function () {
  54922. return this.imageProcessingConfiguration.vignetteCentreX;
  54923. },
  54924. /**
  54925. * Sets Vignette centre X Offset.
  54926. */
  54927. set: function (value) {
  54928. this.imageProcessingConfiguration.vignetteCentreX = value;
  54929. },
  54930. enumerable: true,
  54931. configurable: true
  54932. });
  54933. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  54934. /**
  54935. * Gets Vignette centre Y Offset.
  54936. */
  54937. get: function () {
  54938. return this.imageProcessingConfiguration.vignetteCentreY;
  54939. },
  54940. /**
  54941. * Sets Vignette centre Y Offset.
  54942. */
  54943. set: function (value) {
  54944. this.imageProcessingConfiguration.vignetteCentreY = value;
  54945. },
  54946. enumerable: true,
  54947. configurable: true
  54948. });
  54949. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  54950. /**
  54951. * Gets Vignette weight or intensity of the vignette effect.
  54952. */
  54953. get: function () {
  54954. return this.imageProcessingConfiguration.vignetteWeight;
  54955. },
  54956. /**
  54957. * Sets Vignette weight or intensity of the vignette effect.
  54958. */
  54959. set: function (value) {
  54960. this.imageProcessingConfiguration.vignetteWeight = value;
  54961. },
  54962. enumerable: true,
  54963. configurable: true
  54964. });
  54965. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  54966. /**
  54967. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54968. * if vignetteEnabled is set to true.
  54969. */
  54970. get: function () {
  54971. return this.imageProcessingConfiguration.vignetteColor;
  54972. },
  54973. /**
  54974. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  54975. * if vignetteEnabled is set to true.
  54976. */
  54977. set: function (value) {
  54978. this.imageProcessingConfiguration.vignetteColor = value;
  54979. },
  54980. enumerable: true,
  54981. configurable: true
  54982. });
  54983. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  54984. /**
  54985. * Gets Camera field of view used by the Vignette effect.
  54986. */
  54987. get: function () {
  54988. return this.imageProcessingConfiguration.vignetteCameraFov;
  54989. },
  54990. /**
  54991. * Sets Camera field of view used by the Vignette effect.
  54992. */
  54993. set: function (value) {
  54994. this.imageProcessingConfiguration.vignetteCameraFov = value;
  54995. },
  54996. enumerable: true,
  54997. configurable: true
  54998. });
  54999. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  55000. /**
  55001. * Gets the vignette blend mode allowing different kind of effect.
  55002. */
  55003. get: function () {
  55004. return this.imageProcessingConfiguration.vignetteBlendMode;
  55005. },
  55006. /**
  55007. * Sets the vignette blend mode allowing different kind of effect.
  55008. */
  55009. set: function (value) {
  55010. this.imageProcessingConfiguration.vignetteBlendMode = value;
  55011. },
  55012. enumerable: true,
  55013. configurable: true
  55014. });
  55015. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  55016. /**
  55017. * Gets wether the vignette effect is enabled.
  55018. */
  55019. get: function () {
  55020. return this.imageProcessingConfiguration.vignetteEnabled;
  55021. },
  55022. /**
  55023. * Sets wether the vignette effect is enabled.
  55024. */
  55025. set: function (value) {
  55026. this.imageProcessingConfiguration.vignetteEnabled = value;
  55027. },
  55028. enumerable: true,
  55029. configurable: true
  55030. });
  55031. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  55032. /**
  55033. * Gets wether the input of the processing is in Gamma or Linear Space.
  55034. */
  55035. get: function () {
  55036. return this._fromLinearSpace;
  55037. },
  55038. /**
  55039. * Sets wether the input of the processing is in Gamma or Linear Space.
  55040. */
  55041. set: function (value) {
  55042. if (this._fromLinearSpace === value) {
  55043. return;
  55044. }
  55045. this._fromLinearSpace = value;
  55046. this._updateParameters();
  55047. },
  55048. enumerable: true,
  55049. configurable: true
  55050. });
  55051. ImageProcessingPostProcess.prototype.getClassName = function () {
  55052. return "ImageProcessingPostProcess";
  55053. };
  55054. ImageProcessingPostProcess.prototype._updateParameters = function () {
  55055. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  55056. this.imageProcessingConfiguration.prepareDefines(this._defines);
  55057. var defines = "";
  55058. for (var define in this._defines) {
  55059. if (this._defines[define]) {
  55060. defines += "#define " + define + ";\r\n";
  55061. }
  55062. }
  55063. var samplers = ["textureSampler"];
  55064. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  55065. var uniforms = ["scale"];
  55066. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  55067. this.updateEffect(defines, uniforms, samplers);
  55068. };
  55069. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  55070. _super.prototype.dispose.call(this, camera);
  55071. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  55072. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  55073. }
  55074. this.imageProcessingConfiguration.applyByPostProcess = false;
  55075. };
  55076. __decorate([
  55077. BABYLON.serialize()
  55078. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  55079. return ImageProcessingPostProcess;
  55080. }(BABYLON.PostProcess));
  55081. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  55082. })(BABYLON || (BABYLON = {}));
  55083. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  55084. var BABYLON;
  55085. (function (BABYLON) {
  55086. var BlurPostProcess = (function (_super) {
  55087. __extends(BlurPostProcess, _super);
  55088. function BlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable, textureType) {
  55089. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  55090. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  55091. var _this = _super.call(this, name, "kernelBlur", ["delta", "direction"], null, options, camera, samplingMode, engine, reusable, null, textureType, "kernelBlur", { varyingCount: 0, depCount: 0 }, true) || this;
  55092. _this.direction = direction;
  55093. _this._packedFloat = false;
  55094. _this.onApplyObservable.add(function (effect) {
  55095. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  55096. });
  55097. _this.kernel = kernel;
  55098. return _this;
  55099. }
  55100. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  55101. /**
  55102. * Gets the length in pixels of the blur sample region
  55103. */
  55104. get: function () {
  55105. return this._idealKernel;
  55106. },
  55107. /**
  55108. * Sets the length in pixels of the blur sample region
  55109. */
  55110. set: function (v) {
  55111. if (this._idealKernel === v) {
  55112. return;
  55113. }
  55114. v = Math.max(v, 1);
  55115. this._idealKernel = v;
  55116. this._kernel = this._nearestBestKernel(v);
  55117. this._updateParameters();
  55118. },
  55119. enumerable: true,
  55120. configurable: true
  55121. });
  55122. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  55123. /**
  55124. * Gets wether or not the blur is unpacking/repacking floats
  55125. */
  55126. get: function () {
  55127. return this._packedFloat;
  55128. },
  55129. /**
  55130. * Sets wether or not the blur needs to unpack/repack floats
  55131. */
  55132. set: function (v) {
  55133. if (this._packedFloat === v) {
  55134. return;
  55135. }
  55136. this._packedFloat = v;
  55137. this._updateParameters();
  55138. },
  55139. enumerable: true,
  55140. configurable: true
  55141. });
  55142. BlurPostProcess.prototype._updateParameters = function () {
  55143. // Generate sampling offsets and weights
  55144. var N = this._kernel;
  55145. var centerIndex = (N - 1) / 2;
  55146. // Generate Gaussian sampling weights over kernel
  55147. var offsets = [];
  55148. var weights = [];
  55149. var totalWeight = 0;
  55150. for (var i = 0; i < N; i++) {
  55151. var u = i / (N - 1);
  55152. var w = this._gaussianWeight(u * 2.0 - 1);
  55153. offsets[i] = (i - centerIndex);
  55154. weights[i] = w;
  55155. totalWeight += w;
  55156. }
  55157. // Normalize weights
  55158. for (var i = 0; i < weights.length; i++) {
  55159. weights[i] /= totalWeight;
  55160. }
  55161. // Optimize: combine samples to take advantage of hardware linear sampling
  55162. // Walk from left to center, combining pairs (symmetrically)
  55163. var linearSamplingWeights = [];
  55164. var linearSamplingOffsets = [];
  55165. var linearSamplingMap = [];
  55166. for (var i = 0; i <= centerIndex; i += 2) {
  55167. var j = Math.min(i + 1, Math.floor(centerIndex));
  55168. var singleCenterSample = i === j;
  55169. if (singleCenterSample) {
  55170. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55171. }
  55172. else {
  55173. var sharedCell = j === centerIndex;
  55174. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  55175. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  55176. if (offsetLinear === 0) {
  55177. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  55178. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  55179. }
  55180. else {
  55181. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  55182. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  55183. }
  55184. }
  55185. }
  55186. for (var i = 0; i < linearSamplingMap.length; i++) {
  55187. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  55188. linearSamplingWeights[i] = linearSamplingMap[i].w;
  55189. }
  55190. // Replace with optimized
  55191. offsets = linearSamplingOffsets;
  55192. weights = linearSamplingWeights;
  55193. // Generate shaders
  55194. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  55195. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  55196. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  55197. var defines = "";
  55198. for (var i = 0; i < varyingCount; i++) {
  55199. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  55200. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  55201. }
  55202. var depCount = 0;
  55203. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  55204. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  55205. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  55206. depCount++;
  55207. }
  55208. if (this.packedFloat) {
  55209. defines += "#define PACKEDFLOAT 1";
  55210. }
  55211. this.updateEffect(defines, null, null, {
  55212. varyingCount: varyingCount,
  55213. depCount: depCount
  55214. });
  55215. };
  55216. /**
  55217. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  55218. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  55219. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  55220. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  55221. * The gaps between physical kernels are compensated for in the weighting of the samples
  55222. * @param idealKernel Ideal blur kernel.
  55223. * @return Nearest best kernel.
  55224. */
  55225. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  55226. var v = Math.round(idealKernel);
  55227. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  55228. var k = _a[_i];
  55229. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  55230. return Math.max(k, 3);
  55231. }
  55232. }
  55233. return Math.max(v, 3);
  55234. };
  55235. /**
  55236. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  55237. * @param x The point on the Gaussian distribution to sample.
  55238. * @return the value of the Gaussian function at x.
  55239. */
  55240. BlurPostProcess.prototype._gaussianWeight = function (x) {
  55241. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  55242. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  55243. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  55244. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  55245. // truncated at around 1.3% of peak strength.
  55246. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  55247. var sigma = (1 / 3);
  55248. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  55249. var exponent = -((x * x) / (2.0 * sigma * sigma));
  55250. var weight = (1.0 / denominator) * Math.exp(exponent);
  55251. return weight;
  55252. };
  55253. /**
  55254. * Generates a string that can be used as a floating point number in GLSL.
  55255. * @param x Value to print.
  55256. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  55257. * @return GLSL float string.
  55258. */
  55259. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  55260. if (decimalFigures === void 0) { decimalFigures = 8; }
  55261. return x.toFixed(decimalFigures).replace(/0+$/, '');
  55262. };
  55263. return BlurPostProcess;
  55264. }(BABYLON.PostProcess));
  55265. BABYLON.BlurPostProcess = BlurPostProcess;
  55266. })(BABYLON || (BABYLON = {}));
  55267. //# sourceMappingURL=babylon.blurPostProcess.js.map
  55268. /// <reference path="..\babylon.node.ts" />
  55269. var BABYLON;
  55270. (function (BABYLON) {
  55271. var Bone = (function (_super) {
  55272. __extends(Bone, _super);
  55273. function Bone(name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  55274. if (parentBone === void 0) { parentBone = null; }
  55275. var _this = _super.call(this, name, skeleton.getScene()) || this;
  55276. _this.name = name;
  55277. _this.children = new Array();
  55278. _this.animations = new Array();
  55279. _this._worldTransform = new BABYLON.Matrix();
  55280. _this._absoluteTransform = new BABYLON.Matrix();
  55281. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  55282. _this._scaleMatrix = BABYLON.Matrix.Identity();
  55283. _this._scaleVector = BABYLON.Vector3.One();
  55284. _this._negateScaleChildren = BABYLON.Vector3.One();
  55285. _this._scalingDeterminant = 1;
  55286. _this._skeleton = skeleton;
  55287. _this._localMatrix = localMatrix ? localMatrix : BABYLON.Matrix.Identity();
  55288. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  55289. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  55290. _this._index = index;
  55291. skeleton.bones.push(_this);
  55292. _this.setParent(parentBone, false);
  55293. _this._updateDifferenceMatrix();
  55294. return _this;
  55295. }
  55296. Object.defineProperty(Bone.prototype, "_matrix", {
  55297. get: function () {
  55298. return this._localMatrix;
  55299. },
  55300. set: function (val) {
  55301. if (this._localMatrix) {
  55302. this._localMatrix.copyFrom(val);
  55303. }
  55304. else {
  55305. this._localMatrix = val;
  55306. }
  55307. },
  55308. enumerable: true,
  55309. configurable: true
  55310. });
  55311. // Members
  55312. Bone.prototype.getSkeleton = function () {
  55313. return this._skeleton;
  55314. };
  55315. Bone.prototype.getParent = function () {
  55316. return this._parent;
  55317. };
  55318. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  55319. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55320. if (this._parent === parent) {
  55321. return;
  55322. }
  55323. if (this._parent) {
  55324. var index = this._parent.children.indexOf(this);
  55325. if (index !== -1) {
  55326. this._parent.children.splice(index);
  55327. }
  55328. }
  55329. this._parent = parent;
  55330. if (this._parent) {
  55331. this._parent.children.push(this);
  55332. }
  55333. if (updateDifferenceMatrix) {
  55334. this._updateDifferenceMatrix();
  55335. }
  55336. };
  55337. Bone.prototype.getLocalMatrix = function () {
  55338. return this._localMatrix;
  55339. };
  55340. Bone.prototype.getBaseMatrix = function () {
  55341. return this._baseMatrix;
  55342. };
  55343. Bone.prototype.getRestPose = function () {
  55344. return this._restPose;
  55345. };
  55346. Bone.prototype.returnToRest = function () {
  55347. this.updateMatrix(this._restPose.clone());
  55348. };
  55349. Bone.prototype.getWorldMatrix = function () {
  55350. return this._worldTransform;
  55351. };
  55352. Bone.prototype.getInvertedAbsoluteTransform = function () {
  55353. return this._invertedAbsoluteTransform;
  55354. };
  55355. Bone.prototype.getAbsoluteTransform = function () {
  55356. return this._absoluteTransform;
  55357. };
  55358. Object.defineProperty(Bone.prototype, "position", {
  55359. // Properties (matches AbstractMesh properties)
  55360. get: function () {
  55361. return this.getPosition();
  55362. },
  55363. set: function (newPosition) {
  55364. this.setPosition(newPosition);
  55365. },
  55366. enumerable: true,
  55367. configurable: true
  55368. });
  55369. Object.defineProperty(Bone.prototype, "rotation", {
  55370. get: function () {
  55371. return this.getRotation();
  55372. },
  55373. set: function (newRotation) {
  55374. this.setRotation(newRotation);
  55375. },
  55376. enumerable: true,
  55377. configurable: true
  55378. });
  55379. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  55380. get: function () {
  55381. return this.getRotationQuaternion();
  55382. },
  55383. set: function (newRotation) {
  55384. this.setRotationQuaternion(newRotation);
  55385. },
  55386. enumerable: true,
  55387. configurable: true
  55388. });
  55389. Object.defineProperty(Bone.prototype, "scaling", {
  55390. get: function () {
  55391. return this.getScale();
  55392. },
  55393. set: function (newScaling) {
  55394. this.setScale(newScaling.x, newScaling.y, newScaling.z);
  55395. },
  55396. enumerable: true,
  55397. configurable: true
  55398. });
  55399. // Methods
  55400. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix) {
  55401. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  55402. this._baseMatrix = matrix.clone();
  55403. this._localMatrix = matrix.clone();
  55404. this._skeleton._markAsDirty();
  55405. if (updateDifferenceMatrix) {
  55406. this._updateDifferenceMatrix();
  55407. }
  55408. };
  55409. Bone.prototype._updateDifferenceMatrix = function (rootMatrix) {
  55410. if (!rootMatrix) {
  55411. rootMatrix = this._baseMatrix;
  55412. }
  55413. if (this._parent) {
  55414. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55415. }
  55416. else {
  55417. this._absoluteTransform.copyFrom(rootMatrix);
  55418. }
  55419. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  55420. for (var index = 0; index < this.children.length; index++) {
  55421. this.children[index]._updateDifferenceMatrix();
  55422. }
  55423. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  55424. };
  55425. Bone.prototype.markAsDirty = function () {
  55426. this._currentRenderId++;
  55427. this._skeleton._markAsDirty();
  55428. };
  55429. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  55430. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  55431. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  55432. // all animation may be coming from a library skeleton, so may need to create animation
  55433. if (this.animations.length === 0) {
  55434. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  55435. this.animations[0].setKeys([]);
  55436. }
  55437. // get animation info / verify there is such a range from the source bone
  55438. var sourceRange = source.animations[0].getRange(rangeName);
  55439. if (!sourceRange) {
  55440. return false;
  55441. }
  55442. var from = sourceRange.from;
  55443. var to = sourceRange.to;
  55444. var sourceKeys = source.animations[0].getKeys();
  55445. // rescaling prep
  55446. var sourceBoneLength = source.length;
  55447. var sourceParent = source.getParent();
  55448. var parent = this.getParent();
  55449. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  55450. var parentRatio = parentScalingReqd ? parent.length / sourceParent.length : null;
  55451. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  55452. var destKeys = this.animations[0].getKeys();
  55453. // loop vars declaration
  55454. var orig;
  55455. var origTranslation;
  55456. var mat;
  55457. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  55458. orig = sourceKeys[key];
  55459. if (orig.frame >= from && orig.frame <= to) {
  55460. if (rescaleAsRequired) {
  55461. mat = orig.value.clone();
  55462. // scale based on parent ratio, when bone has parent
  55463. if (parentScalingReqd) {
  55464. origTranslation = mat.getTranslation();
  55465. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  55466. // scale based on skeleton dimension ratio when root bone, and value is passed
  55467. }
  55468. else if (dimensionsScalingReqd) {
  55469. origTranslation = mat.getTranslation();
  55470. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  55471. // use original when root bone, and no data for skelDimensionsRatio
  55472. }
  55473. else {
  55474. mat = orig.value;
  55475. }
  55476. }
  55477. else {
  55478. mat = orig.value;
  55479. }
  55480. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  55481. }
  55482. }
  55483. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  55484. return true;
  55485. };
  55486. /**
  55487. * Translate the bone in local or world space.
  55488. * @param vec The amount to translate the bone.
  55489. * @param space The space that the translation is in.
  55490. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55491. */
  55492. Bone.prototype.translate = function (vec, space, mesh) {
  55493. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55494. var lm = this.getLocalMatrix();
  55495. if (space == BABYLON.Space.LOCAL) {
  55496. lm.m[12] += vec.x;
  55497. lm.m[13] += vec.y;
  55498. lm.m[14] += vec.z;
  55499. }
  55500. else {
  55501. var wm;
  55502. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55503. if (mesh) {
  55504. wm = mesh.getWorldMatrix();
  55505. }
  55506. this._skeleton.computeAbsoluteTransforms();
  55507. var tmat = Bone._tmpMats[0];
  55508. var tvec = Bone._tmpVecs[0];
  55509. if (mesh) {
  55510. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55511. tmat.multiplyToRef(wm, tmat);
  55512. }
  55513. else {
  55514. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55515. }
  55516. tmat.m[12] = 0;
  55517. tmat.m[13] = 0;
  55518. tmat.m[14] = 0;
  55519. tmat.invert();
  55520. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  55521. lm.m[12] += tvec.x;
  55522. lm.m[13] += tvec.y;
  55523. lm.m[14] += tvec.z;
  55524. }
  55525. this.markAsDirty();
  55526. };
  55527. /**
  55528. * Set the postion of the bone in local or world space.
  55529. * @param position The position to set the bone.
  55530. * @param space The space that the position is in.
  55531. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55532. */
  55533. Bone.prototype.setPosition = function (position, space, mesh) {
  55534. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55535. var lm = this.getLocalMatrix();
  55536. if (space == BABYLON.Space.LOCAL) {
  55537. lm.m[12] = position.x;
  55538. lm.m[13] = position.y;
  55539. lm.m[14] = position.z;
  55540. }
  55541. else {
  55542. var wm;
  55543. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55544. if (mesh) {
  55545. wm = mesh.getWorldMatrix();
  55546. }
  55547. this._skeleton.computeAbsoluteTransforms();
  55548. var tmat = Bone._tmpMats[0];
  55549. var vec = Bone._tmpVecs[0];
  55550. if (mesh) {
  55551. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55552. tmat.multiplyToRef(wm, tmat);
  55553. }
  55554. else {
  55555. tmat.copyFrom(this._parent.getAbsoluteTransform());
  55556. }
  55557. tmat.invert();
  55558. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  55559. lm.m[12] = vec.x;
  55560. lm.m[13] = vec.y;
  55561. lm.m[14] = vec.z;
  55562. }
  55563. this.markAsDirty();
  55564. };
  55565. /**
  55566. * Set the absolute postion of the bone (world space).
  55567. * @param position The position to set the bone.
  55568. * @param mesh The mesh that this bone is attached to.
  55569. */
  55570. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  55571. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  55572. };
  55573. /**
  55574. * Set the scale of the bone on the x, y and z axes.
  55575. * @param x The scale of the bone on the x axis.
  55576. * @param x The scale of the bone on the y axis.
  55577. * @param z The scale of the bone on the z axis.
  55578. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55579. */
  55580. Bone.prototype.setScale = function (x, y, z, scaleChildren) {
  55581. if (scaleChildren === void 0) { scaleChildren = false; }
  55582. if (this.animations[0] && !this.animations[0].isStopped()) {
  55583. if (!scaleChildren) {
  55584. this._negateScaleChildren.x = 1 / x;
  55585. this._negateScaleChildren.y = 1 / y;
  55586. this._negateScaleChildren.z = 1 / z;
  55587. }
  55588. this._syncScaleVector();
  55589. }
  55590. this.scale(x / this._scaleVector.x, y / this._scaleVector.y, z / this._scaleVector.z, scaleChildren);
  55591. };
  55592. /**
  55593. * Scale the bone on the x, y and z axes.
  55594. * @param x The amount to scale the bone on the x axis.
  55595. * @param x The amount to scale the bone on the y axis.
  55596. * @param z The amount to scale the bone on the z axis.
  55597. * @param scaleChildren Set this to true if children of the bone should be scaled.
  55598. */
  55599. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  55600. if (scaleChildren === void 0) { scaleChildren = false; }
  55601. var locMat = this.getLocalMatrix();
  55602. var origLocMat = Bone._tmpMats[0];
  55603. origLocMat.copyFrom(locMat);
  55604. var origLocMatInv = Bone._tmpMats[1];
  55605. origLocMatInv.copyFrom(origLocMat);
  55606. origLocMatInv.invert();
  55607. var scaleMat = Bone._tmpMats[2];
  55608. BABYLON.Matrix.FromValuesToRef(x, 0, 0, 0, 0, y, 0, 0, 0, 0, z, 0, 0, 0, 0, 1, scaleMat);
  55609. this._scaleMatrix.multiplyToRef(scaleMat, this._scaleMatrix);
  55610. this._scaleVector.x *= x;
  55611. this._scaleVector.y *= y;
  55612. this._scaleVector.z *= z;
  55613. locMat.multiplyToRef(origLocMatInv, locMat);
  55614. locMat.multiplyToRef(scaleMat, locMat);
  55615. locMat.multiplyToRef(origLocMat, locMat);
  55616. var parent = this.getParent();
  55617. if (parent) {
  55618. locMat.multiplyToRef(parent.getAbsoluteTransform(), this.getAbsoluteTransform());
  55619. }
  55620. else {
  55621. this.getAbsoluteTransform().copyFrom(locMat);
  55622. }
  55623. var len = this.children.length;
  55624. scaleMat.invert();
  55625. for (var i = 0; i < len; i++) {
  55626. var child = this.children[i];
  55627. var cm = child.getLocalMatrix();
  55628. cm.multiplyToRef(scaleMat, cm);
  55629. var lm = child.getLocalMatrix();
  55630. lm.m[12] *= x;
  55631. lm.m[13] *= y;
  55632. lm.m[14] *= z;
  55633. }
  55634. this.computeAbsoluteTransforms();
  55635. if (scaleChildren) {
  55636. for (var i = 0; i < len; i++) {
  55637. this.children[i].scale(x, y, z, scaleChildren);
  55638. }
  55639. }
  55640. this.markAsDirty();
  55641. };
  55642. /**
  55643. * Set the yaw, pitch, and roll of the bone in local or world space.
  55644. * @param yaw The rotation of the bone on the y axis.
  55645. * @param pitch The rotation of the bone on the x axis.
  55646. * @param roll The rotation of the bone on the z axis.
  55647. * @param space The space that the axes of rotation are in.
  55648. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55649. */
  55650. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  55651. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55652. var rotMat = Bone._tmpMats[0];
  55653. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  55654. var rotMatInv = Bone._tmpMats[1];
  55655. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55656. rotMatInv.multiplyToRef(rotMat, rotMat);
  55657. this._rotateWithMatrix(rotMat, space, mesh);
  55658. };
  55659. /**
  55660. * Rotate the bone on an axis in local or world space.
  55661. * @param axis The axis to rotate the bone on.
  55662. * @param amount The amount to rotate the bone.
  55663. * @param space The space that the axis is in.
  55664. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55665. */
  55666. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  55667. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55668. var rmat = Bone._tmpMats[0];
  55669. rmat.m[12] = 0;
  55670. rmat.m[13] = 0;
  55671. rmat.m[14] = 0;
  55672. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  55673. this._rotateWithMatrix(rmat, space, mesh);
  55674. };
  55675. /**
  55676. * Set the rotation of the bone to a particular axis angle in local or world space.
  55677. * @param axis The axis to rotate the bone on.
  55678. * @param angle The angle that the bone should be rotated to.
  55679. * @param space The space that the axis is in.
  55680. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55681. */
  55682. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  55683. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55684. var rotMat = Bone._tmpMats[0];
  55685. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  55686. var rotMatInv = Bone._tmpMats[1];
  55687. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55688. rotMatInv.multiplyToRef(rotMat, rotMat);
  55689. this._rotateWithMatrix(rotMat, space, mesh);
  55690. };
  55691. /**
  55692. * Set the euler rotation of the bone in local of world space.
  55693. * @param rotation The euler rotation that the bone should be set to.
  55694. * @param space The space that the rotation is in.
  55695. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55696. */
  55697. Bone.prototype.setRotation = function (rotation, space, mesh) {
  55698. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55699. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  55700. };
  55701. /**
  55702. * Set the quaternion rotation of the bone in local of world space.
  55703. * @param quat The quaternion rotation that the bone should be set to.
  55704. * @param space The space that the rotation is in.
  55705. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55706. */
  55707. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  55708. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55709. var rotMatInv = Bone._tmpMats[0];
  55710. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55711. var rotMat = Bone._tmpMats[1];
  55712. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  55713. rotMatInv.multiplyToRef(rotMat, rotMat);
  55714. this._rotateWithMatrix(rotMat, space, mesh);
  55715. };
  55716. /**
  55717. * Set the rotation matrix of the bone in local of world space.
  55718. * @param rotMat The rotation matrix that the bone should be set to.
  55719. * @param space The space that the rotation is in.
  55720. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55721. */
  55722. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  55723. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55724. var rotMatInv = Bone._tmpMats[0];
  55725. this._getNegativeRotationToRef(rotMatInv, space, mesh);
  55726. var rotMat2 = Bone._tmpMats[1];
  55727. rotMat2.copyFrom(rotMat);
  55728. rotMatInv.multiplyToRef(rotMat, rotMat2);
  55729. this._rotateWithMatrix(rotMat2, space, mesh);
  55730. };
  55731. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  55732. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55733. var lmat = this.getLocalMatrix();
  55734. var lx = lmat.m[12];
  55735. var ly = lmat.m[13];
  55736. var lz = lmat.m[14];
  55737. var parent = this.getParent();
  55738. var parentScale = Bone._tmpMats[3];
  55739. var parentScaleInv = Bone._tmpMats[4];
  55740. if (parent) {
  55741. if (space == BABYLON.Space.WORLD) {
  55742. if (mesh) {
  55743. parentScale.copyFrom(mesh.getWorldMatrix());
  55744. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  55745. }
  55746. else {
  55747. parentScale.copyFrom(parent.getAbsoluteTransform());
  55748. }
  55749. }
  55750. else {
  55751. parentScale = parent._scaleMatrix;
  55752. }
  55753. parentScaleInv.copyFrom(parentScale);
  55754. parentScaleInv.invert();
  55755. lmat.multiplyToRef(parentScale, lmat);
  55756. lmat.multiplyToRef(rmat, lmat);
  55757. lmat.multiplyToRef(parentScaleInv, lmat);
  55758. }
  55759. else {
  55760. if (space == BABYLON.Space.WORLD && mesh) {
  55761. parentScale.copyFrom(mesh.getWorldMatrix());
  55762. parentScaleInv.copyFrom(parentScale);
  55763. parentScaleInv.invert();
  55764. lmat.multiplyToRef(parentScale, lmat);
  55765. lmat.multiplyToRef(rmat, lmat);
  55766. lmat.multiplyToRef(parentScaleInv, lmat);
  55767. }
  55768. else {
  55769. lmat.multiplyToRef(rmat, lmat);
  55770. }
  55771. }
  55772. lmat.m[12] = lx;
  55773. lmat.m[13] = ly;
  55774. lmat.m[14] = lz;
  55775. this.computeAbsoluteTransforms();
  55776. this.markAsDirty();
  55777. };
  55778. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, space, mesh) {
  55779. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55780. if (space == BABYLON.Space.WORLD) {
  55781. var scaleMatrix = Bone._tmpMats[2];
  55782. scaleMatrix.copyFrom(this._scaleMatrix);
  55783. rotMatInv.copyFrom(this.getAbsoluteTransform());
  55784. if (mesh) {
  55785. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  55786. var meshScale = Bone._tmpMats[3];
  55787. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, meshScale);
  55788. scaleMatrix.multiplyToRef(meshScale, scaleMatrix);
  55789. }
  55790. rotMatInv.invert();
  55791. scaleMatrix.m[0] *= this._scalingDeterminant;
  55792. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55793. }
  55794. else {
  55795. rotMatInv.copyFrom(this.getLocalMatrix());
  55796. rotMatInv.invert();
  55797. var scaleMatrix = Bone._tmpMats[2];
  55798. scaleMatrix.copyFrom(this._scaleMatrix);
  55799. if (this._parent) {
  55800. var pscaleMatrix = Bone._tmpMats[3];
  55801. pscaleMatrix.copyFrom(this._parent._scaleMatrix);
  55802. pscaleMatrix.invert();
  55803. pscaleMatrix.multiplyToRef(rotMatInv, rotMatInv);
  55804. }
  55805. else {
  55806. scaleMatrix.m[0] *= this._scalingDeterminant;
  55807. }
  55808. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  55809. }
  55810. };
  55811. /**
  55812. * Get the scale of the bone
  55813. * @returns the scale of the bone
  55814. */
  55815. Bone.prototype.getScale = function () {
  55816. return this._scaleVector.clone();
  55817. };
  55818. /**
  55819. * Copy the scale of the bone to a vector3.
  55820. * @param result The vector3 to copy the scale to
  55821. */
  55822. Bone.prototype.getScaleToRef = function (result) {
  55823. result.copyFrom(this._scaleVector);
  55824. };
  55825. /**
  55826. * Get the position of the bone in local or world space.
  55827. * @param space The space that the returned position is in.
  55828. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55829. * @returns The position of the bone
  55830. */
  55831. Bone.prototype.getPosition = function (space, mesh) {
  55832. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55833. var pos = BABYLON.Vector3.Zero();
  55834. this.getPositionToRef(space, mesh, pos);
  55835. return pos;
  55836. };
  55837. /**
  55838. * Copy the position of the bone to a vector3 in local or world space.
  55839. * @param space The space that the returned position is in.
  55840. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55841. * @param result The vector3 to copy the position to.
  55842. */
  55843. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  55844. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55845. if (space == BABYLON.Space.LOCAL) {
  55846. var lm = this.getLocalMatrix();
  55847. result.x = lm.m[12];
  55848. result.y = lm.m[13];
  55849. result.z = lm.m[14];
  55850. }
  55851. else {
  55852. var wm;
  55853. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55854. if (mesh) {
  55855. wm = mesh.getWorldMatrix();
  55856. }
  55857. this._skeleton.computeAbsoluteTransforms();
  55858. var tmat = Bone._tmpMats[0];
  55859. if (mesh) {
  55860. tmat.copyFrom(this.getAbsoluteTransform());
  55861. tmat.multiplyToRef(wm, tmat);
  55862. }
  55863. else {
  55864. tmat = this.getAbsoluteTransform();
  55865. }
  55866. result.x = tmat.m[12];
  55867. result.y = tmat.m[13];
  55868. result.z = tmat.m[14];
  55869. }
  55870. };
  55871. /**
  55872. * Get the absolute position of the bone (world space).
  55873. * @param mesh The mesh that this bone is attached to.
  55874. * @returns The absolute position of the bone
  55875. */
  55876. Bone.prototype.getAbsolutePosition = function (mesh) {
  55877. var pos = BABYLON.Vector3.Zero();
  55878. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  55879. return pos;
  55880. };
  55881. /**
  55882. * Copy the absolute position of the bone (world space) to the result param.
  55883. * @param mesh The mesh that this bone is attached to.
  55884. * @param result The vector3 to copy the absolute position to.
  55885. */
  55886. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  55887. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  55888. };
  55889. /**
  55890. * Compute the absolute transforms of this bone and its children.
  55891. */
  55892. Bone.prototype.computeAbsoluteTransforms = function () {
  55893. if (this._parent) {
  55894. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  55895. }
  55896. else {
  55897. this._absoluteTransform.copyFrom(this._localMatrix);
  55898. var poseMatrix = this._skeleton.getPoseMatrix();
  55899. if (poseMatrix) {
  55900. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  55901. }
  55902. }
  55903. var children = this.children;
  55904. var len = children.length;
  55905. for (var i = 0; i < len; i++) {
  55906. children[i].computeAbsoluteTransforms();
  55907. }
  55908. };
  55909. Bone.prototype._syncScaleVector = function () {
  55910. var lm = this.getLocalMatrix();
  55911. var xsq = (lm.m[0] * lm.m[0] + lm.m[1] * lm.m[1] + lm.m[2] * lm.m[2]);
  55912. var ysq = (lm.m[4] * lm.m[4] + lm.m[5] * lm.m[5] + lm.m[6] * lm.m[6]);
  55913. var zsq = (lm.m[8] * lm.m[8] + lm.m[9] * lm.m[9] + lm.m[10] * lm.m[10]);
  55914. var xs = lm.m[0] * lm.m[1] * lm.m[2] * lm.m[3] < 0 ? -1 : 1;
  55915. var ys = lm.m[4] * lm.m[5] * lm.m[6] * lm.m[7] < 0 ? -1 : 1;
  55916. var zs = lm.m[8] * lm.m[9] * lm.m[10] * lm.m[11] < 0 ? -1 : 1;
  55917. this._scaleVector.x = xs * Math.sqrt(xsq);
  55918. this._scaleVector.y = ys * Math.sqrt(ysq);
  55919. this._scaleVector.z = zs * Math.sqrt(zsq);
  55920. if (this._parent) {
  55921. this._scaleVector.x /= this._parent._negateScaleChildren.x;
  55922. this._scaleVector.y /= this._parent._negateScaleChildren.y;
  55923. this._scaleVector.z /= this._parent._negateScaleChildren.z;
  55924. }
  55925. 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);
  55926. };
  55927. /**
  55928. * Get the world direction from an axis that is in the local space of the bone.
  55929. * @param localAxis The local direction that is used to compute the world direction.
  55930. * @param mesh The mesh that this bone is attached to.
  55931. * @returns The world direction
  55932. */
  55933. Bone.prototype.getDirection = function (localAxis, mesh) {
  55934. var result = BABYLON.Vector3.Zero();
  55935. this.getDirectionToRef(localAxis, mesh, result);
  55936. return result;
  55937. };
  55938. /**
  55939. * Copy the world direction to a vector3 from an axis that is in the local space of the bone.
  55940. * @param localAxis The local direction that is used to compute the world direction.
  55941. * @param mesh The mesh that this bone is attached to.
  55942. * @param result The vector3 that the world direction will be copied to.
  55943. */
  55944. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  55945. var wm;
  55946. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  55947. if (mesh) {
  55948. wm = mesh.getWorldMatrix();
  55949. }
  55950. this._skeleton.computeAbsoluteTransforms();
  55951. var mat = Bone._tmpMats[0];
  55952. mat.copyFrom(this.getAbsoluteTransform());
  55953. if (mesh) {
  55954. mat.multiplyToRef(wm, mat);
  55955. }
  55956. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  55957. result.normalize();
  55958. };
  55959. /**
  55960. * Get the euler rotation of the bone in local or world space.
  55961. * @param space The space that the rotation should be in.
  55962. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55963. * @returns The euler rotation
  55964. */
  55965. Bone.prototype.getRotation = function (space, mesh) {
  55966. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55967. var result = BABYLON.Vector3.Zero();
  55968. this.getRotationToRef(space, mesh, result);
  55969. return result;
  55970. };
  55971. /**
  55972. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space.
  55973. * @param space The space that the rotation should be in.
  55974. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55975. * @param result The vector3 that the rotation should be copied to.
  55976. */
  55977. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  55978. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55979. var quat = Bone._tmpQuat;
  55980. this.getRotationQuaternionToRef(space, mesh, quat);
  55981. quat.toEulerAnglesToRef(result);
  55982. };
  55983. /**
  55984. * Get the quaternion rotation of the bone in either local or world space.
  55985. * @param space The space that the rotation should be in.
  55986. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55987. * @returns The quaternion rotation
  55988. */
  55989. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  55990. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  55991. var result = BABYLON.Quaternion.Identity();
  55992. this.getRotationQuaternionToRef(space, mesh, result);
  55993. return result;
  55994. };
  55995. /**
  55996. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space.
  55997. * @param space The space that the rotation should be in.
  55998. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  55999. * @param result The quaternion that the rotation should be copied to.
  56000. */
  56001. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  56002. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56003. if (space == BABYLON.Space.LOCAL) {
  56004. this.getLocalMatrix().decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56005. }
  56006. else {
  56007. var mat = Bone._tmpMats[0];
  56008. var amat = this.getAbsoluteTransform();
  56009. if (mesh) {
  56010. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56011. }
  56012. else {
  56013. mat.copyFrom(amat);
  56014. }
  56015. mat.m[0] *= this._scalingDeterminant;
  56016. mat.m[1] *= this._scalingDeterminant;
  56017. mat.m[2] *= this._scalingDeterminant;
  56018. mat.decompose(Bone._tmpVecs[0], result, Bone._tmpVecs[1]);
  56019. }
  56020. };
  56021. /**
  56022. * Get the rotation matrix of the bone in local or world space.
  56023. * @param space The space that the rotation should be in.
  56024. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56025. * @returns The rotation matrix
  56026. */
  56027. Bone.prototype.getRotationMatrix = function (space, mesh) {
  56028. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56029. var result = BABYLON.Matrix.Identity();
  56030. this.getRotationMatrixToRef(space, mesh, result);
  56031. return result;
  56032. };
  56033. /**
  56034. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space.
  56035. * @param space The space that the rotation should be in.
  56036. * @param mesh The mesh that this bone is attached to. This is only used in world space.
  56037. * @param result The quaternion that the rotation should be copied to.
  56038. */
  56039. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  56040. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  56041. if (space == BABYLON.Space.LOCAL) {
  56042. this.getLocalMatrix().getRotationMatrixToRef(result);
  56043. }
  56044. else {
  56045. var mat = Bone._tmpMats[0];
  56046. var amat = this.getAbsoluteTransform();
  56047. if (mesh) {
  56048. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  56049. }
  56050. else {
  56051. mat.copyFrom(amat);
  56052. }
  56053. mat.m[0] *= this._scalingDeterminant;
  56054. mat.m[1] *= this._scalingDeterminant;
  56055. mat.m[2] *= this._scalingDeterminant;
  56056. mat.getRotationMatrixToRef(result);
  56057. }
  56058. };
  56059. /**
  56060. * Get the world position of a point that is in the local space of the bone.
  56061. * @param position The local position
  56062. * @param mesh The mesh that this bone is attached to.
  56063. * @returns The world position
  56064. */
  56065. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  56066. var result = BABYLON.Vector3.Zero();
  56067. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  56068. return result;
  56069. };
  56070. /**
  56071. * Get the world position of a point that is in the local space of the bone and copy it to the result param.
  56072. * @param position The local position
  56073. * @param mesh The mesh that this bone is attached to.
  56074. * @param result The vector3 that the world position should be copied to.
  56075. */
  56076. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  56077. var wm;
  56078. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56079. if (mesh) {
  56080. wm = mesh.getWorldMatrix();
  56081. }
  56082. this._skeleton.computeAbsoluteTransforms();
  56083. var tmat = Bone._tmpMats[0];
  56084. if (mesh) {
  56085. tmat.copyFrom(this.getAbsoluteTransform());
  56086. tmat.multiplyToRef(wm, tmat);
  56087. }
  56088. else {
  56089. tmat = this.getAbsoluteTransform();
  56090. }
  56091. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56092. };
  56093. /**
  56094. * Get the local position of a point that is in world space.
  56095. * @param position The world position
  56096. * @param mesh The mesh that this bone is attached to.
  56097. * @returns The local position
  56098. */
  56099. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  56100. var result = BABYLON.Vector3.Zero();
  56101. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  56102. return result;
  56103. };
  56104. /**
  56105. * Get the local position of a point that is in world space and copy it to the result param.
  56106. * @param position The world position
  56107. * @param mesh The mesh that this bone is attached to.
  56108. * @param result The vector3 that the local position should be copied to.
  56109. */
  56110. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  56111. var wm;
  56112. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  56113. if (mesh) {
  56114. wm = mesh.getWorldMatrix();
  56115. }
  56116. this._skeleton.computeAbsoluteTransforms();
  56117. var tmat = Bone._tmpMats[0];
  56118. tmat.copyFrom(this.getAbsoluteTransform());
  56119. if (mesh) {
  56120. tmat.multiplyToRef(wm, tmat);
  56121. }
  56122. tmat.invert();
  56123. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  56124. };
  56125. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56126. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  56127. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56128. return Bone;
  56129. }(BABYLON.Node));
  56130. BABYLON.Bone = Bone;
  56131. })(BABYLON || (BABYLON = {}));
  56132. //# sourceMappingURL=babylon.bone.js.map
  56133. var BABYLON;
  56134. (function (BABYLON) {
  56135. var BoneIKController = (function () {
  56136. function BoneIKController(mesh, bone, options) {
  56137. this.targetPosition = BABYLON.Vector3.Zero();
  56138. this.poleTargetPosition = BABYLON.Vector3.Zero();
  56139. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  56140. this.poleAngle = 0;
  56141. this.slerpAmount = 1;
  56142. this._bone1Quat = BABYLON.Quaternion.Identity();
  56143. this._bone1Mat = BABYLON.Matrix.Identity();
  56144. this._bone2Ang = Math.PI;
  56145. this._maxAngle = Math.PI;
  56146. this._rightHandedSystem = false;
  56147. this._bendAxis = BABYLON.Vector3.Right();
  56148. this._slerping = false;
  56149. this._adjustRoll = 0;
  56150. this._bone2 = bone;
  56151. this._bone1 = bone.getParent();
  56152. this.mesh = mesh;
  56153. var bonePos = bone.getPosition();
  56154. if (bone.getAbsoluteTransform().determinant() > 0) {
  56155. this._rightHandedSystem = true;
  56156. this._bendAxis.x = 0;
  56157. this._bendAxis.y = 0;
  56158. this._bendAxis.z = -1;
  56159. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  56160. this._adjustRoll = Math.PI * .5;
  56161. this._bendAxis.z = 1;
  56162. }
  56163. }
  56164. if (this._bone1.length) {
  56165. var boneScale1 = this._bone1.getScale();
  56166. var boneScale2 = this._bone2.getScale();
  56167. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  56168. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  56169. }
  56170. else if (this._bone1.children[0]) {
  56171. mesh.computeWorldMatrix(true);
  56172. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  56173. var pos2 = this._bone2.getAbsolutePosition(mesh);
  56174. var pos3 = this._bone1.getAbsolutePosition(mesh);
  56175. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  56176. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  56177. }
  56178. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  56179. this.maxAngle = Math.PI;
  56180. if (options) {
  56181. if (options.targetMesh) {
  56182. this.targetMesh = options.targetMesh;
  56183. this.targetMesh.computeWorldMatrix(true);
  56184. }
  56185. if (options.poleTargetMesh) {
  56186. this.poleTargetMesh = options.poleTargetMesh;
  56187. this.poleTargetMesh.computeWorldMatrix(true);
  56188. }
  56189. else if (options.poleTargetBone) {
  56190. this.poleTargetBone = options.poleTargetBone;
  56191. }
  56192. else if (this._bone1.getParent()) {
  56193. this.poleTargetBone = this._bone1.getParent();
  56194. }
  56195. if (options.poleTargetLocalOffset) {
  56196. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  56197. }
  56198. if (options.poleAngle) {
  56199. this.poleAngle = options.poleAngle;
  56200. }
  56201. if (options.bendAxis) {
  56202. this._bendAxis.copyFrom(options.bendAxis);
  56203. }
  56204. if (options.maxAngle) {
  56205. this.maxAngle = options.maxAngle;
  56206. }
  56207. if (options.slerpAmount) {
  56208. this.slerpAmount = options.slerpAmount;
  56209. }
  56210. }
  56211. }
  56212. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  56213. get: function () {
  56214. return this._maxAngle;
  56215. },
  56216. set: function (value) {
  56217. this._setMaxAngle(value);
  56218. },
  56219. enumerable: true,
  56220. configurable: true
  56221. });
  56222. BoneIKController.prototype._setMaxAngle = function (ang) {
  56223. if (ang < 0) {
  56224. ang = 0;
  56225. }
  56226. if (ang > Math.PI || ang == undefined) {
  56227. ang = Math.PI;
  56228. }
  56229. this._maxAngle = ang;
  56230. var a = this._bone1Length;
  56231. var b = this._bone2Length;
  56232. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  56233. };
  56234. BoneIKController.prototype.update = function () {
  56235. var bone1 = this._bone1;
  56236. var target = this.targetPosition;
  56237. var poleTarget = this.poleTargetPosition;
  56238. var mat1 = BoneIKController._tmpMats[0];
  56239. var mat2 = BoneIKController._tmpMats[1];
  56240. if (this.targetMesh) {
  56241. target.copyFrom(this.targetMesh.getAbsolutePosition());
  56242. }
  56243. if (this.poleTargetBone) {
  56244. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  56245. }
  56246. else if (this.poleTargetMesh) {
  56247. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  56248. }
  56249. var bonePos = BoneIKController._tmpVecs[0];
  56250. var zaxis = BoneIKController._tmpVecs[1];
  56251. var xaxis = BoneIKController._tmpVecs[2];
  56252. var yaxis = BoneIKController._tmpVecs[3];
  56253. var upAxis = BoneIKController._tmpVecs[4];
  56254. var _tmpQuat = BoneIKController._tmpQuat;
  56255. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  56256. poleTarget.subtractToRef(bonePos, upAxis);
  56257. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  56258. upAxis.y = 1;
  56259. }
  56260. else {
  56261. upAxis.normalize();
  56262. }
  56263. target.subtractToRef(bonePos, yaxis);
  56264. yaxis.normalize();
  56265. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  56266. zaxis.normalize();
  56267. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  56268. xaxis.normalize();
  56269. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  56270. var a = this._bone1Length;
  56271. var b = this._bone2Length;
  56272. var c = BABYLON.Vector3.Distance(bonePos, target);
  56273. if (this._maxReach > 0) {
  56274. c = Math.min(this._maxReach, c);
  56275. }
  56276. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  56277. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  56278. if (acosa > 1) {
  56279. acosa = 1;
  56280. }
  56281. if (acosb > 1) {
  56282. acosb = 1;
  56283. }
  56284. if (acosa < -1) {
  56285. acosa = -1;
  56286. }
  56287. if (acosb < -1) {
  56288. acosb = -1;
  56289. }
  56290. var angA = Math.acos(acosa);
  56291. var angB = Math.acos(acosb);
  56292. var angC = -angA - angB;
  56293. if (this._rightHandedSystem) {
  56294. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  56295. mat2.multiplyToRef(mat1, mat1);
  56296. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  56297. mat2.multiplyToRef(mat1, mat1);
  56298. }
  56299. else {
  56300. var _tmpVec = BoneIKController._tmpVecs[5];
  56301. _tmpVec.copyFrom(this._bendAxis);
  56302. _tmpVec.x *= -1;
  56303. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  56304. mat2.multiplyToRef(mat1, mat1);
  56305. }
  56306. if (this.poleAngle) {
  56307. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  56308. mat1.multiplyToRef(mat2, mat1);
  56309. }
  56310. if (this.slerpAmount < 1) {
  56311. if (!this._slerping) {
  56312. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  56313. }
  56314. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  56315. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  56316. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  56317. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  56318. this._slerping = true;
  56319. }
  56320. else {
  56321. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  56322. this._bone1Mat.copyFrom(mat1);
  56323. this._slerping = false;
  56324. }
  56325. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  56326. this._bone2Ang = angC;
  56327. };
  56328. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56329. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  56330. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56331. return BoneIKController;
  56332. }());
  56333. BABYLON.BoneIKController = BoneIKController;
  56334. })(BABYLON || (BABYLON = {}));
  56335. //# sourceMappingURL=babylon.boneIKController.js.map
  56336. var BABYLON;
  56337. (function (BABYLON) {
  56338. var BoneLookController = (function () {
  56339. /**
  56340. * Create a BoneLookController
  56341. * @param mesh the mesh that the bone belongs to
  56342. * @param bone the bone that will be looking to the target
  56343. * @param target the target Vector3 to look at
  56344. * @param settings optional settings:
  56345. * - maxYaw: the maximum angle the bone will yaw to
  56346. * - minYaw: the minimum angle the bone will yaw to
  56347. * - maxPitch: the maximum angle the bone will pitch to
  56348. * - minPitch: the minimum angle the bone will yaw to
  56349. * - slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  56350. * - upAxis: the up axis of the coordinate system
  56351. * - upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56352. * - yawAxis: set yawAxis if the bone does not yaw on the y axis
  56353. * - pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  56354. * - adjustYaw: used to make an adjustment to the yaw of the bone
  56355. * - adjustPitch: used to make an adjustment to the pitch of the bone
  56356. * - adjustRoll: used to make an adjustment to the roll of the bone
  56357. **/
  56358. function BoneLookController(mesh, bone, target, options) {
  56359. /**
  56360. * The up axis of the coordinate system that is used when the bone is rotated.
  56361. */
  56362. this.upAxis = BABYLON.Vector3.Up();
  56363. /**
  56364. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  56365. */
  56366. this.upAxisSpace = BABYLON.Space.LOCAL;
  56367. /**
  56368. * Used to make an adjustment to the yaw of the bone.
  56369. */
  56370. this.adjustYaw = 0;
  56371. /**
  56372. * Used to make an adjustment to the pitch of the bone.
  56373. */
  56374. this.adjustPitch = 0;
  56375. /**
  56376. * Used to make an adjustment to the roll of the bone.
  56377. */
  56378. this.adjustRoll = 0;
  56379. /**
  56380. * The amount to slerp (spherical linear interpolation) to the target. Set this to a value between 0 and 1 (a value of 1 disables slerp).
  56381. */
  56382. this.slerpAmount = 1;
  56383. this._boneQuat = BABYLON.Quaternion.Identity();
  56384. this._slerping = false;
  56385. this._firstFrameSkipped = false;
  56386. this._fowardAxis = BABYLON.Vector3.Forward();
  56387. this.mesh = mesh;
  56388. this.bone = bone;
  56389. this.target = target;
  56390. if (options) {
  56391. if (options.adjustYaw) {
  56392. this.adjustYaw = options.adjustYaw;
  56393. }
  56394. if (options.adjustPitch) {
  56395. this.adjustPitch = options.adjustPitch;
  56396. }
  56397. if (options.adjustRoll) {
  56398. this.adjustRoll = options.adjustRoll;
  56399. }
  56400. if (options.maxYaw != null) {
  56401. this.maxYaw = options.maxYaw;
  56402. }
  56403. else {
  56404. this.maxYaw = Math.PI;
  56405. }
  56406. if (options.minYaw != null) {
  56407. this.minYaw = options.minYaw;
  56408. }
  56409. else {
  56410. this.minYaw = -Math.PI;
  56411. }
  56412. if (options.maxPitch != null) {
  56413. this.maxPitch = options.maxPitch;
  56414. }
  56415. else {
  56416. this.maxPitch = Math.PI;
  56417. }
  56418. if (options.minPitch != null) {
  56419. this.minPitch = options.minPitch;
  56420. }
  56421. else {
  56422. this.minPitch = -Math.PI;
  56423. }
  56424. if (options.slerpAmount != null) {
  56425. this.slerpAmount = options.slerpAmount;
  56426. }
  56427. if (options.upAxis != null) {
  56428. this.upAxis = options.upAxis;
  56429. }
  56430. if (options.upAxisSpace != null) {
  56431. this.upAxisSpace = options.upAxisSpace;
  56432. }
  56433. if (options.yawAxis != null || options.pitchAxis != null) {
  56434. var newYawAxis = BABYLON.Axis.Y;
  56435. var newPitchAxis = BABYLON.Axis.X;
  56436. if (options.yawAxis != null) {
  56437. newYawAxis = options.yawAxis.clone();
  56438. newYawAxis.normalize();
  56439. }
  56440. if (options.pitchAxis != null) {
  56441. newPitchAxis = options.pitchAxis.clone();
  56442. newPitchAxis.normalize();
  56443. }
  56444. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  56445. this._transformYawPitch = BABYLON.Matrix.Identity();
  56446. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  56447. this._transformYawPitchInv = this._transformYawPitch.clone();
  56448. this._transformYawPitch.invert();
  56449. }
  56450. }
  56451. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  56452. this.upAxisSpace = BABYLON.Space.LOCAL;
  56453. }
  56454. }
  56455. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  56456. /**
  56457. * Get/set the minimum yaw angle that the bone can look to.
  56458. */
  56459. get: function () {
  56460. return this._minYaw;
  56461. },
  56462. set: function (value) {
  56463. this._minYaw = value;
  56464. this._minYawSin = Math.sin(value);
  56465. this._minYawCos = Math.cos(value);
  56466. if (this._maxYaw != null) {
  56467. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56468. this._yawRange = this._maxYaw - this._minYaw;
  56469. }
  56470. },
  56471. enumerable: true,
  56472. configurable: true
  56473. });
  56474. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  56475. /**
  56476. * Get/set the maximum yaw angle that the bone can look to.
  56477. */
  56478. get: function () {
  56479. return this._maxYaw;
  56480. },
  56481. set: function (value) {
  56482. this._maxYaw = value;
  56483. this._maxYawSin = Math.sin(value);
  56484. this._maxYawCos = Math.cos(value);
  56485. if (this._minYaw != null) {
  56486. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  56487. this._yawRange = this._maxYaw - this._minYaw;
  56488. }
  56489. },
  56490. enumerable: true,
  56491. configurable: true
  56492. });
  56493. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  56494. /**
  56495. * Get/set the minimum pitch angle that the bone can look to.
  56496. */
  56497. get: function () {
  56498. return this._minPitch;
  56499. },
  56500. set: function (value) {
  56501. this._minPitch = value;
  56502. this._minPitchTan = Math.tan(value);
  56503. },
  56504. enumerable: true,
  56505. configurable: true
  56506. });
  56507. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  56508. /**
  56509. * Get/set the maximum pitch angle that the bone can look to.
  56510. */
  56511. get: function () {
  56512. return this._maxPitch;
  56513. },
  56514. set: function (value) {
  56515. this._maxPitch = value;
  56516. this._maxPitchTan = Math.tan(value);
  56517. },
  56518. enumerable: true,
  56519. configurable: true
  56520. });
  56521. /**
  56522. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender()).
  56523. */
  56524. BoneLookController.prototype.update = function () {
  56525. //skip the first frame when slerping so that the mesh rotation is correct
  56526. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  56527. this._firstFrameSkipped = true;
  56528. return;
  56529. }
  56530. var bone = this.bone;
  56531. var bonePos = BoneLookController._tmpVecs[0];
  56532. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  56533. var target = this.target;
  56534. var _tmpMat1 = BoneLookController._tmpMats[0];
  56535. var _tmpMat2 = BoneLookController._tmpMats[1];
  56536. var mesh = this.mesh;
  56537. var parentBone = bone.getParent();
  56538. var upAxis = BoneLookController._tmpVecs[1];
  56539. upAxis.copyFrom(this.upAxis);
  56540. if (this.upAxisSpace == BABYLON.Space.BONE) {
  56541. if (this._transformYawPitch) {
  56542. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  56543. }
  56544. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  56545. }
  56546. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  56547. mesh.getDirectionToRef(upAxis, upAxis);
  56548. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  56549. upAxis.normalize();
  56550. }
  56551. }
  56552. var checkYaw = false;
  56553. var checkPitch = false;
  56554. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  56555. checkYaw = true;
  56556. }
  56557. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  56558. checkPitch = true;
  56559. }
  56560. if (checkYaw || checkPitch) {
  56561. var spaceMat = BoneLookController._tmpMats[2];
  56562. var spaceMatInv = BoneLookController._tmpMats[3];
  56563. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1) {
  56564. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  56565. }
  56566. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  56567. spaceMat.copyFrom(mesh.getWorldMatrix());
  56568. }
  56569. else {
  56570. var forwardAxis = BoneLookController._tmpVecs[2];
  56571. forwardAxis.copyFrom(this._fowardAxis);
  56572. if (this._transformYawPitch) {
  56573. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  56574. }
  56575. if (parentBone) {
  56576. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  56577. }
  56578. else {
  56579. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  56580. }
  56581. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  56582. rightAxis.normalize();
  56583. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  56584. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  56585. }
  56586. spaceMat.invertToRef(spaceMatInv);
  56587. var xzlen;
  56588. if (checkPitch) {
  56589. var localTarget = BoneLookController._tmpVecs[3];
  56590. target.subtractToRef(bonePos, localTarget);
  56591. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56592. var xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56593. var pitch = Math.atan2(localTarget.y, xzlen);
  56594. var newPitch = pitch;
  56595. if (pitch > this._maxPitch) {
  56596. localTarget.y = this._maxPitchTan * xzlen;
  56597. newPitch = this._maxPitch;
  56598. }
  56599. else if (pitch < this._minPitch) {
  56600. localTarget.y = this._minPitchTan * xzlen;
  56601. newPitch = this._minPitch;
  56602. }
  56603. if (pitch != newPitch) {
  56604. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56605. localTarget.addInPlace(bonePos);
  56606. target = localTarget;
  56607. }
  56608. }
  56609. if (checkYaw) {
  56610. var localTarget = BoneLookController._tmpVecs[4];
  56611. target.subtractToRef(bonePos, localTarget);
  56612. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  56613. var yaw = Math.atan2(localTarget.x, localTarget.z);
  56614. var newYaw = yaw;
  56615. if (yaw > this._maxYaw || yaw < this._minYaw) {
  56616. if (xzlen == null) {
  56617. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56618. }
  56619. if (this._yawRange > Math.PI) {
  56620. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  56621. localTarget.z = this._maxYawCos * xzlen;
  56622. localTarget.x = this._maxYawSin * xzlen;
  56623. newYaw = this._maxYaw;
  56624. }
  56625. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  56626. localTarget.z = this._minYawCos * xzlen;
  56627. localTarget.x = this._minYawSin * xzlen;
  56628. newYaw = this._minYaw;
  56629. }
  56630. }
  56631. else {
  56632. if (yaw > this._maxYaw) {
  56633. localTarget.z = this._maxYawCos * xzlen;
  56634. localTarget.x = this._maxYawSin * xzlen;
  56635. newYaw = this._maxYaw;
  56636. }
  56637. else if (yaw < this._minYaw) {
  56638. localTarget.z = this._minYawCos * xzlen;
  56639. localTarget.x = this._minYawSin * xzlen;
  56640. newYaw = this._minYaw;
  56641. }
  56642. }
  56643. }
  56644. if (this._slerping && this._yawRange > Math.PI) {
  56645. //are we going to be crossing into the min/max region?
  56646. var boneFwd = BoneLookController._tmpVecs[8];
  56647. boneFwd.copyFrom(BABYLON.Axis.Z);
  56648. if (this._transformYawPitch) {
  56649. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  56650. }
  56651. var boneRotMat = BABYLON.BoneLookController._tmpMats[4];
  56652. this._boneQuat.toRotationMatrix(boneRotMat);
  56653. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  56654. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  56655. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  56656. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  56657. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  56658. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  56659. if (angBtwTar > angBtwMidYaw) {
  56660. if (xzlen == null) {
  56661. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  56662. }
  56663. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  56664. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  56665. if (angBtwMin < angBtwMax) {
  56666. newYaw = boneYaw + Math.PI * .75;
  56667. localTarget.z = Math.cos(newYaw) * xzlen;
  56668. localTarget.x = Math.sin(newYaw) * xzlen;
  56669. }
  56670. else {
  56671. newYaw = boneYaw - Math.PI * .75;
  56672. localTarget.z = Math.cos(newYaw) * xzlen;
  56673. localTarget.x = Math.sin(newYaw) * xzlen;
  56674. }
  56675. }
  56676. }
  56677. if (yaw != newYaw) {
  56678. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  56679. localTarget.addInPlace(bonePos);
  56680. target = localTarget;
  56681. }
  56682. }
  56683. }
  56684. var zaxis = BoneLookController._tmpVecs[5];
  56685. var xaxis = BoneLookController._tmpVecs[6];
  56686. var yaxis = BoneLookController._tmpVecs[7];
  56687. var _tmpQuat = BoneLookController._tmpQuat;
  56688. target.subtractToRef(bonePos, zaxis);
  56689. zaxis.normalize();
  56690. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  56691. xaxis.normalize();
  56692. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  56693. yaxis.normalize();
  56694. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  56695. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  56696. return;
  56697. }
  56698. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  56699. return;
  56700. }
  56701. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  56702. return;
  56703. }
  56704. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  56705. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  56706. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  56707. }
  56708. if (this.slerpAmount < 1) {
  56709. if (!this._slerping) {
  56710. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  56711. }
  56712. if (this._transformYawPitch) {
  56713. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56714. }
  56715. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  56716. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  56717. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  56718. this._slerping = true;
  56719. }
  56720. else {
  56721. if (this._transformYawPitch) {
  56722. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  56723. }
  56724. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  56725. this._slerping = false;
  56726. }
  56727. };
  56728. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  56729. var angDiff = ang2 - ang1;
  56730. angDiff %= Math.PI * 2;
  56731. if (angDiff > Math.PI) {
  56732. angDiff -= Math.PI * 2;
  56733. }
  56734. else if (angDiff < -Math.PI) {
  56735. angDiff += Math.PI * 2;
  56736. }
  56737. return angDiff;
  56738. };
  56739. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  56740. ang1 %= (2 * Math.PI);
  56741. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56742. ang2 %= (2 * Math.PI);
  56743. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56744. var ab = 0;
  56745. if (ang1 < ang2) {
  56746. ab = ang2 - ang1;
  56747. }
  56748. else {
  56749. ab = ang1 - ang2;
  56750. }
  56751. if (ab > Math.PI) {
  56752. ab = Math.PI * 2 - ab;
  56753. }
  56754. return ab;
  56755. };
  56756. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  56757. ang %= (2 * Math.PI);
  56758. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  56759. ang1 %= (2 * Math.PI);
  56760. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  56761. ang2 %= (2 * Math.PI);
  56762. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  56763. if (ang1 < ang2) {
  56764. if (ang > ang1 && ang < ang2) {
  56765. return true;
  56766. }
  56767. }
  56768. else {
  56769. if (ang > ang2 && ang < ang1) {
  56770. return true;
  56771. }
  56772. }
  56773. return false;
  56774. };
  56775. BoneLookController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  56776. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  56777. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  56778. return BoneLookController;
  56779. }());
  56780. BABYLON.BoneLookController = BoneLookController;
  56781. })(BABYLON || (BABYLON = {}));
  56782. //# sourceMappingURL=babylon.boneLookController.js.map
  56783. var BABYLON;
  56784. (function (BABYLON) {
  56785. var Skeleton = (function () {
  56786. function Skeleton(name, id, scene) {
  56787. this.name = name;
  56788. this.id = id;
  56789. this.bones = new Array();
  56790. this.needInitialSkinMatrix = false;
  56791. this._isDirty = true;
  56792. this._meshesWithPoseMatrix = new Array();
  56793. this._identity = BABYLON.Matrix.Identity();
  56794. this._ranges = {};
  56795. this._lastAbsoluteTransformsUpdateId = -1;
  56796. // Events
  56797. /**
  56798. * An event triggered before computing the skeleton's matrices
  56799. * @type {BABYLON.Observable}
  56800. */
  56801. this.onBeforeComputeObservable = new BABYLON.Observable();
  56802. this.bones = [];
  56803. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  56804. scene.skeletons.push(this);
  56805. //make sure it will recalculate the matrix next time prepare is called.
  56806. this._isDirty = true;
  56807. }
  56808. // Members
  56809. Skeleton.prototype.getTransformMatrices = function (mesh) {
  56810. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  56811. return mesh._bonesTransformMatrices;
  56812. }
  56813. if (!this._transformMatrices) {
  56814. this.prepare();
  56815. }
  56816. return this._transformMatrices;
  56817. };
  56818. Skeleton.prototype.getScene = function () {
  56819. return this._scene;
  56820. };
  56821. // Methods
  56822. /**
  56823. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  56824. */
  56825. Skeleton.prototype.toString = function (fullDetails) {
  56826. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  56827. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  56828. if (fullDetails) {
  56829. ret += ", Ranges: {";
  56830. var first = true;
  56831. for (var name_1 in this._ranges) {
  56832. if (first) {
  56833. ret += ", ";
  56834. first = false;
  56835. }
  56836. ret += name_1;
  56837. }
  56838. ret += "}";
  56839. }
  56840. return ret;
  56841. };
  56842. /**
  56843. * Get bone's index searching by name
  56844. * @param {string} name is bone's name to search for
  56845. * @return {number} Indice of the bone. Returns -1 if not found
  56846. */
  56847. Skeleton.prototype.getBoneIndexByName = function (name) {
  56848. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  56849. if (this.bones[boneIndex].name === name) {
  56850. return boneIndex;
  56851. }
  56852. }
  56853. return -1;
  56854. };
  56855. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  56856. // check name not already in use
  56857. if (!this._ranges[name]) {
  56858. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  56859. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56860. if (this.bones[i].animations[0]) {
  56861. this.bones[i].animations[0].createRange(name, from, to);
  56862. }
  56863. }
  56864. }
  56865. };
  56866. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  56867. if (deleteFrames === void 0) { deleteFrames = true; }
  56868. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56869. if (this.bones[i].animations[0]) {
  56870. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  56871. }
  56872. }
  56873. this._ranges[name] = undefined; // said much faster than 'delete this._range[name]'
  56874. };
  56875. Skeleton.prototype.getAnimationRange = function (name) {
  56876. return this._ranges[name];
  56877. };
  56878. /**
  56879. * Returns as an Array, all AnimationRanges defined on this skeleton
  56880. */
  56881. Skeleton.prototype.getAnimationRanges = function () {
  56882. var animationRanges = [];
  56883. var name;
  56884. var i = 0;
  56885. for (name in this._ranges) {
  56886. animationRanges[i] = this._ranges[name];
  56887. i++;
  56888. }
  56889. return animationRanges;
  56890. };
  56891. /**
  56892. * note: This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  56893. */
  56894. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  56895. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  56896. if (this._ranges[name] || !source.getAnimationRange(name)) {
  56897. return false;
  56898. }
  56899. var ret = true;
  56900. var frameOffset = this._getHighestAnimationFrame() + 1;
  56901. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  56902. var boneDict = {};
  56903. var sourceBones = source.bones;
  56904. var nBones;
  56905. var i;
  56906. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  56907. boneDict[sourceBones[i].name] = sourceBones[i];
  56908. }
  56909. if (this.bones.length !== sourceBones.length) {
  56910. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  56911. ret = false;
  56912. }
  56913. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  56914. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  56915. var boneName = this.bones[i].name;
  56916. var sourceBone = boneDict[boneName];
  56917. if (sourceBone) {
  56918. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  56919. }
  56920. else {
  56921. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  56922. ret = false;
  56923. }
  56924. }
  56925. // do not call createAnimationRange(), since it also is done to bones, which was already done
  56926. var range = source.getAnimationRange(name);
  56927. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  56928. return ret;
  56929. };
  56930. Skeleton.prototype.returnToRest = function () {
  56931. for (var index = 0; index < this.bones.length; index++) {
  56932. this.bones[index].returnToRest();
  56933. }
  56934. };
  56935. Skeleton.prototype._getHighestAnimationFrame = function () {
  56936. var ret = 0;
  56937. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  56938. if (this.bones[i].animations[0]) {
  56939. var highest = this.bones[i].animations[0].getHighestFrame();
  56940. if (ret < highest) {
  56941. ret = highest;
  56942. }
  56943. }
  56944. }
  56945. return ret;
  56946. };
  56947. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  56948. var range = this.getAnimationRange(name);
  56949. if (!range) {
  56950. return null;
  56951. }
  56952. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  56953. };
  56954. Skeleton.prototype._markAsDirty = function () {
  56955. this._isDirty = true;
  56956. };
  56957. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  56958. this._meshesWithPoseMatrix.push(mesh);
  56959. };
  56960. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  56961. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  56962. if (index > -1) {
  56963. this._meshesWithPoseMatrix.splice(index, 1);
  56964. }
  56965. };
  56966. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  56967. this.onBeforeComputeObservable.notifyObservers(this);
  56968. for (var index = 0; index < this.bones.length; index++) {
  56969. var bone = this.bones[index];
  56970. var parentBone = bone.getParent();
  56971. if (parentBone) {
  56972. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  56973. }
  56974. else {
  56975. if (initialSkinMatrix) {
  56976. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  56977. }
  56978. else {
  56979. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  56980. }
  56981. }
  56982. if (bone._index !== -1) {
  56983. var mappedIndex = bone._index === undefined ? index : bone._index;
  56984. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  56985. }
  56986. }
  56987. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  56988. };
  56989. Skeleton.prototype.prepare = function () {
  56990. if (!this._isDirty) {
  56991. return;
  56992. }
  56993. if (this.needInitialSkinMatrix) {
  56994. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  56995. var mesh = this._meshesWithPoseMatrix[index];
  56996. var poseMatrix = mesh.getPoseMatrix();
  56997. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  56998. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  56999. }
  57000. if (this._synchronizedWithMesh !== mesh) {
  57001. this._synchronizedWithMesh = mesh;
  57002. // Prepare bones
  57003. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  57004. var bone = this.bones[boneIndex];
  57005. if (!bone.getParent()) {
  57006. var matrix = bone.getBaseMatrix();
  57007. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  57008. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  57009. }
  57010. }
  57011. }
  57012. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  57013. }
  57014. }
  57015. else {
  57016. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  57017. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  57018. }
  57019. this._computeTransformMatrices(this._transformMatrices, null);
  57020. }
  57021. this._isDirty = false;
  57022. this._scene._activeBones.addCount(this.bones.length, false);
  57023. };
  57024. Skeleton.prototype.getAnimatables = function () {
  57025. if (!this._animatables || this._animatables.length !== this.bones.length) {
  57026. this._animatables = [];
  57027. for (var index = 0; index < this.bones.length; index++) {
  57028. this._animatables.push(this.bones[index]);
  57029. }
  57030. }
  57031. return this._animatables;
  57032. };
  57033. Skeleton.prototype.clone = function (name, id) {
  57034. var result = new Skeleton(name, id || name, this._scene);
  57035. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57036. for (var index = 0; index < this.bones.length; index++) {
  57037. var source = this.bones[index];
  57038. var parentBone = null;
  57039. if (source.getParent()) {
  57040. var parentIndex = this.bones.indexOf(source.getParent());
  57041. parentBone = result.bones[parentIndex];
  57042. }
  57043. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  57044. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  57045. }
  57046. if (this._ranges) {
  57047. result._ranges = {};
  57048. for (var rangeName in this._ranges) {
  57049. result._ranges[rangeName] = this._ranges[rangeName].clone();
  57050. }
  57051. }
  57052. this._isDirty = true;
  57053. return result;
  57054. };
  57055. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  57056. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  57057. this.bones.forEach(function (bone) {
  57058. bone.animations.forEach(function (animation) {
  57059. animation.enableBlending = true;
  57060. animation.blendingSpeed = blendingSpeed;
  57061. });
  57062. });
  57063. };
  57064. Skeleton.prototype.dispose = function () {
  57065. this._meshesWithPoseMatrix = [];
  57066. // Animations
  57067. this.getScene().stopAnimation(this);
  57068. // Remove from scene
  57069. this.getScene().removeSkeleton(this);
  57070. };
  57071. Skeleton.prototype.serialize = function () {
  57072. var serializationObject = {};
  57073. serializationObject.name = this.name;
  57074. serializationObject.id = this.id;
  57075. serializationObject.dimensionsAtRest = this.dimensionsAtRest;
  57076. serializationObject.bones = [];
  57077. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  57078. for (var index = 0; index < this.bones.length; index++) {
  57079. var bone = this.bones[index];
  57080. var serializedBone = {
  57081. parentBoneIndex: bone.getParent() ? this.bones.indexOf(bone.getParent()) : -1,
  57082. name: bone.name,
  57083. matrix: bone.getBaseMatrix().toArray(),
  57084. rest: bone.getRestPose().toArray()
  57085. };
  57086. serializationObject.bones.push(serializedBone);
  57087. if (bone.length) {
  57088. serializedBone.length = bone.length;
  57089. }
  57090. if (bone.animations && bone.animations.length > 0) {
  57091. serializedBone.animation = bone.animations[0].serialize();
  57092. }
  57093. serializationObject.ranges = [];
  57094. for (var name in this._ranges) {
  57095. var range = {};
  57096. range.name = name;
  57097. range.from = this._ranges[name].from;
  57098. range.to = this._ranges[name].to;
  57099. serializationObject.ranges.push(range);
  57100. }
  57101. }
  57102. return serializationObject;
  57103. };
  57104. Skeleton.Parse = function (parsedSkeleton, scene) {
  57105. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  57106. if (parsedSkeleton.dimensionsAtRest) {
  57107. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  57108. }
  57109. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  57110. var index;
  57111. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  57112. var parsedBone = parsedSkeleton.bones[index];
  57113. var parentBone = null;
  57114. if (parsedBone.parentBoneIndex > -1) {
  57115. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  57116. }
  57117. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  57118. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  57119. if (parsedBone.length) {
  57120. bone.length = parsedBone.length;
  57121. }
  57122. if (parsedBone.animation) {
  57123. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  57124. }
  57125. }
  57126. // placed after bones, so createAnimationRange can cascade down
  57127. if (parsedSkeleton.ranges) {
  57128. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  57129. var data = parsedSkeleton.ranges[index];
  57130. skeleton.createAnimationRange(data.name, data.from, data.to);
  57131. }
  57132. }
  57133. return skeleton;
  57134. };
  57135. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  57136. if (forceUpdate === void 0) { forceUpdate = false; }
  57137. var renderId = this._scene.getRenderId();
  57138. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  57139. this.bones[0].computeAbsoluteTransforms();
  57140. this._lastAbsoluteTransformsUpdateId = renderId;
  57141. }
  57142. };
  57143. Skeleton.prototype.getPoseMatrix = function () {
  57144. var poseMatrix;
  57145. if (this._meshesWithPoseMatrix.length > 0) {
  57146. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  57147. }
  57148. return poseMatrix;
  57149. };
  57150. Skeleton.prototype.sortBones = function () {
  57151. var bones = new Array();
  57152. var visited = new Array(this.bones.length);
  57153. for (var index = 0; index < this.bones.length; index++) {
  57154. this._sortBones(index, bones, visited);
  57155. }
  57156. this.bones = bones;
  57157. };
  57158. Skeleton.prototype._sortBones = function (index, bones, visited) {
  57159. if (visited[index]) {
  57160. return;
  57161. }
  57162. visited[index] = true;
  57163. var bone = this.bones[index];
  57164. if (bone._index === undefined) {
  57165. bone._index = index;
  57166. }
  57167. var parentBone = bone.getParent();
  57168. if (parentBone) {
  57169. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  57170. }
  57171. bones.push(bone);
  57172. };
  57173. return Skeleton;
  57174. }());
  57175. BABYLON.Skeleton = Skeleton;
  57176. })(BABYLON || (BABYLON = {}));
  57177. //# sourceMappingURL=babylon.skeleton.js.map
  57178. var BABYLON;
  57179. (function (BABYLON) {
  57180. var SphericalPolynomial = (function () {
  57181. function SphericalPolynomial() {
  57182. this.x = BABYLON.Vector3.Zero();
  57183. this.y = BABYLON.Vector3.Zero();
  57184. this.z = BABYLON.Vector3.Zero();
  57185. this.xx = BABYLON.Vector3.Zero();
  57186. this.yy = BABYLON.Vector3.Zero();
  57187. this.zz = BABYLON.Vector3.Zero();
  57188. this.xy = BABYLON.Vector3.Zero();
  57189. this.yz = BABYLON.Vector3.Zero();
  57190. this.zx = BABYLON.Vector3.Zero();
  57191. }
  57192. SphericalPolynomial.prototype.addAmbient = function (color) {
  57193. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57194. this.xx = this.xx.add(colorVector);
  57195. this.yy = this.yy.add(colorVector);
  57196. this.zz = this.zz.add(colorVector);
  57197. };
  57198. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  57199. var result = new SphericalPolynomial();
  57200. result.x = harmonics.L11.scale(1.02333);
  57201. result.y = harmonics.L1_1.scale(1.02333);
  57202. result.z = harmonics.L10.scale(1.02333);
  57203. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  57204. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  57205. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  57206. result.yz = harmonics.L2_1.scale(0.858086);
  57207. result.zx = harmonics.L21.scale(0.858086);
  57208. result.xy = harmonics.L2_2.scale(0.858086);
  57209. result.scale(1.0 / Math.PI);
  57210. return result;
  57211. };
  57212. SphericalPolynomial.prototype.scale = function (scale) {
  57213. this.x = this.x.scale(scale);
  57214. this.y = this.y.scale(scale);
  57215. this.z = this.z.scale(scale);
  57216. this.xx = this.xx.scale(scale);
  57217. this.yy = this.yy.scale(scale);
  57218. this.zz = this.zz.scale(scale);
  57219. this.yz = this.yz.scale(scale);
  57220. this.zx = this.zx.scale(scale);
  57221. this.xy = this.xy.scale(scale);
  57222. };
  57223. return SphericalPolynomial;
  57224. }());
  57225. BABYLON.SphericalPolynomial = SphericalPolynomial;
  57226. var SphericalHarmonics = (function () {
  57227. function SphericalHarmonics() {
  57228. this.L00 = BABYLON.Vector3.Zero();
  57229. this.L1_1 = BABYLON.Vector3.Zero();
  57230. this.L10 = BABYLON.Vector3.Zero();
  57231. this.L11 = BABYLON.Vector3.Zero();
  57232. this.L2_2 = BABYLON.Vector3.Zero();
  57233. this.L2_1 = BABYLON.Vector3.Zero();
  57234. this.L20 = BABYLON.Vector3.Zero();
  57235. this.L21 = BABYLON.Vector3.Zero();
  57236. this.L22 = BABYLON.Vector3.Zero();
  57237. }
  57238. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  57239. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  57240. var c = colorVector.scale(deltaSolidAngle);
  57241. this.L00 = this.L00.add(c.scale(0.282095));
  57242. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  57243. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  57244. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  57245. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  57246. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  57247. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  57248. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  57249. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  57250. };
  57251. SphericalHarmonics.prototype.scale = function (scale) {
  57252. this.L00 = this.L00.scale(scale);
  57253. this.L1_1 = this.L1_1.scale(scale);
  57254. this.L10 = this.L10.scale(scale);
  57255. this.L11 = this.L11.scale(scale);
  57256. this.L2_2 = this.L2_2.scale(scale);
  57257. this.L2_1 = this.L2_1.scale(scale);
  57258. this.L20 = this.L20.scale(scale);
  57259. this.L21 = this.L21.scale(scale);
  57260. this.L22 = this.L22.scale(scale);
  57261. };
  57262. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  57263. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  57264. //
  57265. // E_lm = A_l * L_lm
  57266. //
  57267. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  57268. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  57269. // the scaling factors are given in equation 9.
  57270. // Constant (Band 0)
  57271. this.L00 = this.L00.scale(3.141593);
  57272. // Linear (Band 1)
  57273. this.L1_1 = this.L1_1.scale(2.094395);
  57274. this.L10 = this.L10.scale(2.094395);
  57275. this.L11 = this.L11.scale(2.094395);
  57276. // Quadratic (Band 2)
  57277. this.L2_2 = this.L2_2.scale(0.785398);
  57278. this.L2_1 = this.L2_1.scale(0.785398);
  57279. this.L20 = this.L20.scale(0.785398);
  57280. this.L21 = this.L21.scale(0.785398);
  57281. this.L22 = this.L22.scale(0.785398);
  57282. };
  57283. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  57284. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  57285. // L = (1/pi) * E * rho
  57286. //
  57287. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  57288. this.scale(1.0 / Math.PI);
  57289. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  57290. // (The pixel shader must apply albedo after texture fetches, etc).
  57291. };
  57292. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  57293. var result = new SphericalHarmonics();
  57294. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  57295. result.L1_1 = polynomial.y.scale(0.977204);
  57296. result.L10 = polynomial.z.scale(0.977204);
  57297. result.L11 = polynomial.x.scale(0.977204);
  57298. result.L2_2 = polynomial.xy.scale(1.16538);
  57299. result.L2_1 = polynomial.yz.scale(1.16538);
  57300. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  57301. result.L21 = polynomial.zx.scale(1.16538);
  57302. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  57303. result.scale(Math.PI);
  57304. return result;
  57305. };
  57306. return SphericalHarmonics;
  57307. }());
  57308. BABYLON.SphericalHarmonics = SphericalHarmonics;
  57309. })(BABYLON || (BABYLON = {}));
  57310. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  57311. var BABYLON;
  57312. (function (BABYLON) {
  57313. var Internals;
  57314. (function (Internals) {
  57315. var FileFaceOrientation = (function () {
  57316. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  57317. this.name = name;
  57318. this.worldAxisForNormal = worldAxisForNormal;
  57319. this.worldAxisForFileX = worldAxisForFileX;
  57320. this.worldAxisForFileY = worldAxisForFileY;
  57321. }
  57322. return FileFaceOrientation;
  57323. }());
  57324. ;
  57325. /**
  57326. * Helper class dealing with the extraction of spherical polynomial dataArray
  57327. * from a cube map.
  57328. */
  57329. var CubeMapToSphericalPolynomialTools = (function () {
  57330. function CubeMapToSphericalPolynomialTools() {
  57331. }
  57332. /**
  57333. * Converts a texture to the according Spherical Polynomial data.
  57334. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57335. *
  57336. * @param texture The texture to extract the information from.
  57337. * @return The Spherical Polynomial data.
  57338. */
  57339. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  57340. if (!texture.isCube) {
  57341. // Only supports cube Textures currently.
  57342. return null;
  57343. }
  57344. var size = texture.getSize().width;
  57345. var right = texture.readPixels(0);
  57346. var left = texture.readPixels(1);
  57347. var up;
  57348. var down;
  57349. if (texture.isRenderTarget) {
  57350. up = texture.readPixels(3);
  57351. down = texture.readPixels(2);
  57352. }
  57353. else {
  57354. up = texture.readPixels(2);
  57355. down = texture.readPixels(3);
  57356. }
  57357. var front = texture.readPixels(4);
  57358. var back = texture.readPixels(5);
  57359. var gammaSpace = texture.gammaSpace;
  57360. // Always read as RGBA.
  57361. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  57362. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  57363. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57364. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  57365. }
  57366. var cubeInfo = {
  57367. size: size,
  57368. right: right,
  57369. left: left,
  57370. up: up,
  57371. down: down,
  57372. front: front,
  57373. back: back,
  57374. format: format,
  57375. type: type,
  57376. gammaSpace: gammaSpace,
  57377. };
  57378. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  57379. };
  57380. /**
  57381. * Converts a cubemap to the according Spherical Polynomial data.
  57382. * This extracts the first 3 orders only as they are the only one used in the lighting.
  57383. *
  57384. * @param cubeInfo The Cube map to extract the information from.
  57385. * @return The Spherical Polynomial data.
  57386. */
  57387. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  57388. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  57389. var totalSolidAngle = 0.0;
  57390. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  57391. var du = 2.0 / cubeInfo.size;
  57392. var dv = du;
  57393. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  57394. var minUV = du * 0.5 - 1.0;
  57395. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57396. var fileFace = this.FileFaces[faceIndex];
  57397. var dataArray = cubeInfo[fileFace.name];
  57398. var v = minUV;
  57399. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  57400. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  57401. // Because SP is still linear, so summation is fine in that basis.
  57402. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  57403. for (var y = 0; y < cubeInfo.size; y++) {
  57404. var u = minUV;
  57405. for (var x = 0; x < cubeInfo.size; x++) {
  57406. // World direction (not normalised)
  57407. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  57408. worldDirection.normalize();
  57409. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  57410. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  57411. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  57412. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  57413. // Handle Integer types.
  57414. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  57415. r /= 255;
  57416. g /= 255;
  57417. b /= 255;
  57418. }
  57419. // Handle Gamma space textures.
  57420. if (cubeInfo.gammaSpace) {
  57421. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  57422. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  57423. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  57424. }
  57425. var color = new BABYLON.Color3(r, g, b);
  57426. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  57427. totalSolidAngle += deltaSolidAngle;
  57428. u += du;
  57429. }
  57430. v += dv;
  57431. }
  57432. }
  57433. // Solid angle for entire sphere is 4*pi
  57434. var sphereSolidAngle = 4.0 * Math.PI;
  57435. // Adjust the solid angle to allow for how many faces we processed.
  57436. var facesProcessed = 6.0;
  57437. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  57438. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  57439. // This is needed because the numerical integration over the cube uses a
  57440. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  57441. // and also to compensate for accumulative error due to float precision in the summation.
  57442. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  57443. sphericalHarmonics.scale(correctionFactor);
  57444. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  57445. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  57446. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  57447. };
  57448. CubeMapToSphericalPolynomialTools.FileFaces = [
  57449. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  57450. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  57451. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  57452. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  57453. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  57454. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  57455. ];
  57456. return CubeMapToSphericalPolynomialTools;
  57457. }());
  57458. Internals.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  57459. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57460. })(BABYLON || (BABYLON = {}));
  57461. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  57462. var BABYLON;
  57463. (function (BABYLON) {
  57464. var Internals;
  57465. (function (Internals) {
  57466. /**
  57467. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  57468. */
  57469. var PanoramaToCubeMapTools = (function () {
  57470. function PanoramaToCubeMapTools() {
  57471. }
  57472. /**
  57473. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  57474. *
  57475. * @param float32Array The source data.
  57476. * @param inputWidth The width of the input panorama.
  57477. * @param inputhHeight The height of the input panorama.
  57478. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  57479. * @return The cubemap data
  57480. */
  57481. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  57482. if (!float32Array) {
  57483. throw "ConvertPanoramaToCubemap: input cannot be null";
  57484. }
  57485. if (float32Array.length != inputWidth * inputHeight * 3) {
  57486. throw "ConvertPanoramaToCubemap: input size is wrong";
  57487. }
  57488. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  57489. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  57490. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  57491. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  57492. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  57493. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  57494. return {
  57495. front: textureFront,
  57496. back: textureBack,
  57497. left: textureLeft,
  57498. right: textureRight,
  57499. up: textureUp,
  57500. down: textureDown,
  57501. size: size,
  57502. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  57503. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  57504. gammaSpace: false,
  57505. };
  57506. };
  57507. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  57508. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  57509. var textureArray = new Float32Array(buffer);
  57510. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  57511. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  57512. var dy = 1 / texSize;
  57513. var fy = 0;
  57514. for (var y = 0; y < texSize; y++) {
  57515. var xv1 = faceData[0];
  57516. var xv2 = faceData[2];
  57517. for (var x = 0; x < texSize; x++) {
  57518. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  57519. v.normalize();
  57520. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  57521. // 3 channels per pixels
  57522. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  57523. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  57524. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  57525. xv1 = xv1.add(rotDX1);
  57526. xv2 = xv2.add(rotDX2);
  57527. }
  57528. fy += dy;
  57529. }
  57530. return textureArray;
  57531. };
  57532. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  57533. var theta = Math.atan2(vDir.z, vDir.x);
  57534. var phi = Math.acos(vDir.y);
  57535. while (theta < -Math.PI)
  57536. theta += 2 * Math.PI;
  57537. while (theta > Math.PI)
  57538. theta -= 2 * Math.PI;
  57539. var dx = theta / Math.PI;
  57540. var dy = phi / Math.PI;
  57541. // recenter.
  57542. dx = dx * 0.5 + 0.5;
  57543. var px = Math.round(dx * inputWidth);
  57544. if (px < 0)
  57545. px = 0;
  57546. else if (px >= inputWidth)
  57547. px = inputWidth - 1;
  57548. var py = Math.round(dy * inputHeight);
  57549. if (py < 0)
  57550. py = 0;
  57551. else if (py >= inputHeight)
  57552. py = inputHeight - 1;
  57553. var inputY = (inputHeight - py - 1);
  57554. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  57555. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  57556. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  57557. return {
  57558. r: r,
  57559. g: g,
  57560. b: b
  57561. };
  57562. };
  57563. PanoramaToCubeMapTools.FACE_FRONT = [
  57564. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57565. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57566. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57567. new BABYLON.Vector3(1.0, 1.0, -1.0)
  57568. ];
  57569. PanoramaToCubeMapTools.FACE_BACK = [
  57570. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57571. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57572. new BABYLON.Vector3(1.0, 1.0, 1.0),
  57573. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  57574. ];
  57575. PanoramaToCubeMapTools.FACE_RIGHT = [
  57576. new BABYLON.Vector3(1.0, -1.0, -1.0),
  57577. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57578. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57579. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57580. ];
  57581. PanoramaToCubeMapTools.FACE_LEFT = [
  57582. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57583. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57584. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57585. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  57586. ];
  57587. PanoramaToCubeMapTools.FACE_DOWN = [
  57588. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  57589. new BABYLON.Vector3(1.0, 1.0, -1.0),
  57590. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  57591. new BABYLON.Vector3(1.0, 1.0, 1.0)
  57592. ];
  57593. PanoramaToCubeMapTools.FACE_UP = [
  57594. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  57595. new BABYLON.Vector3(1.0, -1.0, 1.0),
  57596. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  57597. new BABYLON.Vector3(1.0, -1.0, -1.0)
  57598. ];
  57599. return PanoramaToCubeMapTools;
  57600. }());
  57601. Internals.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  57602. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57603. })(BABYLON || (BABYLON = {}));
  57604. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  57605. var BABYLON;
  57606. (function (BABYLON) {
  57607. var Internals;
  57608. (function (Internals) {
  57609. ;
  57610. /**
  57611. * This groups tools to convert HDR texture to native colors array.
  57612. */
  57613. var HDRTools = (function () {
  57614. function HDRTools() {
  57615. }
  57616. HDRTools.Ldexp = function (mantissa, exponent) {
  57617. if (exponent > 1023) {
  57618. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  57619. }
  57620. if (exponent < -1074) {
  57621. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  57622. }
  57623. return mantissa * Math.pow(2, exponent);
  57624. };
  57625. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  57626. if (exponent > 0) {
  57627. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  57628. float32array[index + 0] = red * exponent;
  57629. float32array[index + 1] = green * exponent;
  57630. float32array[index + 2] = blue * exponent;
  57631. }
  57632. else {
  57633. float32array[index + 0] = 0;
  57634. float32array[index + 1] = 0;
  57635. float32array[index + 2] = 0;
  57636. }
  57637. };
  57638. HDRTools.readStringLine = function (uint8array, startIndex) {
  57639. var line = "";
  57640. var character = "";
  57641. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  57642. character = String.fromCharCode(uint8array[i]);
  57643. if (character == "\n") {
  57644. break;
  57645. }
  57646. line += character;
  57647. }
  57648. return line;
  57649. };
  57650. /**
  57651. * Reads header information from an RGBE texture stored in a native array.
  57652. * More information on this format are available here:
  57653. * https://en.wikipedia.org/wiki/RGBE_image_format
  57654. *
  57655. * @param uint8array The binary file stored in native array.
  57656. * @return The header information.
  57657. */
  57658. HDRTools.RGBE_ReadHeader = function (uint8array) {
  57659. var height = 0;
  57660. var width = 0;
  57661. var line = this.readStringLine(uint8array, 0);
  57662. if (line[0] != '#' || line[1] != '?') {
  57663. throw "Bad HDR Format.";
  57664. }
  57665. var endOfHeader = false;
  57666. var findFormat = false;
  57667. var lineIndex = 0;
  57668. do {
  57669. lineIndex += (line.length + 1);
  57670. line = this.readStringLine(uint8array, lineIndex);
  57671. if (line == "FORMAT=32-bit_rle_rgbe") {
  57672. findFormat = true;
  57673. }
  57674. else if (line.length == 0) {
  57675. endOfHeader = true;
  57676. }
  57677. } while (!endOfHeader);
  57678. if (!findFormat) {
  57679. throw "HDR Bad header format, unsupported FORMAT";
  57680. }
  57681. lineIndex += (line.length + 1);
  57682. line = this.readStringLine(uint8array, lineIndex);
  57683. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  57684. var match = sizeRegexp.exec(line);
  57685. // TODO. Support +Y and -X if needed.
  57686. if (match.length < 3) {
  57687. throw "HDR Bad header format, no size";
  57688. }
  57689. width = parseInt(match[2]);
  57690. height = parseInt(match[1]);
  57691. if (width < 8 || width > 0x7fff) {
  57692. throw "HDR Bad header format, unsupported size";
  57693. }
  57694. lineIndex += (line.length + 1);
  57695. return {
  57696. height: height,
  57697. width: width,
  57698. dataPosition: lineIndex
  57699. };
  57700. };
  57701. /**
  57702. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  57703. * This RGBE texture needs to store the information as a panorama.
  57704. *
  57705. * More information on this format are available here:
  57706. * https://en.wikipedia.org/wiki/RGBE_image_format
  57707. *
  57708. * @param buffer The binary file stored in an array buffer.
  57709. * @param size The expected size of the extracted cubemap.
  57710. * @return The Cube Map information.
  57711. */
  57712. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  57713. var uint8array = new Uint8Array(buffer);
  57714. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  57715. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57716. var cubeMapData = Internals.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  57717. return cubeMapData;
  57718. };
  57719. /**
  57720. * Returns the pixels data extracted from an RGBE texture.
  57721. * This pixels will be stored left to right up to down in the R G B order in one array.
  57722. *
  57723. * More information on this format are available here:
  57724. * https://en.wikipedia.org/wiki/RGBE_image_format
  57725. *
  57726. * @param uint8array The binary file stored in an array buffer.
  57727. * @param hdrInfo The header information of the file.
  57728. * @return The pixels data in RGB right to left up to down order.
  57729. */
  57730. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  57731. // Keep for multi format supports.
  57732. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  57733. };
  57734. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  57735. var num_scanlines = hdrInfo.height;
  57736. var scanline_width = hdrInfo.width;
  57737. var a, b, c, d, count;
  57738. var dataIndex = hdrInfo.dataPosition;
  57739. var index = 0, endIndex = 0, i = 0;
  57740. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  57741. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  57742. // 3 channels of 4 bytes per pixel in float.
  57743. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  57744. var resultArray = new Float32Array(resultBuffer);
  57745. // read in each successive scanline
  57746. while (num_scanlines > 0) {
  57747. a = uint8array[dataIndex++];
  57748. b = uint8array[dataIndex++];
  57749. c = uint8array[dataIndex++];
  57750. d = uint8array[dataIndex++];
  57751. if (a != 2 || b != 2 || (c & 0x80)) {
  57752. // this file is not run length encoded
  57753. throw "HDR Bad header format, not RLE";
  57754. }
  57755. if (((c << 8) | d) != scanline_width) {
  57756. throw "HDR Bad header format, wrong scan line width";
  57757. }
  57758. index = 0;
  57759. // read each of the four channels for the scanline into the buffer
  57760. for (i = 0; i < 4; i++) {
  57761. endIndex = (i + 1) * scanline_width;
  57762. while (index < endIndex) {
  57763. a = uint8array[dataIndex++];
  57764. b = uint8array[dataIndex++];
  57765. if (a > 128) {
  57766. // a run of the same value
  57767. count = a - 128;
  57768. if ((count == 0) || (count > endIndex - index)) {
  57769. throw "HDR Bad Format, bad scanline data (run)";
  57770. }
  57771. while (count-- > 0) {
  57772. scanLineArray[index++] = b;
  57773. }
  57774. }
  57775. else {
  57776. // a non-run
  57777. count = a;
  57778. if ((count == 0) || (count > endIndex - index)) {
  57779. throw "HDR Bad Format, bad scanline data (non-run)";
  57780. }
  57781. scanLineArray[index++] = b;
  57782. if (--count > 0) {
  57783. for (var j = 0; j < count; j++) {
  57784. scanLineArray[index++] = uint8array[dataIndex++];
  57785. }
  57786. }
  57787. }
  57788. }
  57789. }
  57790. // now convert data from buffer into floats
  57791. for (i = 0; i < scanline_width; i++) {
  57792. a = scanLineArray[i];
  57793. b = scanLineArray[i + scanline_width];
  57794. c = scanLineArray[i + 2 * scanline_width];
  57795. d = scanLineArray[i + 3 * scanline_width];
  57796. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  57797. }
  57798. num_scanlines--;
  57799. }
  57800. return resultArray;
  57801. };
  57802. return HDRTools;
  57803. }());
  57804. Internals.HDRTools = HDRTools;
  57805. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  57806. })(BABYLON || (BABYLON = {}));
  57807. //# sourceMappingURL=babylon.hdr.js.map
  57808. var BABYLON;
  57809. (function (BABYLON) {
  57810. /**
  57811. * This represents a texture coming from an HDR input.
  57812. *
  57813. * The only supported format is currently panorama picture stored in RGBE format.
  57814. * Example of such files can be found on HDRLib: http://hdrlib.com/
  57815. */
  57816. var HDRCubeTexture = (function (_super) {
  57817. __extends(HDRCubeTexture, _super);
  57818. /**
  57819. * Instantiates an HDRTexture from the following parameters.
  57820. *
  57821. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  57822. * @param scene The scene the texture will be used in
  57823. * @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.
  57824. * @param noMipmap Forces to not generate the mipmap if true
  57825. * @param generateHarmonics Specifies wether you want to extract the polynomial harmonics during the generation process
  57826. * @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)
  57827. * @param usePMREMGenerator Specifies wether or not to generate the CubeMap through CubeMapGen to avoid seams issue at run time.
  57828. */
  57829. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator, onLoad, onError) {
  57830. if (noMipmap === void 0) { noMipmap = false; }
  57831. if (generateHarmonics === void 0) { generateHarmonics = true; }
  57832. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  57833. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  57834. if (onLoad === void 0) { onLoad = null; }
  57835. if (onError === void 0) { onError = null; }
  57836. var _this = _super.call(this, scene) || this;
  57837. _this._useInGammaSpace = false;
  57838. _this._generateHarmonics = true;
  57839. _this._isBABYLONPreprocessed = false;
  57840. _this._onLoad = null;
  57841. _this._onError = null;
  57842. /**
  57843. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  57844. */
  57845. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  57846. /**
  57847. * Specifies wether the texture has been generated through the PMREMGenerator tool.
  57848. * This is usefull at run time to apply the good shader.
  57849. */
  57850. _this.isPMREM = false;
  57851. _this._isBlocking = true;
  57852. if (!url) {
  57853. return _this;
  57854. }
  57855. _this.name = url;
  57856. _this.url = url;
  57857. _this.hasAlpha = false;
  57858. _this.isCube = true;
  57859. _this._textureMatrix = BABYLON.Matrix.Identity();
  57860. _this._onLoad = onLoad;
  57861. _this._onError = onError;
  57862. _this.gammaSpace = false;
  57863. if (size) {
  57864. _this._isBABYLONPreprocessed = false;
  57865. _this._noMipmap = noMipmap;
  57866. _this._size = size;
  57867. _this._useInGammaSpace = useInGammaSpace;
  57868. _this._usePMREMGenerator = usePMREMGenerator &&
  57869. scene.getEngine().getCaps().textureLOD &&
  57870. _this.getScene().getEngine().getCaps().textureFloat &&
  57871. !_this._useInGammaSpace;
  57872. }
  57873. else {
  57874. _this._isBABYLONPreprocessed = true;
  57875. _this._noMipmap = false;
  57876. _this._useInGammaSpace = false;
  57877. _this._usePMREMGenerator = scene.getEngine().getCaps().textureLOD &&
  57878. _this.getScene().getEngine().getCaps().textureFloat &&
  57879. !_this._useInGammaSpace;
  57880. }
  57881. _this.isPMREM = _this._usePMREMGenerator;
  57882. _this._texture = _this._getFromCache(url, _this._noMipmap);
  57883. if (!_this._texture) {
  57884. if (!scene.useDelayedTextureLoading) {
  57885. _this.loadTexture();
  57886. }
  57887. else {
  57888. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  57889. }
  57890. }
  57891. return _this;
  57892. }
  57893. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  57894. /**
  57895. * Gets wether or not the texture is blocking during loading.
  57896. */
  57897. get: function () {
  57898. return this._isBlocking;
  57899. },
  57900. /**
  57901. * Sets wether or not the texture is blocking during loading.
  57902. */
  57903. set: function (value) {
  57904. this._isBlocking = value;
  57905. },
  57906. enumerable: true,
  57907. configurable: true
  57908. });
  57909. /**
  57910. * Occurs when the file is a preprocessed .babylon.hdr file.
  57911. */
  57912. HDRCubeTexture.prototype.loadBabylonTexture = function () {
  57913. var _this = this;
  57914. var mipLevels = 0;
  57915. var floatArrayView = null;
  57916. var mipmapGenerator = (!this._useInGammaSpace && this.getScene().getEngine().getCaps().textureFloat) ? function (data) {
  57917. var mips = [];
  57918. var startIndex = 30;
  57919. for (var level = 0; level < mipLevels; level++) {
  57920. mips.push([]);
  57921. // Fill each pixel of the mip level.
  57922. var faceSize = Math.pow(_this._size >> level, 2) * 3;
  57923. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57924. var faceData = floatArrayView.subarray(startIndex, startIndex + faceSize);
  57925. mips[level].push(faceData);
  57926. startIndex += faceSize;
  57927. }
  57928. }
  57929. return mips;
  57930. } : null;
  57931. var callback = function (buffer) {
  57932. // Create Native Array Views
  57933. var intArrayView = new Int32Array(buffer);
  57934. floatArrayView = new Float32Array(buffer);
  57935. // Fill header.
  57936. var version = intArrayView[0]; // Version 1. (MAy be use in case of format changes for backward compaibility)
  57937. _this._size = intArrayView[1]; // CubeMap max mip face size.
  57938. // Update Texture Information.
  57939. _this._texture.updateSize(_this._size, _this._size);
  57940. // Fill polynomial information.
  57941. var sphericalPolynomial = new BABYLON.SphericalPolynomial();
  57942. sphericalPolynomial.x.copyFromFloats(floatArrayView[2], floatArrayView[3], floatArrayView[4]);
  57943. sphericalPolynomial.y.copyFromFloats(floatArrayView[5], floatArrayView[6], floatArrayView[7]);
  57944. sphericalPolynomial.z.copyFromFloats(floatArrayView[8], floatArrayView[9], floatArrayView[10]);
  57945. sphericalPolynomial.xx.copyFromFloats(floatArrayView[11], floatArrayView[12], floatArrayView[13]);
  57946. sphericalPolynomial.yy.copyFromFloats(floatArrayView[14], floatArrayView[15], floatArrayView[16]);
  57947. sphericalPolynomial.zz.copyFromFloats(floatArrayView[17], floatArrayView[18], floatArrayView[19]);
  57948. sphericalPolynomial.xy.copyFromFloats(floatArrayView[20], floatArrayView[21], floatArrayView[22]);
  57949. sphericalPolynomial.yz.copyFromFloats(floatArrayView[23], floatArrayView[24], floatArrayView[25]);
  57950. sphericalPolynomial.zx.copyFromFloats(floatArrayView[26], floatArrayView[27], floatArrayView[28]);
  57951. _this.sphericalPolynomial = sphericalPolynomial;
  57952. // Fill pixel data.
  57953. mipLevels = intArrayView[29]; // Number of mip levels.
  57954. var startIndex = 30;
  57955. var data = [];
  57956. var faceSize = Math.pow(_this._size, 2) * 3;
  57957. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  57958. data.push(floatArrayView.subarray(startIndex, startIndex + faceSize));
  57959. startIndex += faceSize;
  57960. }
  57961. var results = [];
  57962. var byteArray = null;
  57963. // Push each faces.
  57964. for (var k = 0; k < 6; k++) {
  57965. var dataFace = null;
  57966. // To be deprecated.
  57967. if (version === 1) {
  57968. var j = ([0, 2, 4, 1, 3, 5])[k]; // Transforms +X+Y+Z... to +X-X+Y-Y...
  57969. dataFace = data[j];
  57970. }
  57971. // If special cases.
  57972. if (!mipmapGenerator) {
  57973. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  57974. // 3 channels of 1 bytes per pixel in bytes.
  57975. var byteBuffer = new ArrayBuffer(faceSize);
  57976. byteArray = new Uint8Array(byteBuffer);
  57977. }
  57978. for (var i = 0; i < _this._size * _this._size; i++) {
  57979. // Put in gamma space if requested.
  57980. if (_this._useInGammaSpace) {
  57981. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  57982. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  57983. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  57984. }
  57985. // Convert to int texture for fallback.
  57986. if (byteArray) {
  57987. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  57988. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  57989. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  57990. // May use luminance instead if the result is not accurate.
  57991. var max = Math.max(Math.max(r, g), b);
  57992. if (max > 255) {
  57993. var scale = 255 / max;
  57994. r *= scale;
  57995. g *= scale;
  57996. b *= scale;
  57997. }
  57998. byteArray[(i * 3) + 0] = r;
  57999. byteArray[(i * 3) + 1] = g;
  58000. byteArray[(i * 3) + 2] = b;
  58001. }
  58002. }
  58003. }
  58004. // Fill the array accordingly.
  58005. if (byteArray) {
  58006. results.push(byteArray);
  58007. }
  58008. else {
  58009. results.push(dataFace);
  58010. }
  58011. }
  58012. return results;
  58013. };
  58014. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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, this._onLoad, this._onError);
  58015. };
  58016. /**
  58017. * Occurs when the file is raw .hdr file.
  58018. */
  58019. HDRCubeTexture.prototype.loadHDRTexture = function () {
  58020. var _this = this;
  58021. var callback = function (buffer) {
  58022. // Extract the raw linear data.
  58023. var data = BABYLON.Internals.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  58024. // Generate harmonics if needed.
  58025. if (_this._generateHarmonics) {
  58026. var sphericalPolynomial = BABYLON.Internals.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  58027. _this.sphericalPolynomial = sphericalPolynomial;
  58028. }
  58029. var results = [];
  58030. var byteArray = null;
  58031. // Push each faces.
  58032. for (var j = 0; j < 6; j++) {
  58033. // Create uintarray fallback.
  58034. if (!_this.getScene().getEngine().getCaps().textureFloat) {
  58035. // 3 channels of 1 bytes per pixel in bytes.
  58036. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  58037. byteArray = new Uint8Array(byteBuffer);
  58038. }
  58039. var dataFace = data[HDRCubeTexture._facesMapping[j]];
  58040. // If special cases.
  58041. if (_this._useInGammaSpace || byteArray) {
  58042. for (var i = 0; i < _this._size * _this._size; i++) {
  58043. // Put in gamma space if requested.
  58044. if (_this._useInGammaSpace) {
  58045. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  58046. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  58047. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  58048. }
  58049. // Convert to int texture for fallback.
  58050. if (byteArray) {
  58051. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  58052. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  58053. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  58054. // May use luminance instead if the result is not accurate.
  58055. var max = Math.max(Math.max(r, g), b);
  58056. if (max > 255) {
  58057. var scale = 255 / max;
  58058. r *= scale;
  58059. g *= scale;
  58060. b *= scale;
  58061. }
  58062. byteArray[(i * 3) + 0] = r;
  58063. byteArray[(i * 3) + 1] = g;
  58064. byteArray[(i * 3) + 2] = b;
  58065. }
  58066. }
  58067. }
  58068. if (byteArray) {
  58069. results.push(byteArray);
  58070. }
  58071. else {
  58072. results.push(dataFace);
  58073. }
  58074. }
  58075. return results;
  58076. };
  58077. var mipmapGenerator = null;
  58078. // TODO. Implement In code PMREM Generator following the LYS toolset generation.
  58079. // if (!this._noMipmap &&
  58080. // this._usePMREMGenerator) {
  58081. // mipmapGenerator = (data: ArrayBufferView[]) => {
  58082. // // Custom setup of the generator matching with the PBR shader values.
  58083. // var generator = new BABYLON.Internals.PMREMGenerator(data,
  58084. // this._size,
  58085. // this._size,
  58086. // 0,
  58087. // 3,
  58088. // this.getScene().getEngine().getCaps().textureFloat,
  58089. // 2048,
  58090. // 0.25,
  58091. // false,
  58092. // true);
  58093. // return generator.filterCubeMap();
  58094. // };
  58095. // }
  58096. this._texture = this.getScene().getEngine().createRawCubeTextureFromUrl(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, this._onLoad, this._onError);
  58097. };
  58098. /**
  58099. * Starts the loading process of the texture.
  58100. */
  58101. HDRCubeTexture.prototype.loadTexture = function () {
  58102. if (this._isBABYLONPreprocessed) {
  58103. this.loadBabylonTexture();
  58104. }
  58105. else {
  58106. this.loadHDRTexture();
  58107. }
  58108. };
  58109. HDRCubeTexture.prototype.clone = function () {
  58110. var size = this._isBABYLONPreprocessed ? null : this._size;
  58111. var newTexture = new HDRCubeTexture(this.url, this.getScene(), size, this._noMipmap, this._generateHarmonics, this._useInGammaSpace, this._usePMREMGenerator);
  58112. // Base texture
  58113. newTexture.level = this.level;
  58114. newTexture.wrapU = this.wrapU;
  58115. newTexture.wrapV = this.wrapV;
  58116. newTexture.coordinatesIndex = this.coordinatesIndex;
  58117. newTexture.coordinatesMode = this.coordinatesMode;
  58118. return newTexture;
  58119. };
  58120. // Methods
  58121. HDRCubeTexture.prototype.delayLoad = function () {
  58122. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  58123. return;
  58124. }
  58125. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  58126. this._texture = this._getFromCache(this.url, this._noMipmap);
  58127. if (!this._texture) {
  58128. this.loadTexture();
  58129. }
  58130. };
  58131. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  58132. return this._textureMatrix;
  58133. };
  58134. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  58135. this._textureMatrix = value;
  58136. };
  58137. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  58138. var texture = null;
  58139. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  58140. var size = parsedTexture.isBABYLONPreprocessed ? null : parsedTexture.size;
  58141. texture = new BABYLON.HDRCubeTexture(rootUrl + parsedTexture.name, scene, size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace, parsedTexture.usePMREMGenerator);
  58142. texture.name = parsedTexture.name;
  58143. texture.hasAlpha = parsedTexture.hasAlpha;
  58144. texture.level = parsedTexture.level;
  58145. texture.coordinatesMode = parsedTexture.coordinatesMode;
  58146. texture.isBlocking = parsedTexture.isBlocking;
  58147. }
  58148. return texture;
  58149. };
  58150. HDRCubeTexture.prototype.serialize = function () {
  58151. if (!this.name) {
  58152. return null;
  58153. }
  58154. var serializationObject = {};
  58155. serializationObject.name = this.name;
  58156. serializationObject.hasAlpha = this.hasAlpha;
  58157. serializationObject.isCube = true;
  58158. serializationObject.level = this.level;
  58159. serializationObject.size = this._size;
  58160. serializationObject.coordinatesMode = this.coordinatesMode;
  58161. serializationObject.useInGammaSpace = this._useInGammaSpace;
  58162. serializationObject.generateHarmonics = this._generateHarmonics;
  58163. serializationObject.usePMREMGenerator = this._usePMREMGenerator;
  58164. serializationObject.isBABYLONPreprocessed = this._isBABYLONPreprocessed;
  58165. serializationObject.customType = "BABYLON.HDRCubeTexture";
  58166. serializationObject.noMipmap = this._noMipmap;
  58167. serializationObject.isBlocking = this._isBlocking;
  58168. return serializationObject;
  58169. };
  58170. /**
  58171. * Saves as a file the data contained in the texture in a binary format.
  58172. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58173. * as the spherical used in the lighting.
  58174. * @param url The HDR file url.
  58175. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58176. * @param onError Method called if any error happens during download.
  58177. * @return The packed binary data.
  58178. */
  58179. HDRCubeTexture.generateBabylonHDROnDisk = function (url, size, onError) {
  58180. if (onError === void 0) { onError = null; }
  58181. var callback = function (buffer) {
  58182. var data = new Blob([buffer], { type: 'application/octet-stream' });
  58183. // Returns a URL you can use as a href.
  58184. var objUrl = window.URL.createObjectURL(data);
  58185. // Simulates a link to it and click to dowload.
  58186. var a = document.createElement("a");
  58187. document.body.appendChild(a);
  58188. a.style.display = "none";
  58189. a.href = objUrl;
  58190. a.download = "envmap.babylon.hdr";
  58191. a.click();
  58192. };
  58193. HDRCubeTexture.generateBabylonHDR(url, size, callback, onError);
  58194. };
  58195. /**
  58196. * Serializes the data contained in the texture in a binary format.
  58197. * This can be used to prevent the long loading tie associated with creating the seamless texture as well
  58198. * as the spherical used in the lighting.
  58199. * @param url The HDR file url.
  58200. * @param size The size of the texture data to generate (one of the cubemap face desired width).
  58201. * @param onError Method called if any error happens during download.
  58202. * @return The packed binary data.
  58203. */
  58204. HDRCubeTexture.generateBabylonHDR = function (url, size, callback, onError) {
  58205. if (onError === void 0) { onError = null; }
  58206. // Needs the url tho create the texture.
  58207. if (!url) {
  58208. return null;
  58209. }
  58210. // Check Power of two size.
  58211. if (!BABYLON.Tools.IsExponentOfTwo(size)) {
  58212. return null;
  58213. }
  58214. // Coming Back in 3.1.
  58215. BABYLON.Tools.Error("Generation of Babylon HDR is coming back in 3.1.");
  58216. return null;
  58217. };
  58218. HDRCubeTexture._facesMapping = [
  58219. "right",
  58220. "left",
  58221. "up",
  58222. "down",
  58223. "front",
  58224. "back"
  58225. ];
  58226. return HDRCubeTexture;
  58227. }(BABYLON.BaseTexture));
  58228. BABYLON.HDRCubeTexture = HDRCubeTexture;
  58229. })(BABYLON || (BABYLON = {}));
  58230. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  58231. // All the credit goes to this project and the guy who's behind it https://github.com/mapbox/earcut
  58232. // Huge respect for a such great lib.
  58233. // Earcut license:
  58234. // Copyright (c) 2016, Mapbox
  58235. //
  58236. // Permission to use, copy, modify, and/or distribute this software for any purpose
  58237. // with or without fee is hereby granted, provided that the above copyright notice
  58238. // and this permission notice appear in all copies.
  58239. //
  58240. // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
  58241. // REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND
  58242. // FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
  58243. // INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS
  58244. // OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
  58245. // TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF
  58246. // THIS SOFTWARE.
  58247. var Earcut;
  58248. (function (Earcut) {
  58249. /**
  58250. * The fastest and smallest JavaScript polygon triangulation library for your WebGL apps
  58251. * @param data is a flat array of vertice coordinates like [x0, y0, x1, y1, x2, y2, ...].
  58252. * @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).
  58253. * @param dim is the number of coordinates per vertice in the input array (2 by default).
  58254. */
  58255. function earcut(data, holeIndices, dim) {
  58256. dim = dim || 2;
  58257. var hasHoles = holeIndices && holeIndices.length, outerLen = hasHoles ? holeIndices[0] * dim : data.length, outerNode = linkedList(data, 0, outerLen, dim, true), triangles = [];
  58258. if (!outerNode)
  58259. return triangles;
  58260. var minX, minY, maxX, maxY, x, y, size;
  58261. if (hasHoles)
  58262. outerNode = eliminateHoles(data, holeIndices, outerNode, dim);
  58263. // if the shape is not too simple, we'll use z-order curve hash later; calculate polygon bbox
  58264. if (data.length > 80 * dim) {
  58265. minX = maxX = data[0];
  58266. minY = maxY = data[1];
  58267. for (var i = dim; i < outerLen; i += dim) {
  58268. x = data[i];
  58269. y = data[i + 1];
  58270. if (x < minX)
  58271. minX = x;
  58272. if (y < minY)
  58273. minY = y;
  58274. if (x > maxX)
  58275. maxX = x;
  58276. if (y > maxY)
  58277. maxY = y;
  58278. }
  58279. // minX, minY and size are later used to transform coords into integers for z-order calculation
  58280. size = Math.max(maxX - minX, maxY - minY);
  58281. }
  58282. earcutLinked(outerNode, triangles, dim, minX, minY, size, undefined);
  58283. return triangles;
  58284. }
  58285. Earcut.earcut = earcut;
  58286. // create a circular doubly linked list from polygon points in the specified winding order
  58287. function linkedList(data, start, end, dim, clockwise) {
  58288. var i, last;
  58289. if (clockwise === (signedArea(data, start, end, dim) > 0)) {
  58290. for (i = start; i < end; i += dim)
  58291. last = insertNode(i, data[i], data[i + 1], last);
  58292. }
  58293. else {
  58294. for (i = end - dim; i >= start; i -= dim)
  58295. last = insertNode(i, data[i], data[i + 1], last);
  58296. }
  58297. if (last && equals(last, last.next)) {
  58298. removeNode(last);
  58299. last = last.next;
  58300. }
  58301. return last;
  58302. }
  58303. // eliminate colinear or duplicate points
  58304. function filterPoints(start, end) {
  58305. if (!start)
  58306. return start;
  58307. if (!end)
  58308. end = start;
  58309. var p = start, again;
  58310. do {
  58311. again = false;
  58312. if (!p.steiner && (equals(p, p.next) || area(p.prev, p, p.next) === 0)) {
  58313. removeNode(p);
  58314. p = end = p.prev;
  58315. if (p === p.next)
  58316. return null;
  58317. again = true;
  58318. }
  58319. else {
  58320. p = p.next;
  58321. }
  58322. } while (again || p !== end);
  58323. return end;
  58324. }
  58325. // main ear slicing loop which triangulates a polygon (given as a linked list)
  58326. function earcutLinked(ear, triangles, dim, minX, minY, size, pass) {
  58327. if (!ear)
  58328. return;
  58329. // interlink polygon nodes in z-order
  58330. if (!pass && size)
  58331. indexCurve(ear, minX, minY, size);
  58332. var stop = ear, prev, next;
  58333. // iterate through ears, slicing them one by one
  58334. while (ear.prev !== ear.next) {
  58335. prev = ear.prev;
  58336. next = ear.next;
  58337. if (size ? isEarHashed(ear, minX, minY, size) : isEar(ear)) {
  58338. // cut off the triangle
  58339. triangles.push(prev.i / dim);
  58340. triangles.push(ear.i / dim);
  58341. triangles.push(next.i / dim);
  58342. removeNode(ear);
  58343. // skipping the next vertice leads to less sliver triangles
  58344. ear = next.next;
  58345. stop = next.next;
  58346. continue;
  58347. }
  58348. ear = next;
  58349. // if we looped through the whole remaining polygon and can't find any more ears
  58350. if (ear === stop) {
  58351. // try filtering points and slicing again
  58352. if (!pass) {
  58353. earcutLinked(filterPoints(ear, undefined), triangles, dim, minX, minY, size, 1);
  58354. // if this didn't work, try curing all small self-intersections locally
  58355. }
  58356. else if (pass === 1) {
  58357. ear = cureLocalIntersections(ear, triangles, dim);
  58358. earcutLinked(ear, triangles, dim, minX, minY, size, 2);
  58359. // as a last resort, try splitting the remaining polygon into two
  58360. }
  58361. else if (pass === 2) {
  58362. splitEarcut(ear, triangles, dim, minX, minY, size);
  58363. }
  58364. break;
  58365. }
  58366. }
  58367. }
  58368. // check whether a polygon node forms a valid ear with adjacent nodes
  58369. function isEar(ear) {
  58370. var a = ear.prev, b = ear, c = ear.next;
  58371. if (area(a, b, c) >= 0)
  58372. return false; // reflex, can't be an ear
  58373. // now make sure we don't have other points inside the potential ear
  58374. var p = ear.next.next;
  58375. while (p !== ear.prev) {
  58376. if (pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58377. area(p.prev, p, p.next) >= 0)
  58378. return false;
  58379. p = p.next;
  58380. }
  58381. return true;
  58382. }
  58383. function isEarHashed(ear, minX, minY, size) {
  58384. var a = ear.prev, b = ear, c = ear.next;
  58385. if (area(a, b, c) >= 0)
  58386. return false; // reflex, can't be an ear
  58387. // triangle bbox; min & max are calculated like this for speed
  58388. 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);
  58389. // z-order range for the current triangle bbox;
  58390. var minZ = zOrder(minTX, minTY, minX, minY, size), maxZ = zOrder(maxTX, maxTY, minX, minY, size);
  58391. // first look for points inside the triangle in increasing z-order
  58392. var p = ear.nextZ;
  58393. while (p && p.z <= maxZ) {
  58394. if (p !== ear.prev &&
  58395. p !== ear.next &&
  58396. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58397. area(p.prev, p, p.next) >= 0)
  58398. return false;
  58399. p = p.nextZ;
  58400. }
  58401. // then look for points in decreasing z-order
  58402. p = ear.prevZ;
  58403. while (p && p.z >= minZ) {
  58404. if (p !== ear.prev &&
  58405. p !== ear.next &&
  58406. pointInTriangle(a.x, a.y, b.x, b.y, c.x, c.y, p.x, p.y) &&
  58407. area(p.prev, p, p.next) >= 0)
  58408. return false;
  58409. p = p.prevZ;
  58410. }
  58411. return true;
  58412. }
  58413. // go through all polygon nodes and cure small local self-intersections
  58414. function cureLocalIntersections(start, triangles, dim) {
  58415. var p = start;
  58416. do {
  58417. var a = p.prev, b = p.next.next;
  58418. if (!equals(a, b) && intersects(a, p, p.next, b) && locallyInside(a, b) && locallyInside(b, a)) {
  58419. triangles.push(a.i / dim);
  58420. triangles.push(p.i / dim);
  58421. triangles.push(b.i / dim);
  58422. // remove two nodes involved
  58423. removeNode(p);
  58424. removeNode(p.next);
  58425. p = start = b;
  58426. }
  58427. p = p.next;
  58428. } while (p !== start);
  58429. return p;
  58430. }
  58431. // try splitting polygon into two and triangulate them independently
  58432. function splitEarcut(start, triangles, dim, minX, minY, size) {
  58433. // look for a valid diagonal that divides the polygon into two
  58434. var a = start;
  58435. do {
  58436. var b = a.next.next;
  58437. while (b !== a.prev) {
  58438. if (a.i !== b.i && isValidDiagonal(a, b)) {
  58439. // split the polygon in two by the diagonal
  58440. var c = splitPolygon(a, b);
  58441. // filter colinear points around the cuts
  58442. a = filterPoints(a, a.next);
  58443. c = filterPoints(c, c.next);
  58444. // run earcut on each half
  58445. earcutLinked(a, triangles, dim, minX, minY, size, undefined);
  58446. earcutLinked(c, triangles, dim, minX, minY, size, undefined);
  58447. return;
  58448. }
  58449. b = b.next;
  58450. }
  58451. a = a.next;
  58452. } while (a !== start);
  58453. }
  58454. // link every hole into the outer loop, producing a single-ring polygon without holes
  58455. function eliminateHoles(data, holeIndices, outerNode, dim) {
  58456. var queue = [], i, len, start, end, list;
  58457. for (i = 0, len = holeIndices.length; i < len; i++) {
  58458. start = holeIndices[i] * dim;
  58459. end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58460. list = linkedList(data, start, end, dim, false);
  58461. if (list === list.next)
  58462. list.steiner = true;
  58463. queue.push(getLeftmost(list));
  58464. }
  58465. queue.sort(compareX);
  58466. // process holes from left to right
  58467. for (i = 0; i < queue.length; i++) {
  58468. eliminateHole(queue[i], outerNode);
  58469. outerNode = filterPoints(outerNode, outerNode.next);
  58470. }
  58471. return outerNode;
  58472. }
  58473. function compareX(a, b) {
  58474. return a.x - b.x;
  58475. }
  58476. // find a bridge between vertices that connects hole with an outer ring and and link it
  58477. function eliminateHole(hole, outerNode) {
  58478. outerNode = findHoleBridge(hole, outerNode);
  58479. if (outerNode) {
  58480. var b = splitPolygon(outerNode, hole);
  58481. filterPoints(b, b.next);
  58482. }
  58483. }
  58484. // David Eberly's algorithm for finding a bridge between hole and outer polygon
  58485. function findHoleBridge(hole, outerNode) {
  58486. var p = outerNode, hx = hole.x, hy = hole.y, qx = -Infinity, m;
  58487. // find a segment intersected by a ray from the hole's leftmost point to the left;
  58488. // segment's endpoint with lesser x will be potential connection point
  58489. do {
  58490. if (hy <= p.y && hy >= p.next.y) {
  58491. var x = p.x + (hy - p.y) * (p.next.x - p.x) / (p.next.y - p.y);
  58492. if (x <= hx && x > qx) {
  58493. qx = x;
  58494. if (x === hx) {
  58495. if (hy === p.y)
  58496. return p;
  58497. if (hy === p.next.y)
  58498. return p.next;
  58499. }
  58500. m = p.x < p.next.x ? p : p.next;
  58501. }
  58502. }
  58503. p = p.next;
  58504. } while (p !== outerNode);
  58505. if (!m)
  58506. return null;
  58507. if (hx === qx)
  58508. return m.prev; // hole touches outer segment; pick lower endpoint
  58509. // look for points inside the triangle of hole point, segment intersection and endpoint;
  58510. // if there are no points found, we have a valid connection;
  58511. // otherwise choose the point of the minimum angle with the ray as connection point
  58512. var stop = m, mx = m.x, my = m.y, tanMin = Infinity, tan;
  58513. p = m.next;
  58514. while (p !== stop) {
  58515. if (hx >= p.x &&
  58516. p.x >= mx &&
  58517. pointInTriangle(hy < my ? hx : qx, hy, mx, my, hy < my ? qx : hx, hy, p.x, p.y)) {
  58518. tan = Math.abs(hy - p.y) / (hx - p.x); // tangential
  58519. if ((tan < tanMin || (tan === tanMin && p.x > m.x)) && locallyInside(p, hole)) {
  58520. m = p;
  58521. tanMin = tan;
  58522. }
  58523. }
  58524. p = p.next;
  58525. }
  58526. return m;
  58527. }
  58528. // interlink polygon nodes in z-order
  58529. function indexCurve(start, minX, minY, size) {
  58530. var p = start;
  58531. do {
  58532. if (p.z === null)
  58533. p.z = zOrder(p.x, p.y, minX, minY, size);
  58534. p.prevZ = p.prev;
  58535. p.nextZ = p.next;
  58536. p = p.next;
  58537. } while (p !== start);
  58538. p.prevZ.nextZ = null;
  58539. p.prevZ = null;
  58540. sortLinked(p);
  58541. }
  58542. // Simon Tatham's linked list merge sort algorithm
  58543. // http://www.chiark.greenend.org.uk/~sgtatham/algorithms/listsort.html
  58544. function sortLinked(list) {
  58545. var i, p, q, e, tail, numMerges, pSize, qSize, inSize = 1;
  58546. do {
  58547. p = list;
  58548. list = null;
  58549. tail = null;
  58550. numMerges = 0;
  58551. while (p) {
  58552. numMerges++;
  58553. q = p;
  58554. pSize = 0;
  58555. for (i = 0; i < inSize; i++) {
  58556. pSize++;
  58557. q = q.nextZ;
  58558. if (!q)
  58559. break;
  58560. }
  58561. qSize = inSize;
  58562. while (pSize > 0 || (qSize > 0 && q)) {
  58563. if (pSize === 0) {
  58564. e = q;
  58565. q = q.nextZ;
  58566. qSize--;
  58567. }
  58568. else if (qSize === 0 || !q) {
  58569. e = p;
  58570. p = p.nextZ;
  58571. pSize--;
  58572. }
  58573. else if (p.z <= q.z) {
  58574. e = p;
  58575. p = p.nextZ;
  58576. pSize--;
  58577. }
  58578. else {
  58579. e = q;
  58580. q = q.nextZ;
  58581. qSize--;
  58582. }
  58583. if (tail)
  58584. tail.nextZ = e;
  58585. else
  58586. list = e;
  58587. e.prevZ = tail;
  58588. tail = e;
  58589. }
  58590. p = q;
  58591. }
  58592. tail.nextZ = null;
  58593. inSize *= 2;
  58594. } while (numMerges > 1);
  58595. return list;
  58596. }
  58597. // z-order of a point given coords and size of the data bounding box
  58598. function zOrder(x, y, minX, minY, size) {
  58599. // coords are transformed into non-negative 15-bit integer range
  58600. x = 32767 * (x - minX) / size;
  58601. y = 32767 * (y - minY) / size;
  58602. x = (x | (x << 8)) & 0x00FF00FF;
  58603. x = (x | (x << 4)) & 0x0F0F0F0F;
  58604. x = (x | (x << 2)) & 0x33333333;
  58605. x = (x | (x << 1)) & 0x55555555;
  58606. y = (y | (y << 8)) & 0x00FF00FF;
  58607. y = (y | (y << 4)) & 0x0F0F0F0F;
  58608. y = (y | (y << 2)) & 0x33333333;
  58609. y = (y | (y << 1)) & 0x55555555;
  58610. return x | (y << 1);
  58611. }
  58612. // find the leftmost node of a polygon ring
  58613. function getLeftmost(start) {
  58614. var p = start, leftmost = start;
  58615. do {
  58616. if (p.x < leftmost.x)
  58617. leftmost = p;
  58618. p = p.next;
  58619. } while (p !== start);
  58620. return leftmost;
  58621. }
  58622. // check if a point lies within a convex triangle
  58623. function pointInTriangle(ax, ay, bx, by, cx, cy, px, py) {
  58624. return (cx - px) * (ay - py) - (ax - px) * (cy - py) >= 0 &&
  58625. (ax - px) * (by - py) - (bx - px) * (ay - py) >= 0 &&
  58626. (bx - px) * (cy - py) - (cx - px) * (by - py) >= 0;
  58627. }
  58628. // check if a diagonal between two polygon nodes is valid (lies in polygon interior)
  58629. function isValidDiagonal(a, b) {
  58630. return a.next.i !== b.i &&
  58631. a.prev.i !== b.i &&
  58632. !intersectsPolygon(a, b) &&
  58633. locallyInside(a, b) &&
  58634. locallyInside(b, a) &&
  58635. middleInside(a, b);
  58636. }
  58637. // signed area of a triangle
  58638. function area(p, q, r) {
  58639. return (q.y - p.y) * (r.x - q.x) - (q.x - p.x) * (r.y - q.y);
  58640. }
  58641. // check if two points are equal
  58642. function equals(p1, p2) {
  58643. return p1.x === p2.x && p1.y === p2.y;
  58644. }
  58645. // check if two segments intersect
  58646. function intersects(p1, q1, p2, q2) {
  58647. if ((equals(p1, q1) && equals(p2, q2)) ||
  58648. (equals(p1, q2) && equals(p2, q1)))
  58649. return true;
  58650. return area(p1, q1, p2) > 0 !== area(p1, q1, q2) > 0 &&
  58651. area(p2, q2, p1) > 0 !== area(p2, q2, q1) > 0;
  58652. }
  58653. // check if a polygon diagonal intersects any polygon segments
  58654. function intersectsPolygon(a, b) {
  58655. var p = a;
  58656. do {
  58657. if (p.i !== a.i &&
  58658. p.next.i !== a.i &&
  58659. p.i !== b.i &&
  58660. p.next.i !== b.i &&
  58661. intersects(p, p.next, a, b))
  58662. return true;
  58663. p = p.next;
  58664. } while (p !== a);
  58665. return false;
  58666. }
  58667. // check if a polygon diagonal is locally inside the polygon
  58668. function locallyInside(a, b) {
  58669. return area(a.prev, a, a.next) < 0
  58670. ? area(a, b, a.next) >= 0 && area(a, a.prev, b) >= 0
  58671. : area(a, b, a.prev) < 0 || area(a, a.next, b) < 0;
  58672. }
  58673. // check if the middle point of a polygon diagonal is inside the polygon
  58674. function middleInside(a, b) {
  58675. var p = a, inside = false, px = (a.x + b.x) / 2, py = (a.y + b.y) / 2;
  58676. do {
  58677. if (((p.y > py) !== (p.next.y > py)) && (px < (p.next.x - p.x) * (py - p.y) / (p.next.y - p.y) + p.x))
  58678. inside = !inside;
  58679. p = p.next;
  58680. } while (p !== a);
  58681. return inside;
  58682. }
  58683. // link two polygon vertices with a bridge; if the vertices belong to the same ring, it splits polygon into two;
  58684. // if one belongs to the outer ring and another to a hole, it merges it into a single ring
  58685. function splitPolygon(a, b) {
  58686. 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;
  58687. a.next = b;
  58688. b.prev = a;
  58689. a2.next = an;
  58690. an.prev = a2;
  58691. b2.next = a2;
  58692. a2.prev = b2;
  58693. bp.next = b2;
  58694. b2.prev = bp;
  58695. return b2;
  58696. }
  58697. // create a node and optionally link it with previous one (in a circular doubly linked list)
  58698. function insertNode(i, x, y, last) {
  58699. var p = new Node(i, x, y);
  58700. if (!last) {
  58701. p.prev = p;
  58702. p.next = p;
  58703. }
  58704. else {
  58705. p.next = last.next;
  58706. p.prev = last;
  58707. last.next.prev = p;
  58708. last.next = p;
  58709. }
  58710. return p;
  58711. }
  58712. function removeNode(p) {
  58713. p.next.prev = p.prev;
  58714. p.prev.next = p.next;
  58715. if (p.prevZ)
  58716. p.prevZ.nextZ = p.nextZ;
  58717. if (p.nextZ)
  58718. p.nextZ.prevZ = p.prevZ;
  58719. }
  58720. function Node(i, x, y) {
  58721. // vertice index in coordinates array
  58722. this.i = i;
  58723. // vertex coordinates
  58724. this.x = x;
  58725. this.y = y;
  58726. // previous and next vertice nodes in a polygon ring
  58727. this.prev = null;
  58728. this.next = null;
  58729. // z-order curve value
  58730. this.z = null;
  58731. // previous and next nodes in z-order
  58732. this.prevZ = null;
  58733. this.nextZ = null;
  58734. // indicates whether this is a steiner point
  58735. this.steiner = false;
  58736. }
  58737. /**
  58738. * return a percentage difference between the polygon area and its triangulation area;
  58739. * used to verify correctness of triangulation
  58740. */
  58741. function deviation(data, holeIndices, dim, triangles) {
  58742. var hasHoles = holeIndices && holeIndices.length;
  58743. var outerLen = hasHoles ? holeIndices[0] * dim : data.length;
  58744. var polygonArea = Math.abs(signedArea(data, 0, outerLen, dim));
  58745. if (hasHoles) {
  58746. for (var i = 0, len = holeIndices.length; i < len; i++) {
  58747. var start = holeIndices[i] * dim;
  58748. var end = i < len - 1 ? holeIndices[i + 1] * dim : data.length;
  58749. polygonArea -= Math.abs(signedArea(data, start, end, dim));
  58750. }
  58751. }
  58752. var trianglesArea = 0;
  58753. for (i = 0; i < triangles.length; i += 3) {
  58754. var a = triangles[i] * dim;
  58755. var b = triangles[i + 1] * dim;
  58756. var c = triangles[i + 2] * dim;
  58757. trianglesArea += Math.abs((data[a] - data[c]) * (data[b + 1] - data[a + 1]) -
  58758. (data[a] - data[b]) * (data[c + 1] - data[a + 1]));
  58759. }
  58760. return polygonArea === 0 && trianglesArea === 0 ? 0 : Math.abs((trianglesArea - polygonArea) / polygonArea);
  58761. }
  58762. Earcut.deviation = deviation;
  58763. ;
  58764. function signedArea(data, start, end, dim) {
  58765. var sum = 0;
  58766. for (var i = start, j = end - dim; i < end; i += dim) {
  58767. sum += (data[j] - data[i]) * (data[i + 1] + data[j + 1]);
  58768. j = i;
  58769. }
  58770. return sum;
  58771. }
  58772. /**
  58773. * turn a polygon in a multi-dimensional array form (e.g. as in GeoJSON) into a form Earcut accepts
  58774. */
  58775. function flatten(data) {
  58776. var dim = data[0][0].length, result = { vertices: [], holes: [], dimensions: dim }, holeIndex = 0;
  58777. for (var i = 0; i < data.length; i++) {
  58778. for (var j = 0; j < data[i].length; j++) {
  58779. for (var d = 0; d < dim; d++)
  58780. result.vertices.push(data[i][j][d]);
  58781. }
  58782. if (i > 0) {
  58783. holeIndex += data[i - 1].length;
  58784. result.holes.push(holeIndex);
  58785. }
  58786. }
  58787. return result;
  58788. }
  58789. Earcut.flatten = flatten;
  58790. ;
  58791. })(Earcut || (Earcut = {}));
  58792. //# sourceMappingURL=babylon.earcut.js.map
  58793. /// <reference path="..\Math\babylon.math.ts" />
  58794. var BABYLON;
  58795. (function (BABYLON) {
  58796. var IndexedVector2 = (function (_super) {
  58797. __extends(IndexedVector2, _super);
  58798. function IndexedVector2(original, index) {
  58799. var _this = _super.call(this, original.x, original.y) || this;
  58800. _this.index = index;
  58801. return _this;
  58802. }
  58803. return IndexedVector2;
  58804. }(BABYLON.Vector2));
  58805. var PolygonPoints = (function () {
  58806. function PolygonPoints() {
  58807. this.elements = new Array();
  58808. }
  58809. PolygonPoints.prototype.add = function (originalPoints) {
  58810. var _this = this;
  58811. var result = new Array();
  58812. originalPoints.forEach(function (point) {
  58813. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  58814. var newPoint = new IndexedVector2(point, _this.elements.length);
  58815. result.push(newPoint);
  58816. _this.elements.push(newPoint);
  58817. }
  58818. });
  58819. return result;
  58820. };
  58821. PolygonPoints.prototype.computeBounds = function () {
  58822. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58823. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  58824. this.elements.forEach(function (point) {
  58825. // x
  58826. if (point.x < lmin.x) {
  58827. lmin.x = point.x;
  58828. }
  58829. else if (point.x > lmax.x) {
  58830. lmax.x = point.x;
  58831. }
  58832. // y
  58833. if (point.y < lmin.y) {
  58834. lmin.y = point.y;
  58835. }
  58836. else if (point.y > lmax.y) {
  58837. lmax.y = point.y;
  58838. }
  58839. });
  58840. return {
  58841. min: lmin,
  58842. max: lmax,
  58843. width: lmax.x - lmin.x,
  58844. height: lmax.y - lmin.y
  58845. };
  58846. };
  58847. return PolygonPoints;
  58848. }());
  58849. var Polygon = (function () {
  58850. function Polygon() {
  58851. }
  58852. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  58853. return [
  58854. new BABYLON.Vector2(xmin, ymin),
  58855. new BABYLON.Vector2(xmax, ymin),
  58856. new BABYLON.Vector2(xmax, ymax),
  58857. new BABYLON.Vector2(xmin, ymax)
  58858. ];
  58859. };
  58860. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  58861. if (cx === void 0) { cx = 0; }
  58862. if (cy === void 0) { cy = 0; }
  58863. if (numberOfSides === void 0) { numberOfSides = 32; }
  58864. var result = new Array();
  58865. var angle = 0;
  58866. var increment = (Math.PI * 2) / numberOfSides;
  58867. for (var i = 0; i < numberOfSides; i++) {
  58868. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  58869. angle -= increment;
  58870. }
  58871. return result;
  58872. };
  58873. Polygon.Parse = function (input) {
  58874. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  58875. var i, result = [];
  58876. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  58877. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  58878. }
  58879. return result;
  58880. };
  58881. Polygon.StartingAt = function (x, y) {
  58882. return BABYLON.Path2.StartingAt(x, y);
  58883. };
  58884. return Polygon;
  58885. }());
  58886. BABYLON.Polygon = Polygon;
  58887. var PolygonMeshBuilder = (function () {
  58888. function PolygonMeshBuilder(name, contours, scene) {
  58889. this._points = new PolygonPoints();
  58890. this._outlinepoints = new PolygonPoints();
  58891. this._holes = [];
  58892. this._epoints = new Array();
  58893. this._eholes = new Array();
  58894. this._name = name;
  58895. this._scene = scene;
  58896. var points;
  58897. if (contours instanceof BABYLON.Path2) {
  58898. points = contours.getPoints();
  58899. }
  58900. else {
  58901. points = contours;
  58902. }
  58903. this._addToepoint(points);
  58904. this._points.add(points);
  58905. this._outlinepoints.add(points);
  58906. }
  58907. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  58908. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  58909. var p = points_1[_i];
  58910. this._epoints.push(p.x, p.y);
  58911. }
  58912. };
  58913. PolygonMeshBuilder.prototype.addHole = function (hole) {
  58914. this._points.add(hole);
  58915. var holepoints = new PolygonPoints();
  58916. holepoints.add(hole);
  58917. this._holes.push(holepoints);
  58918. this._eholes.push(this._epoints.length / 2);
  58919. this._addToepoint(hole);
  58920. return this;
  58921. };
  58922. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  58923. var _this = this;
  58924. if (updatable === void 0) { updatable = false; }
  58925. var result = new BABYLON.Mesh(this._name, this._scene);
  58926. var normals = [];
  58927. var positions = [];
  58928. var uvs = [];
  58929. var bounds = this._points.computeBounds();
  58930. this._points.elements.forEach(function (p) {
  58931. normals.push(0, 1.0, 0);
  58932. positions.push(p.x, 0, p.y);
  58933. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  58934. });
  58935. var indices = [];
  58936. var res = Earcut.earcut(this._epoints, this._eholes, 2);
  58937. for (var i = 0; i < res.length; i++) {
  58938. indices.push(res[i]);
  58939. }
  58940. if (depth > 0) {
  58941. var positionscount = (positions.length / 3); //get the current pointcount
  58942. this._points.elements.forEach(function (p) {
  58943. normals.push(0, -1.0, 0);
  58944. positions.push(p.x, -depth, p.y);
  58945. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  58946. });
  58947. var totalCount = indices.length;
  58948. for (var i = 0; i < totalCount; i += 3) {
  58949. var i0 = indices[i + 0];
  58950. var i1 = indices[i + 1];
  58951. var i2 = indices[i + 2];
  58952. indices.push(i2 + positionscount);
  58953. indices.push(i1 + positionscount);
  58954. indices.push(i0 + positionscount);
  58955. }
  58956. //Add the sides
  58957. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  58958. this._holes.forEach(function (hole) {
  58959. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  58960. });
  58961. }
  58962. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  58963. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  58964. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  58965. result.setIndices(indices);
  58966. return result;
  58967. };
  58968. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  58969. var StartIndex = positions.length / 3;
  58970. var ulength = 0;
  58971. for (var i = 0; i < points.elements.length; i++) {
  58972. var p = points.elements[i];
  58973. var p1;
  58974. if ((i + 1) > points.elements.length - 1) {
  58975. p1 = points.elements[0];
  58976. }
  58977. else {
  58978. p1 = points.elements[i + 1];
  58979. }
  58980. positions.push(p.x, 0, p.y);
  58981. positions.push(p.x, -depth, p.y);
  58982. positions.push(p1.x, 0, p1.y);
  58983. positions.push(p1.x, -depth, p1.y);
  58984. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  58985. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  58986. var v3 = v2.subtract(v1);
  58987. var v4 = new BABYLON.Vector3(0, 1, 0);
  58988. var vn = BABYLON.Vector3.Cross(v3, v4);
  58989. vn = vn.normalize();
  58990. uvs.push(ulength / bounds.width, 0);
  58991. uvs.push(ulength / bounds.width, 1);
  58992. ulength += v3.length();
  58993. uvs.push((ulength / bounds.width), 0);
  58994. uvs.push((ulength / bounds.width), 1);
  58995. if (!flip) {
  58996. normals.push(-vn.x, -vn.y, -vn.z);
  58997. normals.push(-vn.x, -vn.y, -vn.z);
  58998. normals.push(-vn.x, -vn.y, -vn.z);
  58999. normals.push(-vn.x, -vn.y, -vn.z);
  59000. indices.push(StartIndex);
  59001. indices.push(StartIndex + 1);
  59002. indices.push(StartIndex + 2);
  59003. indices.push(StartIndex + 1);
  59004. indices.push(StartIndex + 3);
  59005. indices.push(StartIndex + 2);
  59006. }
  59007. else {
  59008. normals.push(vn.x, vn.y, vn.z);
  59009. normals.push(vn.x, vn.y, vn.z);
  59010. normals.push(vn.x, vn.y, vn.z);
  59011. normals.push(vn.x, vn.y, vn.z);
  59012. indices.push(StartIndex);
  59013. indices.push(StartIndex + 2);
  59014. indices.push(StartIndex + 1);
  59015. indices.push(StartIndex + 1);
  59016. indices.push(StartIndex + 2);
  59017. indices.push(StartIndex + 3);
  59018. }
  59019. StartIndex += 4;
  59020. }
  59021. ;
  59022. };
  59023. return PolygonMeshBuilder;
  59024. }());
  59025. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  59026. })(BABYLON || (BABYLON = {}));
  59027. //# sourceMappingURL=babylon.polygonMesh.js.map
  59028. var BABYLON;
  59029. (function (BABYLON) {
  59030. // Unique ID when we import meshes from Babylon to CSG
  59031. var currentCSGMeshId = 0;
  59032. // # class Vertex
  59033. // Represents a vertex of a polygon. Use your own vertex class instead of this
  59034. // one to provide additional features like texture coordinates and vertex
  59035. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  59036. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  59037. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  59038. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  59039. // is not used anywhere else.
  59040. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  59041. var Vertex = (function () {
  59042. function Vertex(pos, normal, uv) {
  59043. this.pos = pos;
  59044. this.normal = normal;
  59045. this.uv = uv;
  59046. }
  59047. Vertex.prototype.clone = function () {
  59048. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  59049. };
  59050. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  59051. // orientation of a polygon is flipped.
  59052. Vertex.prototype.flip = function () {
  59053. this.normal = this.normal.scale(-1);
  59054. };
  59055. // Create a new vertex between this vertex and `other` by linearly
  59056. // interpolating all properties using a parameter of `t`. Subclasses should
  59057. // override this to interpolate additional properties.
  59058. Vertex.prototype.interpolate = function (other, t) {
  59059. 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));
  59060. };
  59061. return Vertex;
  59062. }());
  59063. // # class Plane
  59064. // Represents a plane in 3D space.
  59065. var Plane = (function () {
  59066. function Plane(normal, w) {
  59067. this.normal = normal;
  59068. this.w = w;
  59069. }
  59070. Plane.FromPoints = function (a, b, c) {
  59071. var v0 = c.subtract(a);
  59072. var v1 = b.subtract(a);
  59073. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  59074. return null;
  59075. }
  59076. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  59077. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  59078. };
  59079. Plane.prototype.clone = function () {
  59080. return new Plane(this.normal.clone(), this.w);
  59081. };
  59082. Plane.prototype.flip = function () {
  59083. this.normal.scaleInPlace(-1);
  59084. this.w = -this.w;
  59085. };
  59086. // Split `polygon` by this plane if needed, then put the polygon or polygon
  59087. // fragments in the appropriate lists. Coplanar polygons go into either
  59088. // `coplanarFront` or `coplanarBack` depending on their orientation with
  59089. // respect to this plane. Polygons in front or in back of this plane go into
  59090. // either `front` or `back`.
  59091. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  59092. var COPLANAR = 0;
  59093. var FRONT = 1;
  59094. var BACK = 2;
  59095. var SPANNING = 3;
  59096. // Classify each point as well as the entire polygon into one of the above
  59097. // four classes.
  59098. var polygonType = 0;
  59099. var types = [];
  59100. var i;
  59101. var t;
  59102. for (i = 0; i < polygon.vertices.length; i++) {
  59103. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  59104. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  59105. polygonType |= type;
  59106. types.push(type);
  59107. }
  59108. // Put the polygon in the correct list, splitting it when necessary.
  59109. switch (polygonType) {
  59110. case COPLANAR:
  59111. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  59112. break;
  59113. case FRONT:
  59114. front.push(polygon);
  59115. break;
  59116. case BACK:
  59117. back.push(polygon);
  59118. break;
  59119. case SPANNING:
  59120. var f = [], b = [];
  59121. for (i = 0; i < polygon.vertices.length; i++) {
  59122. var j = (i + 1) % polygon.vertices.length;
  59123. var ti = types[i], tj = types[j];
  59124. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  59125. if (ti !== BACK)
  59126. f.push(vi);
  59127. if (ti !== FRONT)
  59128. b.push(ti !== BACK ? vi.clone() : vi);
  59129. if ((ti | tj) === SPANNING) {
  59130. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  59131. var v = vi.interpolate(vj, t);
  59132. f.push(v);
  59133. b.push(v.clone());
  59134. }
  59135. }
  59136. var poly;
  59137. if (f.length >= 3) {
  59138. poly = new Polygon(f, polygon.shared);
  59139. if (poly.plane)
  59140. front.push(poly);
  59141. }
  59142. if (b.length >= 3) {
  59143. poly = new Polygon(b, polygon.shared);
  59144. if (poly.plane)
  59145. back.push(poly);
  59146. }
  59147. break;
  59148. }
  59149. };
  59150. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  59151. // point is on the plane.
  59152. Plane.EPSILON = 1e-5;
  59153. return Plane;
  59154. }());
  59155. // # class Polygon
  59156. // Represents a convex polygon. The vertices used to initialize a polygon must
  59157. // be coplanar and form a convex loop.
  59158. //
  59159. // Each convex polygon has a `shared` property, which is shared between all
  59160. // polygons that are clones of each other or were split from the same polygon.
  59161. // This can be used to define per-polygon properties (such as surface color).
  59162. var Polygon = (function () {
  59163. function Polygon(vertices, shared) {
  59164. this.vertices = vertices;
  59165. this.shared = shared;
  59166. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  59167. }
  59168. Polygon.prototype.clone = function () {
  59169. var vertices = this.vertices.map(function (v) { return v.clone(); });
  59170. return new Polygon(vertices, this.shared);
  59171. };
  59172. Polygon.prototype.flip = function () {
  59173. this.vertices.reverse().map(function (v) { v.flip(); });
  59174. this.plane.flip();
  59175. };
  59176. return Polygon;
  59177. }());
  59178. // # class Node
  59179. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  59180. // by picking a polygon to split along. That polygon (and all other coplanar
  59181. // polygons) are added directly to that node and the other polygons are added to
  59182. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  59183. // no distinction between internal and leaf nodes.
  59184. var Node = (function () {
  59185. function Node(polygons) {
  59186. this.plane = null;
  59187. this.front = null;
  59188. this.back = null;
  59189. this.polygons = [];
  59190. if (polygons) {
  59191. this.build(polygons);
  59192. }
  59193. }
  59194. Node.prototype.clone = function () {
  59195. var node = new Node();
  59196. node.plane = this.plane && this.plane.clone();
  59197. node.front = this.front && this.front.clone();
  59198. node.back = this.back && this.back.clone();
  59199. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  59200. return node;
  59201. };
  59202. // Convert solid space to empty space and empty space to solid space.
  59203. Node.prototype.invert = function () {
  59204. for (var i = 0; i < this.polygons.length; i++) {
  59205. this.polygons[i].flip();
  59206. }
  59207. if (this.plane) {
  59208. this.plane.flip();
  59209. }
  59210. if (this.front) {
  59211. this.front.invert();
  59212. }
  59213. if (this.back) {
  59214. this.back.invert();
  59215. }
  59216. var temp = this.front;
  59217. this.front = this.back;
  59218. this.back = temp;
  59219. };
  59220. // Recursively remove all polygons in `polygons` that are inside this BSP
  59221. // tree.
  59222. Node.prototype.clipPolygons = function (polygons) {
  59223. if (!this.plane)
  59224. return polygons.slice();
  59225. var front = [], back = [];
  59226. for (var i = 0; i < polygons.length; i++) {
  59227. this.plane.splitPolygon(polygons[i], front, back, front, back);
  59228. }
  59229. if (this.front) {
  59230. front = this.front.clipPolygons(front);
  59231. }
  59232. if (this.back) {
  59233. back = this.back.clipPolygons(back);
  59234. }
  59235. else {
  59236. back = [];
  59237. }
  59238. return front.concat(back);
  59239. };
  59240. // Remove all polygons in this BSP tree that are inside the other BSP tree
  59241. // `bsp`.
  59242. Node.prototype.clipTo = function (bsp) {
  59243. this.polygons = bsp.clipPolygons(this.polygons);
  59244. if (this.front)
  59245. this.front.clipTo(bsp);
  59246. if (this.back)
  59247. this.back.clipTo(bsp);
  59248. };
  59249. // Return a list of all polygons in this BSP tree.
  59250. Node.prototype.allPolygons = function () {
  59251. var polygons = this.polygons.slice();
  59252. if (this.front)
  59253. polygons = polygons.concat(this.front.allPolygons());
  59254. if (this.back)
  59255. polygons = polygons.concat(this.back.allPolygons());
  59256. return polygons;
  59257. };
  59258. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  59259. // new polygons are filtered down to the bottom of the tree and become new
  59260. // nodes there. Each set of polygons is partitioned using the first polygon
  59261. // (no heuristic is used to pick a good split).
  59262. Node.prototype.build = function (polygons) {
  59263. if (!polygons.length)
  59264. return;
  59265. if (!this.plane)
  59266. this.plane = polygons[0].plane.clone();
  59267. var front = [], back = [];
  59268. for (var i = 0; i < polygons.length; i++) {
  59269. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  59270. }
  59271. if (front.length) {
  59272. if (!this.front)
  59273. this.front = new Node();
  59274. this.front.build(front);
  59275. }
  59276. if (back.length) {
  59277. if (!this.back)
  59278. this.back = new Node();
  59279. this.back.build(back);
  59280. }
  59281. };
  59282. return Node;
  59283. }());
  59284. var CSG = (function () {
  59285. function CSG() {
  59286. this.polygons = new Array();
  59287. }
  59288. // Convert BABYLON.Mesh to BABYLON.CSG
  59289. CSG.FromMesh = function (mesh) {
  59290. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  59291. var matrix, meshPosition, meshRotation, meshRotationQuaternion, meshScaling;
  59292. if (mesh instanceof BABYLON.Mesh) {
  59293. mesh.computeWorldMatrix(true);
  59294. matrix = mesh.getWorldMatrix();
  59295. meshPosition = mesh.position.clone();
  59296. meshRotation = mesh.rotation.clone();
  59297. if (mesh.rotationQuaternion) {
  59298. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  59299. }
  59300. meshScaling = mesh.scaling.clone();
  59301. }
  59302. else {
  59303. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  59304. }
  59305. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  59306. var subMeshes = mesh.subMeshes;
  59307. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  59308. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  59309. vertices = [];
  59310. for (var j = 0; j < 3; j++) {
  59311. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  59312. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  59313. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  59314. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  59315. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  59316. vertex = new Vertex(position, normal, uv);
  59317. vertices.push(vertex);
  59318. }
  59319. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  59320. // To handle the case of degenerated triangle
  59321. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  59322. if (polygon.plane)
  59323. polygons.push(polygon);
  59324. }
  59325. }
  59326. var csg = CSG.FromPolygons(polygons);
  59327. csg.matrix = matrix;
  59328. csg.position = meshPosition;
  59329. csg.rotation = meshRotation;
  59330. csg.scaling = meshScaling;
  59331. csg.rotationQuaternion = meshRotationQuaternion;
  59332. currentCSGMeshId++;
  59333. return csg;
  59334. };
  59335. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  59336. CSG.FromPolygons = function (polygons) {
  59337. var csg = new CSG();
  59338. csg.polygons = polygons;
  59339. return csg;
  59340. };
  59341. CSG.prototype.clone = function () {
  59342. var csg = new CSG();
  59343. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  59344. csg.copyTransformAttributes(this);
  59345. return csg;
  59346. };
  59347. CSG.prototype.toPolygons = function () {
  59348. return this.polygons;
  59349. };
  59350. CSG.prototype.union = function (csg) {
  59351. var a = new Node(this.clone().polygons);
  59352. var b = new Node(csg.clone().polygons);
  59353. a.clipTo(b);
  59354. b.clipTo(a);
  59355. b.invert();
  59356. b.clipTo(a);
  59357. b.invert();
  59358. a.build(b.allPolygons());
  59359. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59360. };
  59361. CSG.prototype.unionInPlace = function (csg) {
  59362. var a = new Node(this.polygons);
  59363. var b = new Node(csg.polygons);
  59364. a.clipTo(b);
  59365. b.clipTo(a);
  59366. b.invert();
  59367. b.clipTo(a);
  59368. b.invert();
  59369. a.build(b.allPolygons());
  59370. this.polygons = a.allPolygons();
  59371. };
  59372. CSG.prototype.subtract = function (csg) {
  59373. var a = new Node(this.clone().polygons);
  59374. var b = new Node(csg.clone().polygons);
  59375. a.invert();
  59376. a.clipTo(b);
  59377. b.clipTo(a);
  59378. b.invert();
  59379. b.clipTo(a);
  59380. b.invert();
  59381. a.build(b.allPolygons());
  59382. a.invert();
  59383. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59384. };
  59385. CSG.prototype.subtractInPlace = function (csg) {
  59386. var a = new Node(this.polygons);
  59387. var b = new Node(csg.polygons);
  59388. a.invert();
  59389. a.clipTo(b);
  59390. b.clipTo(a);
  59391. b.invert();
  59392. b.clipTo(a);
  59393. b.invert();
  59394. a.build(b.allPolygons());
  59395. a.invert();
  59396. this.polygons = a.allPolygons();
  59397. };
  59398. CSG.prototype.intersect = function (csg) {
  59399. var a = new Node(this.clone().polygons);
  59400. var b = new Node(csg.clone().polygons);
  59401. a.invert();
  59402. b.clipTo(a);
  59403. b.invert();
  59404. a.clipTo(b);
  59405. b.clipTo(a);
  59406. a.build(b.allPolygons());
  59407. a.invert();
  59408. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  59409. };
  59410. CSG.prototype.intersectInPlace = function (csg) {
  59411. var a = new Node(this.polygons);
  59412. var b = new Node(csg.polygons);
  59413. a.invert();
  59414. b.clipTo(a);
  59415. b.invert();
  59416. a.clipTo(b);
  59417. b.clipTo(a);
  59418. a.build(b.allPolygons());
  59419. a.invert();
  59420. this.polygons = a.allPolygons();
  59421. };
  59422. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  59423. // not modified.
  59424. CSG.prototype.inverse = function () {
  59425. var csg = this.clone();
  59426. csg.inverseInPlace();
  59427. return csg;
  59428. };
  59429. CSG.prototype.inverseInPlace = function () {
  59430. this.polygons.map(function (p) { p.flip(); });
  59431. };
  59432. // This is used to keep meshes transformations so they can be restored
  59433. // when we build back a Babylon Mesh
  59434. // NB : All CSG operations are performed in world coordinates
  59435. CSG.prototype.copyTransformAttributes = function (csg) {
  59436. this.matrix = csg.matrix;
  59437. this.position = csg.position;
  59438. this.rotation = csg.rotation;
  59439. this.scaling = csg.scaling;
  59440. this.rotationQuaternion = csg.rotationQuaternion;
  59441. return this;
  59442. };
  59443. // Build Raw mesh from CSG
  59444. // Coordinates here are in world space
  59445. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  59446. var matrix = this.matrix.clone();
  59447. matrix.invert();
  59448. 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;
  59449. if (keepSubMeshes) {
  59450. // Sort Polygons, since subMeshes are indices range
  59451. polygons.sort(function (a, b) {
  59452. if (a.shared.meshId === b.shared.meshId) {
  59453. return a.shared.subMeshId - b.shared.subMeshId;
  59454. }
  59455. else {
  59456. return a.shared.meshId - b.shared.meshId;
  59457. }
  59458. });
  59459. }
  59460. for (var i = 0, il = polygons.length; i < il; i++) {
  59461. polygon = polygons[i];
  59462. // Building SubMeshes
  59463. if (!subMesh_dict[polygon.shared.meshId]) {
  59464. subMesh_dict[polygon.shared.meshId] = {};
  59465. }
  59466. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  59467. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  59468. indexStart: +Infinity,
  59469. indexEnd: -Infinity,
  59470. materialIndex: polygon.shared.materialIndex
  59471. };
  59472. }
  59473. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  59474. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  59475. polygonIndices[0] = 0;
  59476. polygonIndices[1] = j - 1;
  59477. polygonIndices[2] = j;
  59478. for (var k = 0; k < 3; k++) {
  59479. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  59480. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  59481. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  59482. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  59483. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  59484. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  59485. // Check if 2 points can be merged
  59486. if (!(typeof vertex_idx !== 'undefined' &&
  59487. normals[vertex_idx * 3] === localNormal.x &&
  59488. normals[vertex_idx * 3 + 1] === localNormal.y &&
  59489. normals[vertex_idx * 3 + 2] === localNormal.z &&
  59490. uvs[vertex_idx * 2] === uv.x &&
  59491. uvs[vertex_idx * 2 + 1] === uv.y)) {
  59492. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  59493. uvs.push(uv.x, uv.y);
  59494. normals.push(normal.x, normal.y, normal.z);
  59495. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  59496. }
  59497. indices.push(vertex_idx);
  59498. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  59499. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  59500. currentIndex++;
  59501. }
  59502. }
  59503. }
  59504. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  59505. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  59506. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  59507. mesh.setIndices(indices);
  59508. if (keepSubMeshes) {
  59509. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  59510. var materialIndexOffset = 0, materialMaxIndex;
  59511. mesh.subMeshes = new Array();
  59512. for (var m in subMesh_dict) {
  59513. materialMaxIndex = -1;
  59514. for (var sm in subMesh_dict[m]) {
  59515. subMesh_obj = subMesh_dict[m][sm];
  59516. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  59517. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  59518. }
  59519. materialIndexOffset += ++materialMaxIndex;
  59520. }
  59521. }
  59522. return mesh;
  59523. };
  59524. // Build Mesh from CSG taking material and transforms into account
  59525. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  59526. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  59527. mesh.material = material;
  59528. mesh.position.copyFrom(this.position);
  59529. mesh.rotation.copyFrom(this.rotation);
  59530. if (this.rotationQuaternion) {
  59531. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  59532. }
  59533. mesh.scaling.copyFrom(this.scaling);
  59534. mesh.computeWorldMatrix(true);
  59535. return mesh;
  59536. };
  59537. return CSG;
  59538. }());
  59539. BABYLON.CSG = CSG;
  59540. })(BABYLON || (BABYLON = {}));
  59541. //# sourceMappingURL=babylon.csg.js.map
  59542. var BABYLON;
  59543. (function (BABYLON) {
  59544. var LensFlare = (function () {
  59545. function LensFlare(size, position, color, imgUrl, system) {
  59546. this.size = size;
  59547. this.position = position;
  59548. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  59549. this.dispose = function () {
  59550. if (this.texture) {
  59551. this.texture.dispose();
  59552. }
  59553. // Remove from scene
  59554. var index = this._system.lensFlares.indexOf(this);
  59555. this._system.lensFlares.splice(index, 1);
  59556. };
  59557. this.color = color || new BABYLON.Color3(1, 1, 1);
  59558. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  59559. this._system = system;
  59560. system.lensFlares.push(this);
  59561. }
  59562. return LensFlare;
  59563. }());
  59564. BABYLON.LensFlare = LensFlare;
  59565. })(BABYLON || (BABYLON = {}));
  59566. //# sourceMappingURL=babylon.lensFlare.js.map
  59567. var BABYLON;
  59568. (function (BABYLON) {
  59569. var LensFlareSystem = (function () {
  59570. function LensFlareSystem(name, emitter, scene) {
  59571. this.name = name;
  59572. this.lensFlares = new Array();
  59573. this.borderLimit = 300;
  59574. this.viewportBorder = 0;
  59575. this.layerMask = 0x0FFFFFFF;
  59576. this._vertexBuffers = {};
  59577. this._isEnabled = true;
  59578. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  59579. this._emitter = emitter;
  59580. this.id = name;
  59581. scene.lensFlareSystems.push(this);
  59582. this.meshesSelectionPredicate = function (m) { return m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0); };
  59583. var engine = scene.getEngine();
  59584. // VBO
  59585. var vertices = [];
  59586. vertices.push(1, 1);
  59587. vertices.push(-1, 1);
  59588. vertices.push(-1, -1);
  59589. vertices.push(1, -1);
  59590. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  59591. // Indices
  59592. var indices = [];
  59593. indices.push(0);
  59594. indices.push(1);
  59595. indices.push(2);
  59596. indices.push(0);
  59597. indices.push(2);
  59598. indices.push(3);
  59599. this._indexBuffer = engine.createIndexBuffer(indices);
  59600. // Effects
  59601. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  59602. }
  59603. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  59604. get: function () {
  59605. return this._isEnabled;
  59606. },
  59607. set: function (value) {
  59608. this._isEnabled = value;
  59609. },
  59610. enumerable: true,
  59611. configurable: true
  59612. });
  59613. LensFlareSystem.prototype.getScene = function () {
  59614. return this._scene;
  59615. };
  59616. LensFlareSystem.prototype.getEmitter = function () {
  59617. return this._emitter;
  59618. };
  59619. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  59620. this._emitter = newEmitter;
  59621. };
  59622. LensFlareSystem.prototype.getEmitterPosition = function () {
  59623. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  59624. };
  59625. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  59626. var position = this.getEmitterPosition();
  59627. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  59628. this._positionX = position.x;
  59629. this._positionY = position.y;
  59630. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  59631. if (this.viewportBorder > 0) {
  59632. globalViewport.x -= this.viewportBorder;
  59633. globalViewport.y -= this.viewportBorder;
  59634. globalViewport.width += this.viewportBorder * 2;
  59635. globalViewport.height += this.viewportBorder * 2;
  59636. position.x += this.viewportBorder;
  59637. position.y += this.viewportBorder;
  59638. this._positionX += this.viewportBorder;
  59639. this._positionY += this.viewportBorder;
  59640. }
  59641. if (position.z > 0) {
  59642. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  59643. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  59644. return true;
  59645. }
  59646. return true;
  59647. }
  59648. return false;
  59649. };
  59650. LensFlareSystem.prototype._isVisible = function () {
  59651. if (!this._isEnabled) {
  59652. return false;
  59653. }
  59654. var emitterPosition = this.getEmitterPosition();
  59655. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  59656. var distance = direction.length();
  59657. direction.normalize();
  59658. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  59659. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  59660. return !pickInfo.hit || pickInfo.distance > distance;
  59661. };
  59662. LensFlareSystem.prototype.render = function () {
  59663. if (!this._effect.isReady())
  59664. return false;
  59665. var engine = this._scene.getEngine();
  59666. var viewport = this._scene.activeCamera.viewport;
  59667. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  59668. // Position
  59669. if (!this.computeEffectivePosition(globalViewport)) {
  59670. return false;
  59671. }
  59672. // Visibility
  59673. if (!this._isVisible()) {
  59674. return false;
  59675. }
  59676. // Intensity
  59677. var awayX;
  59678. var awayY;
  59679. if (this._positionX < this.borderLimit + globalViewport.x) {
  59680. awayX = this.borderLimit + globalViewport.x - this._positionX;
  59681. }
  59682. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  59683. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  59684. }
  59685. else {
  59686. awayX = 0;
  59687. }
  59688. if (this._positionY < this.borderLimit + globalViewport.y) {
  59689. awayY = this.borderLimit + globalViewport.y - this._positionY;
  59690. }
  59691. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  59692. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  59693. }
  59694. else {
  59695. awayY = 0;
  59696. }
  59697. var away = (awayX > awayY) ? awayX : awayY;
  59698. away -= this.viewportBorder;
  59699. if (away > this.borderLimit) {
  59700. away = this.borderLimit;
  59701. }
  59702. var intensity = 1.0 - (away / this.borderLimit);
  59703. if (intensity < 0) {
  59704. return false;
  59705. }
  59706. if (intensity > 1.0) {
  59707. intensity = 1.0;
  59708. }
  59709. if (this.viewportBorder > 0) {
  59710. globalViewport.x += this.viewportBorder;
  59711. globalViewport.y += this.viewportBorder;
  59712. globalViewport.width -= this.viewportBorder * 2;
  59713. globalViewport.height -= this.viewportBorder * 2;
  59714. this._positionX -= this.viewportBorder;
  59715. this._positionY -= this.viewportBorder;
  59716. }
  59717. // Position
  59718. var centerX = globalViewport.x + globalViewport.width / 2;
  59719. var centerY = globalViewport.y + globalViewport.height / 2;
  59720. var distX = centerX - this._positionX;
  59721. var distY = centerY - this._positionY;
  59722. // Effects
  59723. engine.enableEffect(this._effect);
  59724. engine.setState(false);
  59725. engine.setDepthBuffer(false);
  59726. // VBOs
  59727. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  59728. // Flares
  59729. for (var index = 0; index < this.lensFlares.length; index++) {
  59730. var flare = this.lensFlares[index];
  59731. engine.setAlphaMode(flare.alphaMode);
  59732. var x = centerX - (distX * flare.position);
  59733. var y = centerY - (distY * flare.position);
  59734. var cw = flare.size;
  59735. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  59736. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  59737. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  59738. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  59739. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  59740. // Texture
  59741. this._effect.setTexture("textureSampler", flare.texture);
  59742. // Color
  59743. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  59744. // Draw order
  59745. engine.draw(true, 0, 6);
  59746. }
  59747. engine.setDepthBuffer(true);
  59748. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  59749. return true;
  59750. };
  59751. LensFlareSystem.prototype.dispose = function () {
  59752. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  59753. if (vertexBuffer) {
  59754. vertexBuffer.dispose();
  59755. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  59756. }
  59757. if (this._indexBuffer) {
  59758. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  59759. this._indexBuffer = null;
  59760. }
  59761. while (this.lensFlares.length) {
  59762. this.lensFlares[0].dispose();
  59763. }
  59764. // Remove from scene
  59765. var index = this._scene.lensFlareSystems.indexOf(this);
  59766. this._scene.lensFlareSystems.splice(index, 1);
  59767. };
  59768. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  59769. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  59770. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  59771. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  59772. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  59773. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  59774. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  59775. var parsedFlare = parsedLensFlareSystem.flares[index];
  59776. var flare = new BABYLON.LensFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  59777. }
  59778. return lensFlareSystem;
  59779. };
  59780. LensFlareSystem.prototype.serialize = function () {
  59781. var serializationObject = {};
  59782. serializationObject.id = this.id;
  59783. serializationObject.name = this.name;
  59784. serializationObject.emitterId = this.getEmitter().id;
  59785. serializationObject.borderLimit = this.borderLimit;
  59786. serializationObject.flares = [];
  59787. for (var index = 0; index < this.lensFlares.length; index++) {
  59788. var flare = this.lensFlares[index];
  59789. serializationObject.flares.push({
  59790. size: flare.size,
  59791. position: flare.position,
  59792. color: flare.color.asArray(),
  59793. textureName: BABYLON.Tools.GetFilename(flare.texture.name)
  59794. });
  59795. }
  59796. return serializationObject;
  59797. };
  59798. return LensFlareSystem;
  59799. }());
  59800. BABYLON.LensFlareSystem = LensFlareSystem;
  59801. })(BABYLON || (BABYLON = {}));
  59802. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  59803. var BABYLON;
  59804. (function (BABYLON) {
  59805. /**
  59806. * This is a holder class for the physics joint created by the physics plugin.
  59807. * It holds a set of functions to control the underlying joint.
  59808. */
  59809. var PhysicsJoint = (function () {
  59810. function PhysicsJoint(type, jointData) {
  59811. this.type = type;
  59812. this.jointData = jointData;
  59813. jointData.nativeParams = jointData.nativeParams || {};
  59814. }
  59815. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  59816. get: function () {
  59817. return this._physicsJoint;
  59818. },
  59819. set: function (newJoint) {
  59820. if (this._physicsJoint) {
  59821. //remove from the wolrd
  59822. }
  59823. this._physicsJoint = newJoint;
  59824. },
  59825. enumerable: true,
  59826. configurable: true
  59827. });
  59828. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  59829. set: function (physicsPlugin) {
  59830. this._physicsPlugin = physicsPlugin;
  59831. },
  59832. enumerable: true,
  59833. configurable: true
  59834. });
  59835. /**
  59836. * Execute a function that is physics-plugin specific.
  59837. * @param {Function} func the function that will be executed.
  59838. * It accepts two parameters: the physics world and the physics joint.
  59839. */
  59840. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  59841. func(this._physicsPlugin.world, this._physicsJoint);
  59842. };
  59843. //TODO check if the native joints are the same
  59844. //Joint Types
  59845. PhysicsJoint.DistanceJoint = 0;
  59846. PhysicsJoint.HingeJoint = 1;
  59847. PhysicsJoint.BallAndSocketJoint = 2;
  59848. PhysicsJoint.WheelJoint = 3;
  59849. PhysicsJoint.SliderJoint = 4;
  59850. //OIMO
  59851. PhysicsJoint.PrismaticJoint = 5;
  59852. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  59853. PhysicsJoint.UniversalJoint = 6;
  59854. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  59855. //Cannon
  59856. //Similar to a Ball-Joint. Different in params
  59857. PhysicsJoint.PointToPointJoint = 8;
  59858. //Cannon only at the moment
  59859. PhysicsJoint.SpringJoint = 9;
  59860. PhysicsJoint.LockJoint = 10;
  59861. return PhysicsJoint;
  59862. }());
  59863. BABYLON.PhysicsJoint = PhysicsJoint;
  59864. /**
  59865. * A class representing a physics distance joint.
  59866. */
  59867. var DistanceJoint = (function (_super) {
  59868. __extends(DistanceJoint, _super);
  59869. function DistanceJoint(jointData) {
  59870. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  59871. }
  59872. /**
  59873. * Update the predefined distance.
  59874. */
  59875. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  59876. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  59877. };
  59878. return DistanceJoint;
  59879. }(PhysicsJoint));
  59880. BABYLON.DistanceJoint = DistanceJoint;
  59881. var MotorEnabledJoint = (function (_super) {
  59882. __extends(MotorEnabledJoint, _super);
  59883. function MotorEnabledJoint(type, jointData) {
  59884. return _super.call(this, type, jointData) || this;
  59885. }
  59886. /**
  59887. * Set the motor values.
  59888. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59889. * @param {number} force the force to apply
  59890. * @param {number} maxForce max force for this motor.
  59891. */
  59892. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  59893. this._physicsPlugin.setMotor(this, force, maxForce);
  59894. };
  59895. /**
  59896. * Set the motor's limits.
  59897. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59898. */
  59899. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59900. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59901. };
  59902. return MotorEnabledJoint;
  59903. }(PhysicsJoint));
  59904. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  59905. /**
  59906. * This class represents a single hinge physics joint
  59907. */
  59908. var HingeJoint = (function (_super) {
  59909. __extends(HingeJoint, _super);
  59910. function HingeJoint(jointData) {
  59911. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  59912. }
  59913. /**
  59914. * Set the motor values.
  59915. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59916. * @param {number} force the force to apply
  59917. * @param {number} maxForce max force for this motor.
  59918. */
  59919. HingeJoint.prototype.setMotor = function (force, maxForce) {
  59920. this._physicsPlugin.setMotor(this, force, maxForce);
  59921. };
  59922. /**
  59923. * Set the motor's limits.
  59924. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59925. */
  59926. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  59927. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  59928. };
  59929. return HingeJoint;
  59930. }(MotorEnabledJoint));
  59931. BABYLON.HingeJoint = HingeJoint;
  59932. /**
  59933. * This class represents a dual hinge physics joint (same as wheel joint)
  59934. */
  59935. var Hinge2Joint = (function (_super) {
  59936. __extends(Hinge2Joint, _super);
  59937. function Hinge2Joint(jointData) {
  59938. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  59939. }
  59940. /**
  59941. * Set the motor values.
  59942. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59943. * @param {number} force the force to apply
  59944. * @param {number} maxForce max force for this motor.
  59945. * @param {motorIndex} the motor's index, 0 or 1.
  59946. */
  59947. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  59948. if (motorIndex === void 0) { motorIndex = 0; }
  59949. this._physicsPlugin.setMotor(this, force, maxForce, motorIndex);
  59950. };
  59951. /**
  59952. * Set the motor limits.
  59953. * Attention, this function is plugin specific. Engines won't react 100% the same.
  59954. * @param {number} upperLimit the upper limit
  59955. * @param {number} lowerLimit lower limit
  59956. * @param {motorIndex} the motor's index, 0 or 1.
  59957. */
  59958. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  59959. if (motorIndex === void 0) { motorIndex = 0; }
  59960. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  59961. };
  59962. return Hinge2Joint;
  59963. }(MotorEnabledJoint));
  59964. BABYLON.Hinge2Joint = Hinge2Joint;
  59965. })(BABYLON || (BABYLON = {}));
  59966. //# sourceMappingURL=babylon.physicsJoint.js.map
  59967. var BABYLON;
  59968. (function (BABYLON) {
  59969. var PhysicsImpostor = (function () {
  59970. function PhysicsImpostor(object, type, _options, _scene) {
  59971. if (_options === void 0) { _options = { mass: 0 }; }
  59972. var _this = this;
  59973. this.object = object;
  59974. this.type = type;
  59975. this._options = _options;
  59976. this._scene = _scene;
  59977. this._bodyUpdateRequired = false;
  59978. this._onBeforePhysicsStepCallbacks = new Array();
  59979. this._onAfterPhysicsStepCallbacks = new Array();
  59980. this._onPhysicsCollideCallbacks = [];
  59981. this._deltaPosition = BABYLON.Vector3.Zero();
  59982. this._isDisposed = false;
  59983. this._tmpPositionWithDelta = BABYLON.Vector3.Zero();
  59984. this._tmpRotationWithDelta = new BABYLON.Quaternion();
  59985. /**
  59986. * this function is executed by the physics engine.
  59987. */
  59988. this.beforeStep = function () {
  59989. _this.object.position.subtractToRef(_this._deltaPosition, _this._tmpPositionWithDelta);
  59990. //conjugate deltaRotation
  59991. if (_this._deltaRotationConjugated) {
  59992. _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this._tmpRotationWithDelta);
  59993. }
  59994. else {
  59995. _this._tmpRotationWithDelta.copyFrom(_this.object.rotationQuaternion);
  59996. }
  59997. _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, _this._tmpPositionWithDelta, _this._tmpRotationWithDelta);
  59998. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  59999. func(_this);
  60000. });
  60001. };
  60002. /**
  60003. * this function is executed by the physics engine.
  60004. */
  60005. this.afterStep = function () {
  60006. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  60007. func(_this);
  60008. });
  60009. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  60010. _this.object.position.addInPlace(_this._deltaPosition);
  60011. if (_this._deltaRotation) {
  60012. _this.object.rotationQuaternion.multiplyInPlace(_this._deltaRotation);
  60013. }
  60014. };
  60015. /**
  60016. * Legacy collision detection event support
  60017. */
  60018. this.onCollideEvent = null;
  60019. //event and body object due to cannon's event-based architecture.
  60020. this.onCollide = function (e) {
  60021. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent)
  60022. return;
  60023. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  60024. if (otherImpostor) {
  60025. // Legacy collision detection event support
  60026. if (_this.onCollideEvent) {
  60027. _this.onCollideEvent(_this, otherImpostor);
  60028. }
  60029. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  60030. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  60031. }).forEach(function (obj) {
  60032. obj.callback(_this, otherImpostor);
  60033. });
  60034. }
  60035. };
  60036. //sanity check!
  60037. if (!this.object) {
  60038. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  60039. return;
  60040. }
  60041. //legacy support for old syntax.
  60042. if (!this._scene && object.getScene) {
  60043. this._scene = object.getScene();
  60044. }
  60045. this._physicsEngine = this._scene.getPhysicsEngine();
  60046. if (!this._physicsEngine) {
  60047. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  60048. }
  60049. else {
  60050. //set the object's quaternion, if not set
  60051. if (!this.object.rotationQuaternion) {
  60052. if (this.object.rotation) {
  60053. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  60054. }
  60055. else {
  60056. this.object.rotationQuaternion = new BABYLON.Quaternion();
  60057. }
  60058. }
  60059. //default options params
  60060. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  60061. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  60062. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  60063. this._joints = [];
  60064. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  60065. if (!this.object.parent) {
  60066. this._init();
  60067. }
  60068. else if (this.object.parent.physicsImpostor) {
  60069. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  60070. }
  60071. }
  60072. }
  60073. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  60074. get: function () {
  60075. return this._isDisposed;
  60076. },
  60077. enumerable: true,
  60078. configurable: true
  60079. });
  60080. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  60081. get: function () {
  60082. return this._physicsEngine.getPhysicsPlugin().getBodyMass(this);
  60083. },
  60084. set: function (value) {
  60085. this.setMass(value);
  60086. },
  60087. enumerable: true,
  60088. configurable: true
  60089. });
  60090. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  60091. get: function () {
  60092. return this._physicsEngine.getPhysicsPlugin().getBodyFriction(this);
  60093. },
  60094. set: function (value) {
  60095. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  60096. },
  60097. enumerable: true,
  60098. configurable: true
  60099. });
  60100. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  60101. get: function () {
  60102. return this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this);
  60103. },
  60104. set: function (value) {
  60105. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  60106. },
  60107. enumerable: true,
  60108. configurable: true
  60109. });
  60110. /**
  60111. * This function will completly initialize this impostor.
  60112. * It will create a new body - but only if this mesh has no parent.
  60113. * If it has, this impostor will not be used other than to define the impostor
  60114. * of the child mesh.
  60115. */
  60116. PhysicsImpostor.prototype._init = function () {
  60117. this._physicsEngine.removeImpostor(this);
  60118. this.physicsBody = null;
  60119. this._parent = this._parent || this._getPhysicsParent();
  60120. if (!this.parent) {
  60121. this._physicsEngine.addImpostor(this);
  60122. }
  60123. };
  60124. PhysicsImpostor.prototype._getPhysicsParent = function () {
  60125. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  60126. var parentMesh = this.object.parent;
  60127. return parentMesh.physicsImpostor;
  60128. }
  60129. return;
  60130. };
  60131. /**
  60132. * Should a new body be generated.
  60133. */
  60134. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  60135. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  60136. };
  60137. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  60138. this.forceUpdate();
  60139. };
  60140. /**
  60141. * Force a regeneration of this or the parent's impostor's body.
  60142. * Use under cautious - This will remove all joints already implemented.
  60143. */
  60144. PhysicsImpostor.prototype.forceUpdate = function () {
  60145. this._init();
  60146. if (this.parent) {
  60147. this.parent.forceUpdate();
  60148. }
  60149. };
  60150. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  60151. /*public get mesh(): AbstractMesh {
  60152. return this._mesh;
  60153. }*/
  60154. /**
  60155. * Gets the body that holds this impostor. Either its own, or its parent.
  60156. */
  60157. get: function () {
  60158. return this._parent ? this._parent.physicsBody : this._physicsBody;
  60159. },
  60160. /**
  60161. * Set the physics body. Used mainly by the physics engine/plugin
  60162. */
  60163. set: function (physicsBody) {
  60164. if (this._physicsBody) {
  60165. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  60166. }
  60167. this._physicsBody = physicsBody;
  60168. this.resetUpdateFlags();
  60169. },
  60170. enumerable: true,
  60171. configurable: true
  60172. });
  60173. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  60174. get: function () {
  60175. return this._parent;
  60176. },
  60177. set: function (value) {
  60178. this._parent = value;
  60179. },
  60180. enumerable: true,
  60181. configurable: true
  60182. });
  60183. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  60184. this._bodyUpdateRequired = false;
  60185. };
  60186. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  60187. if (this.object.getBoundingInfo) {
  60188. var q = this.object.rotationQuaternion;
  60189. //reset rotation
  60190. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  60191. //calculate the world matrix with no rotation
  60192. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60193. var size = this.object.getBoundingInfo().boundingBox.extendSizeWorld.scale(2);
  60194. //bring back the rotation
  60195. this.object.rotationQuaternion = q;
  60196. //calculate the world matrix with the new rotation
  60197. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  60198. return size;
  60199. }
  60200. else {
  60201. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  60202. }
  60203. };
  60204. PhysicsImpostor.prototype.getObjectCenter = function () {
  60205. if (this.object.getBoundingInfo) {
  60206. return this.object.getBoundingInfo().boundingBox.centerWorld;
  60207. }
  60208. else {
  60209. return this.object.position;
  60210. }
  60211. };
  60212. /**
  60213. * Get a specific parametes from the options parameter.
  60214. */
  60215. PhysicsImpostor.prototype.getParam = function (paramName) {
  60216. return this._options[paramName];
  60217. };
  60218. /**
  60219. * Sets a specific parameter in the options given to the physics plugin
  60220. */
  60221. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  60222. this._options[paramName] = value;
  60223. this._bodyUpdateRequired = true;
  60224. };
  60225. /**
  60226. * Specifically change the body's mass option. Won't recreate the physics body object
  60227. */
  60228. PhysicsImpostor.prototype.setMass = function (mass) {
  60229. if (this.getParam("mass") !== mass) {
  60230. this.setParam("mass", mass);
  60231. }
  60232. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  60233. };
  60234. PhysicsImpostor.prototype.getLinearVelocity = function () {
  60235. return this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this);
  60236. };
  60237. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  60238. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  60239. };
  60240. PhysicsImpostor.prototype.getAngularVelocity = function () {
  60241. return this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this);
  60242. };
  60243. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  60244. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  60245. };
  60246. /**
  60247. * Execute a function with the physics plugin native code.
  60248. * Provide a function the will have two variables - the world object and the physics body object.
  60249. */
  60250. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  60251. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  60252. };
  60253. /**
  60254. * Register a function that will be executed before the physics world is stepping forward.
  60255. */
  60256. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  60257. this._onBeforePhysicsStepCallbacks.push(func);
  60258. };
  60259. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  60260. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  60261. if (index > -1) {
  60262. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  60263. }
  60264. else {
  60265. BABYLON.Tools.Warn("Function to remove was not found");
  60266. }
  60267. };
  60268. /**
  60269. * Register a function that will be executed after the physics step
  60270. */
  60271. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  60272. this._onAfterPhysicsStepCallbacks.push(func);
  60273. };
  60274. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  60275. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  60276. if (index > -1) {
  60277. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  60278. }
  60279. else {
  60280. BABYLON.Tools.Warn("Function to remove was not found");
  60281. }
  60282. };
  60283. /**
  60284. * register a function that will be executed when this impostor collides against a different body.
  60285. */
  60286. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  60287. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60288. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  60289. };
  60290. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  60291. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  60292. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  60293. if (index > -1) {
  60294. this._onPhysicsCollideCallbacks.splice(index, 1);
  60295. }
  60296. else {
  60297. BABYLON.Tools.Warn("Function to remove was not found");
  60298. }
  60299. };
  60300. /**
  60301. * Apply a force
  60302. */
  60303. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  60304. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  60305. };
  60306. /**
  60307. * Apply an impulse
  60308. */
  60309. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  60310. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  60311. };
  60312. /**
  60313. * A help function to create a joint.
  60314. */
  60315. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  60316. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  60317. this.addJoint(otherImpostor, joint);
  60318. };
  60319. /**
  60320. * Add a joint to this impostor with a different impostor.
  60321. */
  60322. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  60323. this._joints.push({
  60324. otherImpostor: otherImpostor,
  60325. joint: joint
  60326. });
  60327. this._physicsEngine.addJoint(this, otherImpostor, joint);
  60328. };
  60329. /**
  60330. * Will keep this body still, in a sleep mode.
  60331. */
  60332. PhysicsImpostor.prototype.sleep = function () {
  60333. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  60334. };
  60335. /**
  60336. * Wake the body up.
  60337. */
  60338. PhysicsImpostor.prototype.wakeUp = function () {
  60339. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  60340. };
  60341. PhysicsImpostor.prototype.clone = function (newObject) {
  60342. if (!newObject)
  60343. return null;
  60344. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  60345. };
  60346. PhysicsImpostor.prototype.dispose = function () {
  60347. var _this = this;
  60348. //no dispose if no physics engine is available.
  60349. if (!this._physicsEngine) {
  60350. return;
  60351. }
  60352. this._joints.forEach(function (j) {
  60353. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  60354. });
  60355. //dispose the physics body
  60356. this._physicsEngine.removeImpostor(this);
  60357. if (this.parent) {
  60358. this.parent.forceUpdate();
  60359. }
  60360. else {
  60361. /*this._object.getChildMeshes().forEach(function(mesh) {
  60362. if (mesh.physicsImpostor) {
  60363. if (disposeChildren) {
  60364. mesh.physicsImpostor.dispose();
  60365. mesh.physicsImpostor = null;
  60366. }
  60367. }
  60368. })*/
  60369. }
  60370. this._isDisposed = true;
  60371. };
  60372. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  60373. this._deltaPosition.copyFrom(position);
  60374. };
  60375. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  60376. if (!this._deltaRotation) {
  60377. this._deltaRotation = new BABYLON.Quaternion();
  60378. }
  60379. this._deltaRotation.copyFrom(rotation);
  60380. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  60381. };
  60382. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  60383. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  60384. };
  60385. PhysicsImpostor.prototype.getRadius = function () {
  60386. return this._physicsEngine.getPhysicsPlugin().getRadius(this);
  60387. };
  60388. /**
  60389. * Sync a bone with this impostor
  60390. * @param bone The bone to sync to the impostor.
  60391. * @param boneMesh The mesh that the bone is influencing.
  60392. * @param jointPivot The pivot of the joint / bone in local space.
  60393. * @param distToJoint Optional distance from the impostor to the joint.
  60394. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60395. */
  60396. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  60397. var tempVec = PhysicsImpostor._tmpVecs[0];
  60398. var mesh = this.object;
  60399. if (adjustRotation) {
  60400. var tempQuat = PhysicsImpostor._tmpQuat;
  60401. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  60402. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  60403. }
  60404. else {
  60405. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  60406. }
  60407. tempVec.x = 0;
  60408. tempVec.y = 0;
  60409. tempVec.z = 0;
  60410. if (jointPivot) {
  60411. tempVec.x = jointPivot.x;
  60412. tempVec.y = jointPivot.y;
  60413. tempVec.z = jointPivot.z;
  60414. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  60415. if (distToJoint === undefined || distToJoint === null) {
  60416. distToJoint = jointPivot.length();
  60417. }
  60418. tempVec.x *= distToJoint;
  60419. tempVec.y *= distToJoint;
  60420. tempVec.z *= distToJoint;
  60421. }
  60422. if (bone.getParent()) {
  60423. tempVec.addInPlace(mesh.getAbsolutePosition());
  60424. bone.setAbsolutePosition(tempVec, boneMesh);
  60425. }
  60426. else {
  60427. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  60428. boneMesh.position.x -= tempVec.x;
  60429. boneMesh.position.y -= tempVec.y;
  60430. boneMesh.position.z -= tempVec.z;
  60431. }
  60432. };
  60433. /**
  60434. * Sync impostor to a bone
  60435. * @param bone The bone that the impostor will be synced to.
  60436. * @param boneMesh The mesh that the bone is influencing.
  60437. * @param jointPivot The pivot of the joint / bone in local space.
  60438. * @param distToJoint Optional distance from the impostor to the joint.
  60439. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  60440. * @param boneAxis Optional vector3 axis the bone is aligned with
  60441. */
  60442. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  60443. var mesh = this.object;
  60444. if (adjustRotation) {
  60445. var tempQuat = PhysicsImpostor._tmpQuat;
  60446. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  60447. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  60448. }
  60449. else {
  60450. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  60451. }
  60452. var pos = PhysicsImpostor._tmpVecs[0];
  60453. var boneDir = PhysicsImpostor._tmpVecs[1];
  60454. if (!boneAxis) {
  60455. boneAxis = PhysicsImpostor._tmpVecs[2];
  60456. boneAxis.x = 0;
  60457. boneAxis.y = 1;
  60458. boneAxis.z = 0;
  60459. }
  60460. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  60461. bone.getAbsolutePositionToRef(boneMesh, pos);
  60462. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  60463. distToJoint = jointPivot.length();
  60464. }
  60465. if (distToJoint !== undefined && distToJoint !== null) {
  60466. pos.x += boneDir.x * distToJoint;
  60467. pos.y += boneDir.y * distToJoint;
  60468. pos.z += boneDir.z * distToJoint;
  60469. }
  60470. mesh.setAbsolutePosition(pos);
  60471. };
  60472. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  60473. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  60474. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  60475. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  60476. //Impostor types
  60477. PhysicsImpostor.NoImpostor = 0;
  60478. PhysicsImpostor.SphereImpostor = 1;
  60479. PhysicsImpostor.BoxImpostor = 2;
  60480. PhysicsImpostor.PlaneImpostor = 3;
  60481. PhysicsImpostor.MeshImpostor = 4;
  60482. PhysicsImpostor.CylinderImpostor = 7;
  60483. PhysicsImpostor.ParticleImpostor = 8;
  60484. PhysicsImpostor.HeightmapImpostor = 9;
  60485. return PhysicsImpostor;
  60486. }());
  60487. BABYLON.PhysicsImpostor = PhysicsImpostor;
  60488. })(BABYLON || (BABYLON = {}));
  60489. //# sourceMappingURL=babylon.physicsImpostor.js.map
  60490. var BABYLON;
  60491. (function (BABYLON) {
  60492. var PhysicsEngine = (function () {
  60493. function PhysicsEngine(gravity, _physicsPlugin) {
  60494. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  60495. this._physicsPlugin = _physicsPlugin;
  60496. //new methods and parameters
  60497. this._impostors = [];
  60498. this._joints = [];
  60499. if (!this._physicsPlugin.isSupported()) {
  60500. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  60501. + "Please make sure it is included.");
  60502. }
  60503. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  60504. this.setGravity(gravity);
  60505. this.setTimeStep();
  60506. }
  60507. PhysicsEngine.prototype.setGravity = function (gravity) {
  60508. this.gravity = gravity;
  60509. this._physicsPlugin.setGravity(this.gravity);
  60510. };
  60511. /**
  60512. * Set the time step of the physics engine.
  60513. * default is 1/60.
  60514. * To slow it down, enter 1/600 for example.
  60515. * To speed it up, 1/30
  60516. * @param {number} newTimeStep the new timestep to apply to this world.
  60517. */
  60518. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  60519. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  60520. this._physicsPlugin.setTimeStep(newTimeStep);
  60521. };
  60522. /**
  60523. * Get the time step of the physics engine.
  60524. */
  60525. PhysicsEngine.prototype.getTimeStep = function () {
  60526. return this._physicsPlugin.getTimeStep();
  60527. };
  60528. PhysicsEngine.prototype.dispose = function () {
  60529. this._impostors.forEach(function (impostor) {
  60530. impostor.dispose();
  60531. });
  60532. this._physicsPlugin.dispose();
  60533. };
  60534. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  60535. return this._physicsPlugin.name;
  60536. };
  60537. /**
  60538. * Adding a new impostor for the impostor tracking.
  60539. * This will be done by the impostor itself.
  60540. * @param {PhysicsImpostor} impostor the impostor to add
  60541. */
  60542. PhysicsEngine.prototype.addImpostor = function (impostor) {
  60543. impostor.uniqueId = this._impostors.push(impostor);
  60544. //if no parent, generate the body
  60545. if (!impostor.parent) {
  60546. this._physicsPlugin.generatePhysicsBody(impostor);
  60547. }
  60548. };
  60549. /**
  60550. * Remove an impostor from the engine.
  60551. * This impostor and its mesh will not longer be updated by the physics engine.
  60552. * @param {PhysicsImpostor} impostor the impostor to remove
  60553. */
  60554. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  60555. var index = this._impostors.indexOf(impostor);
  60556. if (index > -1) {
  60557. var removed = this._impostors.splice(index, 1);
  60558. //Is it needed?
  60559. if (removed.length) {
  60560. //this will also remove it from the world.
  60561. removed[0].physicsBody = null;
  60562. }
  60563. }
  60564. };
  60565. /**
  60566. * Add a joint to the physics engine
  60567. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  60568. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  60569. * @param {PhysicsJoint} the joint that will connect both impostors.
  60570. */
  60571. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  60572. var impostorJoint = {
  60573. mainImpostor: mainImpostor,
  60574. connectedImpostor: connectedImpostor,
  60575. joint: joint
  60576. };
  60577. joint.physicsPlugin = this._physicsPlugin;
  60578. this._joints.push(impostorJoint);
  60579. this._physicsPlugin.generateJoint(impostorJoint);
  60580. };
  60581. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  60582. var matchingJoints = this._joints.filter(function (impostorJoint) {
  60583. return (impostorJoint.connectedImpostor === connectedImpostor
  60584. && impostorJoint.joint === joint
  60585. && impostorJoint.mainImpostor === mainImpostor);
  60586. });
  60587. if (matchingJoints.length) {
  60588. this._physicsPlugin.removeJoint(matchingJoints[0]);
  60589. //TODO remove it from the list as well
  60590. }
  60591. };
  60592. /**
  60593. * Called by the scene. no need to call it.
  60594. */
  60595. PhysicsEngine.prototype._step = function (delta) {
  60596. var _this = this;
  60597. //check if any mesh has no body / requires an update
  60598. this._impostors.forEach(function (impostor) {
  60599. if (impostor.isBodyInitRequired()) {
  60600. _this._physicsPlugin.generatePhysicsBody(impostor);
  60601. }
  60602. });
  60603. if (delta > 0.1) {
  60604. delta = 0.1;
  60605. }
  60606. else if (delta <= 0) {
  60607. delta = 1.0 / 60.0;
  60608. }
  60609. this._physicsPlugin.executeStep(delta, this._impostors);
  60610. };
  60611. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  60612. return this._physicsPlugin;
  60613. };
  60614. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  60615. for (var i = 0; i < this._impostors.length; ++i) {
  60616. if (this._impostors[i].object === object) {
  60617. return this._impostors[i];
  60618. }
  60619. }
  60620. };
  60621. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  60622. for (var i = 0; i < this._impostors.length; ++i) {
  60623. if (this._impostors[i].physicsBody === body) {
  60624. return this._impostors[i];
  60625. }
  60626. }
  60627. };
  60628. // Statics
  60629. PhysicsEngine.Epsilon = 0.001;
  60630. return PhysicsEngine;
  60631. }());
  60632. BABYLON.PhysicsEngine = PhysicsEngine;
  60633. })(BABYLON || (BABYLON = {}));
  60634. //# sourceMappingURL=babylon.physicsEngine.js.map
  60635. var BABYLON;
  60636. (function (BABYLON) {
  60637. var CannonJSPlugin = (function () {
  60638. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  60639. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  60640. if (iterations === void 0) { iterations = 10; }
  60641. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  60642. this.name = "CannonJSPlugin";
  60643. this._physicsMaterials = [];
  60644. this._fixedTimeStep = 1 / 60;
  60645. //See https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60646. this._currentCollisionGroup = 2;
  60647. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  60648. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  60649. this._tmpPosition = BABYLON.Vector3.Zero();
  60650. this._tmpQuaternion = new BABYLON.Quaternion();
  60651. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  60652. this._tmpDeltaRotation = new BABYLON.Quaternion();
  60653. this._tmpUnityRotation = new BABYLON.Quaternion();
  60654. if (!this.isSupported()) {
  60655. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  60656. return;
  60657. }
  60658. this.world = new CANNON.World();
  60659. this.world.broadphase = new CANNON.NaiveBroadphase();
  60660. this.world.solver.iterations = iterations;
  60661. }
  60662. CannonJSPlugin.prototype.setGravity = function (gravity) {
  60663. this.world.gravity.copy(gravity);
  60664. };
  60665. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  60666. this._fixedTimeStep = timeStep;
  60667. };
  60668. CannonJSPlugin.prototype.getTimeStep = function () {
  60669. return this._fixedTimeStep;
  60670. };
  60671. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  60672. // Delta is in seconds, should be provided in milliseconds
  60673. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta * 1000 : 0, 3);
  60674. };
  60675. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  60676. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60677. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60678. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  60679. };
  60680. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  60681. var worldPoint = new CANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  60682. var impulse = new CANNON.Vec3(force.x, force.y, force.z);
  60683. impostor.physicsBody.applyForce(impulse, worldPoint);
  60684. };
  60685. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  60686. //parent-child relationship. Does this impostor has a parent impostor?
  60687. if (impostor.parent) {
  60688. if (impostor.physicsBody) {
  60689. this.removePhysicsBody(impostor);
  60690. //TODO is that needed?
  60691. impostor.forceUpdate();
  60692. }
  60693. return;
  60694. }
  60695. //should a new body be created for this impostor?
  60696. if (impostor.isBodyInitRequired()) {
  60697. var shape = this._createShape(impostor);
  60698. //unregister events, if body is being changed
  60699. var oldBody = impostor.physicsBody;
  60700. if (oldBody) {
  60701. this.removePhysicsBody(impostor);
  60702. }
  60703. //create the body and material
  60704. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  60705. var bodyCreationObject = {
  60706. mass: impostor.getParam("mass"),
  60707. material: material
  60708. };
  60709. // A simple extend, in case native options were used.
  60710. var nativeOptions = impostor.getParam("nativeOptions");
  60711. for (var key in nativeOptions) {
  60712. if (nativeOptions.hasOwnProperty(key)) {
  60713. bodyCreationObject[key] = nativeOptions[key];
  60714. }
  60715. }
  60716. impostor.physicsBody = new CANNON.Body(bodyCreationObject);
  60717. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  60718. this.world.addEventListener("preStep", impostor.beforeStep);
  60719. this.world.addEventListener("postStep", impostor.afterStep);
  60720. impostor.physicsBody.addShape(shape);
  60721. this.world.add(impostor.physicsBody);
  60722. //try to keep the body moving in the right direction by taking old properties.
  60723. //Should be tested!
  60724. if (oldBody) {
  60725. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  60726. impostor.physicsBody[param].copy(oldBody[param]);
  60727. });
  60728. }
  60729. this._processChildMeshes(impostor);
  60730. }
  60731. //now update the body's transformation
  60732. this._updatePhysicsBodyTransformation(impostor);
  60733. };
  60734. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  60735. var _this = this;
  60736. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes() : [];
  60737. if (meshChildren.length) {
  60738. var processMesh = function (localPosition, mesh) {
  60739. var childImpostor = mesh.getPhysicsImpostor();
  60740. if (childImpostor) {
  60741. var parent = childImpostor.parent;
  60742. if (parent !== mainImpostor) {
  60743. var localPosition = mesh.position;
  60744. if (childImpostor.physicsBody) {
  60745. _this.removePhysicsBody(childImpostor);
  60746. childImpostor.physicsBody = null;
  60747. }
  60748. childImpostor.parent = mainImpostor;
  60749. childImpostor.resetUpdateFlags();
  60750. mainImpostor.physicsBody.addShape(_this._createShape(childImpostor), new CANNON.Vec3(localPosition.x, localPosition.y, localPosition.z));
  60751. //Add the mass of the children.
  60752. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  60753. }
  60754. }
  60755. mesh.getChildMeshes().forEach(processMesh.bind(_this, mesh.position));
  60756. };
  60757. meshChildren.forEach(processMesh.bind(this, BABYLON.Vector3.Zero()));
  60758. }
  60759. };
  60760. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  60761. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  60762. this.world.removeEventListener("preStep", impostor.beforeStep);
  60763. this.world.removeEventListener("postStep", impostor.afterStep);
  60764. this.world.remove(impostor.physicsBody);
  60765. };
  60766. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  60767. var mainBody = impostorJoint.mainImpostor.physicsBody;
  60768. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  60769. if (!mainBody || !connectedBody) {
  60770. return;
  60771. }
  60772. var constraint;
  60773. var jointData = impostorJoint.joint.jointData;
  60774. //TODO - https://github.com/schteppe/cannon.js/blob/gh-pages/demos/collisionFilter.html
  60775. var constraintData = {
  60776. pivotA: jointData.mainPivot ? new CANNON.Vec3().copy(jointData.mainPivot) : null,
  60777. pivotB: jointData.connectedPivot ? new CANNON.Vec3().copy(jointData.connectedPivot) : null,
  60778. axisA: jointData.mainAxis ? new CANNON.Vec3().copy(jointData.mainAxis) : null,
  60779. axisB: jointData.connectedAxis ? new CANNON.Vec3().copy(jointData.connectedAxis) : null,
  60780. maxForce: jointData.nativeParams.maxForce,
  60781. collideConnected: !!jointData.collision
  60782. };
  60783. switch (impostorJoint.joint.type) {
  60784. case BABYLON.PhysicsJoint.HingeJoint:
  60785. case BABYLON.PhysicsJoint.Hinge2Joint:
  60786. constraint = new CANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  60787. break;
  60788. case BABYLON.PhysicsJoint.DistanceJoint:
  60789. constraint = new CANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  60790. break;
  60791. case BABYLON.PhysicsJoint.SpringJoint:
  60792. var springData = jointData;
  60793. constraint = new CANNON.Spring(mainBody, connectedBody, {
  60794. restLength: springData.length,
  60795. stiffness: springData.stiffness,
  60796. damping: springData.damping,
  60797. localAnchorA: constraintData.pivotA,
  60798. localAnchorB: constraintData.pivotB
  60799. });
  60800. break;
  60801. case BABYLON.PhysicsJoint.LockJoint:
  60802. constraint = new CANNON.LockConstraint(mainBody, connectedBody, constraintData);
  60803. break;
  60804. case BABYLON.PhysicsJoint.PointToPointJoint:
  60805. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  60806. default:
  60807. constraint = new CANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  60808. break;
  60809. }
  60810. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  60811. constraint.collideConnected = !!jointData.collision;
  60812. impostorJoint.joint.physicsJoint = constraint;
  60813. //don't add spring as constraint, as it is not one.
  60814. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  60815. this.world.addConstraint(constraint);
  60816. }
  60817. else {
  60818. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  60819. constraint.applyForce();
  60820. });
  60821. }
  60822. };
  60823. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  60824. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  60825. };
  60826. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  60827. var index;
  60828. var mat;
  60829. for (index = 0; index < this._physicsMaterials.length; index++) {
  60830. mat = this._physicsMaterials[index];
  60831. if (mat.friction === friction && mat.restitution === restitution) {
  60832. return mat;
  60833. }
  60834. }
  60835. var currentMat = new CANNON.Material(name);
  60836. currentMat.friction = friction;
  60837. currentMat.restitution = restitution;
  60838. this._physicsMaterials.push(currentMat);
  60839. return currentMat;
  60840. };
  60841. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  60842. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  60843. };
  60844. CannonJSPlugin.prototype._createShape = function (impostor) {
  60845. var object = impostor.object;
  60846. var returnValue;
  60847. var extendSize = impostor.getObjectExtendSize();
  60848. switch (impostor.type) {
  60849. case BABYLON.PhysicsImpostor.SphereImpostor:
  60850. var radiusX = extendSize.x;
  60851. var radiusY = extendSize.y;
  60852. var radiusZ = extendSize.z;
  60853. returnValue = new CANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  60854. break;
  60855. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  60856. case BABYLON.PhysicsImpostor.CylinderImpostor:
  60857. returnValue = new CANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  60858. break;
  60859. case BABYLON.PhysicsImpostor.BoxImpostor:
  60860. var box = extendSize.scale(0.5);
  60861. returnValue = new CANNON.Box(new CANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  60862. break;
  60863. case BABYLON.PhysicsImpostor.PlaneImpostor:
  60864. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  60865. returnValue = new CANNON.Plane();
  60866. break;
  60867. case BABYLON.PhysicsImpostor.MeshImpostor:
  60868. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  60869. var rawFaces = object.getIndices ? object.getIndices() : [];
  60870. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  60871. returnValue = new CANNON.Trimesh(rawVerts, rawFaces);
  60872. break;
  60873. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  60874. returnValue = this._createHeightmap(object);
  60875. break;
  60876. case BABYLON.PhysicsImpostor.ParticleImpostor:
  60877. returnValue = new CANNON.Particle();
  60878. break;
  60879. }
  60880. return returnValue;
  60881. };
  60882. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  60883. var pos = object.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60884. var matrix = [];
  60885. //For now pointDepth will not be used and will be automatically calculated.
  60886. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  60887. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  60888. var dim = Math.min(object.getBoundingInfo().boundingBox.extendSizeWorld.x, object.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60889. var elementSize = dim * 2 / arraySize;
  60890. var minY = object.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60891. for (var i = 0; i < pos.length; i = i + 3) {
  60892. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  60893. var z = Math.round(((pos[i + 2]) / elementSize - arraySize / 2) * -1);
  60894. var y = pos[i + 1] + minY;
  60895. if (!matrix[x]) {
  60896. matrix[x] = [];
  60897. }
  60898. if (!matrix[x][z]) {
  60899. matrix[x][z] = y;
  60900. }
  60901. matrix[x][z] = Math.max(y, matrix[x][z]);
  60902. }
  60903. for (var x = 0; x <= arraySize; ++x) {
  60904. if (!matrix[x]) {
  60905. var loc = 1;
  60906. while (!matrix[(x + loc) % arraySize]) {
  60907. loc++;
  60908. }
  60909. matrix[x] = matrix[(x + loc) % arraySize].slice();
  60910. //console.log("missing x", x);
  60911. }
  60912. for (var z = 0; z <= arraySize; ++z) {
  60913. if (!matrix[x][z]) {
  60914. var loc = 1;
  60915. var newValue;
  60916. while (newValue === undefined) {
  60917. newValue = matrix[x][(z + loc++) % arraySize];
  60918. }
  60919. matrix[x][z] = newValue;
  60920. }
  60921. }
  60922. }
  60923. var shape = new CANNON.Heightfield(matrix, {
  60924. elementSize: elementSize
  60925. });
  60926. //For future reference, needed for body transformation
  60927. shape.minY = minY;
  60928. return shape;
  60929. };
  60930. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  60931. var object = impostor.object;
  60932. //make sure it is updated...
  60933. object.computeWorldMatrix && object.computeWorldMatrix(true);
  60934. // The delta between the mesh position and the mesh bounding box center
  60935. var center = impostor.getObjectCenter();
  60936. this._tmpDeltaPosition.copyFrom(object.position.subtract(center));
  60937. this._tmpPosition.copyFrom(center);
  60938. var quaternion = object.rotationQuaternion;
  60939. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  60940. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  60941. //-90 DEG in X, precalculated
  60942. quaternion = quaternion.multiply(this._minus90X);
  60943. //Invert! (Precalculated, 90 deg in X)
  60944. //No need to clone. this will never change.
  60945. impostor.setDeltaRotation(this._plus90X);
  60946. }
  60947. //If it is a heightfield, if should be centered.
  60948. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  60949. var mesh = object;
  60950. //calculate the correct body position:
  60951. var rotationQuaternion = mesh.rotationQuaternion;
  60952. mesh.rotationQuaternion = this._tmpUnityRotation;
  60953. mesh.computeWorldMatrix(true);
  60954. //get original center with no rotation
  60955. var c = center.clone();
  60956. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  60957. //rotation is back
  60958. mesh.rotationQuaternion = rotationQuaternion;
  60959. //calculate the new center using a pivot (since Cannon.js doesn't center height maps)
  60960. var p = BABYLON.Matrix.Translation(mesh.getBoundingInfo().boundingBox.extendSizeWorld.x, 0, -mesh.getBoundingInfo().boundingBox.extendSizeWorld.z);
  60961. mesh.setPivotMatrix(p);
  60962. mesh.computeWorldMatrix(true);
  60963. //calculate the translation
  60964. var translation = mesh.getBoundingInfo().boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  60965. this._tmpPosition.copyFromFloats(translation.x, translation.y - mesh.getBoundingInfo().boundingBox.extendSizeWorld.y, translation.z);
  60966. //add it inverted to the delta
  60967. this._tmpDeltaPosition.copyFrom(mesh.getBoundingInfo().boundingBox.centerWorld.subtract(c));
  60968. this._tmpDeltaPosition.y += mesh.getBoundingInfo().boundingBox.extendSizeWorld.y;
  60969. mesh.setPivotMatrix(oldPivot);
  60970. mesh.computeWorldMatrix(true);
  60971. }
  60972. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  60973. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  60974. this._tmpPosition.copyFrom(object.position);
  60975. }
  60976. impostor.setDeltaPosition(this._tmpDeltaPosition);
  60977. //Now update the impostor object
  60978. impostor.physicsBody.position.copy(this._tmpPosition);
  60979. impostor.physicsBody.quaternion.copy(quaternion);
  60980. };
  60981. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  60982. impostor.object.position.copyFrom(impostor.physicsBody.position);
  60983. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  60984. };
  60985. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  60986. impostor.physicsBody.position.copy(newPosition);
  60987. impostor.physicsBody.quaternion.copy(newRotation);
  60988. };
  60989. CannonJSPlugin.prototype.isSupported = function () {
  60990. return window.CANNON !== undefined;
  60991. };
  60992. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  60993. impostor.physicsBody.velocity.copy(velocity);
  60994. };
  60995. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  60996. impostor.physicsBody.angularVelocity.copy(velocity);
  60997. };
  60998. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  60999. var v = impostor.physicsBody.velocity;
  61000. if (!v)
  61001. return null;
  61002. return new BABYLON.Vector3(v.x, v.y, v.z);
  61003. };
  61004. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61005. var v = impostor.physicsBody.angularVelocity;
  61006. if (!v)
  61007. return null;
  61008. return new BABYLON.Vector3(v.x, v.y, v.z);
  61009. };
  61010. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61011. impostor.physicsBody.mass = mass;
  61012. impostor.physicsBody.updateMassProperties();
  61013. };
  61014. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  61015. return impostor.physicsBody.mass;
  61016. };
  61017. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  61018. return impostor.physicsBody.material.friction;
  61019. };
  61020. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61021. impostor.physicsBody.material.friction = friction;
  61022. };
  61023. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61024. return impostor.physicsBody.material.restitution;
  61025. };
  61026. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61027. impostor.physicsBody.material.restitution = restitution;
  61028. };
  61029. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  61030. impostor.physicsBody.sleep();
  61031. };
  61032. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  61033. impostor.physicsBody.wakeUp();
  61034. };
  61035. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61036. joint.physicsJoint.distance = maxDistance;
  61037. };
  61038. CannonJSPlugin.prototype.enableMotor = function (joint, motorIndex) {
  61039. if (!motorIndex) {
  61040. joint.physicsJoint.enableMotor();
  61041. }
  61042. };
  61043. CannonJSPlugin.prototype.disableMotor = function (joint, motorIndex) {
  61044. if (!motorIndex) {
  61045. joint.physicsJoint.disableMotor();
  61046. }
  61047. };
  61048. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61049. if (!motorIndex) {
  61050. joint.physicsJoint.enableMotor();
  61051. joint.physicsJoint.setMotorSpeed(speed);
  61052. if (maxForce) {
  61053. this.setLimit(joint, maxForce);
  61054. }
  61055. }
  61056. };
  61057. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  61058. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  61059. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  61060. };
  61061. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61062. var body = impostor.physicsBody;
  61063. mesh.position.x = body.position.x;
  61064. mesh.position.y = body.position.y;
  61065. mesh.position.z = body.position.z;
  61066. mesh.rotationQuaternion.x = body.quaternion.x;
  61067. mesh.rotationQuaternion.y = body.quaternion.y;
  61068. mesh.rotationQuaternion.z = body.quaternion.z;
  61069. mesh.rotationQuaternion.w = body.quaternion.w;
  61070. };
  61071. CannonJSPlugin.prototype.getRadius = function (impostor) {
  61072. var shape = impostor.physicsBody.shapes[0];
  61073. return shape.boundingSphereRadius;
  61074. };
  61075. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61076. var shape = impostor.physicsBody.shapes[0];
  61077. result.x = shape.halfExtents.x * 2;
  61078. result.y = shape.halfExtents.y * 2;
  61079. result.z = shape.halfExtents.z * 2;
  61080. };
  61081. CannonJSPlugin.prototype.dispose = function () {
  61082. };
  61083. return CannonJSPlugin;
  61084. }());
  61085. BABYLON.CannonJSPlugin = CannonJSPlugin;
  61086. })(BABYLON || (BABYLON = {}));
  61087. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  61088. var BABYLON;
  61089. (function (BABYLON) {
  61090. var OimoJSPlugin = (function () {
  61091. function OimoJSPlugin(iterations) {
  61092. this.name = "OimoJSPlugin";
  61093. this._tmpImpostorsArray = [];
  61094. this._tmpPositionVector = BABYLON.Vector3.Zero();
  61095. this.world = new OIMO.World(1 / 60, 2, iterations, true);
  61096. this.world.worldscale(1);
  61097. this.world.clear();
  61098. //making sure no stats are calculated
  61099. this.world.isNoStat = true;
  61100. }
  61101. OimoJSPlugin.prototype.setGravity = function (gravity) {
  61102. this.world.gravity.copy(gravity);
  61103. };
  61104. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  61105. this.world.timeStep = timeStep;
  61106. };
  61107. OimoJSPlugin.prototype.getTimeStep = function () {
  61108. return this.world.timeStep;
  61109. };
  61110. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  61111. var _this = this;
  61112. impostors.forEach(function (impostor) {
  61113. impostor.beforeStep();
  61114. });
  61115. this.world.step();
  61116. impostors.forEach(function (impostor) {
  61117. impostor.afterStep();
  61118. //update the ordered impostors array
  61119. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  61120. });
  61121. //check for collisions
  61122. var contact = this.world.contacts;
  61123. while (contact !== null) {
  61124. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  61125. contact = contact.next;
  61126. continue;
  61127. }
  61128. //is this body colliding with any other? get the impostor
  61129. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  61130. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  61131. if (!mainImpostor || !collidingImpostor) {
  61132. contact = contact.next;
  61133. continue;
  61134. }
  61135. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  61136. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  61137. contact = contact.next;
  61138. }
  61139. };
  61140. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  61141. var mass = impostor.physicsBody.massInfo.mass;
  61142. impostor.physicsBody.applyImpulse(contactPoint.scale(OIMO.INV_SCALE), force.scale(OIMO.INV_SCALE * mass));
  61143. };
  61144. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  61145. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  61146. this.applyImpulse(impostor, force, contactPoint);
  61147. };
  61148. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  61149. var _this = this;
  61150. //parent-child relationship. Does this impostor has a parent impostor?
  61151. if (impostor.parent) {
  61152. if (impostor.physicsBody) {
  61153. this.removePhysicsBody(impostor);
  61154. //TODO is that needed?
  61155. impostor.forceUpdate();
  61156. }
  61157. return;
  61158. }
  61159. if (impostor.isBodyInitRequired()) {
  61160. var bodyConfig = {
  61161. name: impostor.uniqueId,
  61162. //Oimo must have mass, also for static objects.
  61163. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  61164. size: [],
  61165. type: [],
  61166. pos: [],
  61167. rot: [],
  61168. move: impostor.getParam("mass") !== 0,
  61169. //Supporting older versions of Oimo
  61170. world: this.world
  61171. };
  61172. var impostors = [impostor];
  61173. var addToArray = function (parent) {
  61174. if (!parent.getChildMeshes)
  61175. return;
  61176. parent.getChildMeshes().forEach(function (m) {
  61177. if (m.physicsImpostor) {
  61178. impostors.push(m.physicsImpostor);
  61179. m.physicsImpostor._init();
  61180. }
  61181. });
  61182. };
  61183. addToArray(impostor.object);
  61184. var checkWithEpsilon_1 = function (value) {
  61185. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  61186. };
  61187. impostors.forEach(function (i) {
  61188. //get the correct bounding box
  61189. var oldQuaternion = i.object.rotationQuaternion;
  61190. var rot = new OIMO.Euler().setFromQuaternion({
  61191. x: impostor.object.rotationQuaternion.x,
  61192. y: impostor.object.rotationQuaternion.y,
  61193. z: impostor.object.rotationQuaternion.z,
  61194. s: impostor.object.rotationQuaternion.w
  61195. });
  61196. var extendSize = i.getObjectExtendSize();
  61197. if (i === impostor) {
  61198. var center = impostor.getObjectCenter();
  61199. impostor.object.position.subtractToRef(center, _this._tmpPositionVector);
  61200. //Can also use Array.prototype.push.apply
  61201. bodyConfig.pos.push(center.x);
  61202. bodyConfig.pos.push(center.y);
  61203. bodyConfig.pos.push(center.z);
  61204. //tmp solution
  61205. bodyConfig.rot.push(rot.x / (OIMO.degtorad || OIMO.TO_RAD));
  61206. bodyConfig.rot.push(rot.y / (OIMO.degtorad || OIMO.TO_RAD));
  61207. bodyConfig.rot.push(rot.z / (OIMO.degtorad || OIMO.TO_RAD));
  61208. }
  61209. else {
  61210. bodyConfig.pos.push(i.object.position.x);
  61211. bodyConfig.pos.push(i.object.position.y);
  61212. bodyConfig.pos.push(i.object.position.z);
  61213. //tmp solution until https://github.com/lo-th/Oimo.js/pull/37 is merged
  61214. bodyConfig.rot.push(0);
  61215. bodyConfig.rot.push(0);
  61216. bodyConfig.rot.push(0);
  61217. }
  61218. // register mesh
  61219. switch (i.type) {
  61220. case BABYLON.PhysicsImpostor.ParticleImpostor:
  61221. BABYLON.Tools.Warn("No Particle support in Oimo.js. using SphereImpostor instead");
  61222. case BABYLON.PhysicsImpostor.SphereImpostor:
  61223. var radiusX = extendSize.x;
  61224. var radiusY = extendSize.y;
  61225. var radiusZ = extendSize.z;
  61226. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  61227. bodyConfig.type.push('sphere');
  61228. //due to the way oimo works with compounds, add 3 times
  61229. bodyConfig.size.push(size);
  61230. bodyConfig.size.push(size);
  61231. bodyConfig.size.push(size);
  61232. break;
  61233. case BABYLON.PhysicsImpostor.CylinderImpostor:
  61234. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  61235. var sizeY = checkWithEpsilon_1(extendSize.y);
  61236. bodyConfig.type.push('cylinder');
  61237. bodyConfig.size.push(sizeX);
  61238. bodyConfig.size.push(sizeY);
  61239. //due to the way oimo works with compounds, add one more value.
  61240. bodyConfig.size.push(sizeY);
  61241. break;
  61242. case BABYLON.PhysicsImpostor.PlaneImpostor:
  61243. case BABYLON.PhysicsImpostor.BoxImpostor:
  61244. default:
  61245. var sizeX = checkWithEpsilon_1(extendSize.x);
  61246. var sizeY = checkWithEpsilon_1(extendSize.y);
  61247. var sizeZ = checkWithEpsilon_1(extendSize.z);
  61248. bodyConfig.type.push('box');
  61249. bodyConfig.size.push(sizeX);
  61250. bodyConfig.size.push(sizeY);
  61251. bodyConfig.size.push(sizeZ);
  61252. break;
  61253. }
  61254. //actually not needed, but hey...
  61255. i.object.rotationQuaternion = oldQuaternion;
  61256. });
  61257. impostor.physicsBody = new OIMO.Body(bodyConfig).body; //this.world.add(bodyConfig);
  61258. }
  61259. else {
  61260. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  61261. }
  61262. impostor.setDeltaPosition(this._tmpPositionVector);
  61263. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  61264. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  61265. };
  61266. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  61267. //impostor.physicsBody.dispose();
  61268. //Same as : (older oimo versions)
  61269. this.world.removeRigidBody(impostor.physicsBody);
  61270. };
  61271. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  61272. var mainBody = impostorJoint.mainImpostor.physicsBody;
  61273. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  61274. if (!mainBody || !connectedBody) {
  61275. return;
  61276. }
  61277. var jointData = impostorJoint.joint.jointData;
  61278. var options = jointData.nativeParams || {};
  61279. var type;
  61280. var nativeJointData = {
  61281. body1: mainBody,
  61282. body2: connectedBody,
  61283. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  61284. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  61285. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  61286. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  61287. min: options.min,
  61288. max: options.max,
  61289. collision: options.collision || jointData.collision,
  61290. spring: options.spring,
  61291. //supporting older version of Oimo
  61292. world: this.world
  61293. };
  61294. switch (impostorJoint.joint.type) {
  61295. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  61296. type = "jointBall";
  61297. break;
  61298. case BABYLON.PhysicsJoint.SpringJoint:
  61299. BABYLON.Tools.Warn("Oimo.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  61300. var springData = jointData;
  61301. nativeJointData.min = springData.length || nativeJointData.min;
  61302. //Max should also be set, just make sure it is at least min
  61303. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  61304. case BABYLON.PhysicsJoint.DistanceJoint:
  61305. type = "jointDistance";
  61306. nativeJointData.max = jointData.maxDistance;
  61307. break;
  61308. case BABYLON.PhysicsJoint.PrismaticJoint:
  61309. type = "jointPrisme";
  61310. break;
  61311. case BABYLON.PhysicsJoint.SliderJoint:
  61312. type = "jointSlide";
  61313. break;
  61314. case BABYLON.PhysicsJoint.WheelJoint:
  61315. type = "jointWheel";
  61316. break;
  61317. case BABYLON.PhysicsJoint.HingeJoint:
  61318. default:
  61319. type = "jointHinge";
  61320. break;
  61321. }
  61322. nativeJointData.type = type;
  61323. impostorJoint.joint.physicsJoint = new OIMO.Link(nativeJointData).joint; //this.world.add(nativeJointData);
  61324. };
  61325. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  61326. //Bug in Oimo prevents us from disposing a joint in the playground
  61327. //joint.joint.physicsJoint.dispose();
  61328. //So we will bruteforce it!
  61329. try {
  61330. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  61331. }
  61332. catch (e) {
  61333. BABYLON.Tools.Warn(e);
  61334. }
  61335. };
  61336. OimoJSPlugin.prototype.isSupported = function () {
  61337. return OIMO !== undefined;
  61338. };
  61339. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  61340. if (!impostor.physicsBody.sleeping) {
  61341. //TODO check that
  61342. if (impostor.physicsBody.shapes.next) {
  61343. var parentShape = this._getLastShape(impostor.physicsBody);
  61344. impostor.object.position.x = parentShape.position.x * OIMO.WORLD_SCALE;
  61345. impostor.object.position.y = parentShape.position.y * OIMO.WORLD_SCALE;
  61346. impostor.object.position.z = parentShape.position.z * OIMO.WORLD_SCALE;
  61347. }
  61348. else {
  61349. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  61350. }
  61351. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  61352. impostor.object.rotationQuaternion.normalize();
  61353. }
  61354. };
  61355. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  61356. var body = impostor.physicsBody;
  61357. body.position.init(newPosition.x * OIMO.INV_SCALE, newPosition.y * OIMO.INV_SCALE, newPosition.z * OIMO.INV_SCALE);
  61358. body.orientation.init(newRotation.w, newRotation.x, newRotation.y, newRotation.z);
  61359. body.syncShapes();
  61360. body.awake();
  61361. };
  61362. OimoJSPlugin.prototype._getLastShape = function (body) {
  61363. var lastShape = body.shapes;
  61364. while (lastShape.next) {
  61365. lastShape = lastShape.next;
  61366. }
  61367. return lastShape;
  61368. };
  61369. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  61370. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  61371. };
  61372. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  61373. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  61374. };
  61375. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  61376. var v = impostor.physicsBody.linearVelocity;
  61377. if (!v)
  61378. return null;
  61379. return new BABYLON.Vector3(v.x, v.y, v.z);
  61380. };
  61381. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  61382. var v = impostor.physicsBody.angularVelocity;
  61383. if (!v)
  61384. return null;
  61385. return new BABYLON.Vector3(v.x, v.y, v.z);
  61386. };
  61387. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  61388. var staticBody = mass === 0;
  61389. //this will actually set the body's density and not its mass.
  61390. //But this is how oimo treats the mass variable.
  61391. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  61392. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  61393. };
  61394. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  61395. return impostor.physicsBody.shapes.density;
  61396. };
  61397. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  61398. return impostor.physicsBody.shapes.friction;
  61399. };
  61400. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  61401. impostor.physicsBody.shapes.friction = friction;
  61402. };
  61403. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  61404. return impostor.physicsBody.shapes.restitution;
  61405. };
  61406. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  61407. impostor.physicsBody.shapes.restitution = restitution;
  61408. };
  61409. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  61410. impostor.physicsBody.sleep();
  61411. };
  61412. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  61413. impostor.physicsBody.awake();
  61414. };
  61415. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  61416. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  61417. if (minDistance !== void 0) {
  61418. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  61419. }
  61420. };
  61421. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  61422. //TODO separate rotational and transational motors.
  61423. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61424. if (motor) {
  61425. motor.setMotor(speed, maxForce);
  61426. }
  61427. };
  61428. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  61429. //TODO separate rotational and transational motors.
  61430. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  61431. if (motor) {
  61432. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  61433. }
  61434. };
  61435. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  61436. var body = impostor.physicsBody;
  61437. mesh.position.x = body.position.x;
  61438. mesh.position.y = body.position.y;
  61439. mesh.position.z = body.position.z;
  61440. mesh.rotationQuaternion.x = body.orientation.x;
  61441. mesh.rotationQuaternion.y = body.orientation.y;
  61442. mesh.rotationQuaternion.z = body.orientation.z;
  61443. mesh.rotationQuaternion.w = body.orientation.s;
  61444. };
  61445. OimoJSPlugin.prototype.getRadius = function (impostor) {
  61446. return impostor.physicsBody.shapes.radius;
  61447. };
  61448. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  61449. var shape = impostor.physicsBody.shapes;
  61450. result.x = shape.halfWidth * 2;
  61451. result.y = shape.halfHeight * 2;
  61452. result.z = shape.halfDepth * 2;
  61453. };
  61454. OimoJSPlugin.prototype.dispose = function () {
  61455. this.world.clear();
  61456. };
  61457. return OimoJSPlugin;
  61458. }());
  61459. BABYLON.OimoJSPlugin = OimoJSPlugin;
  61460. })(BABYLON || (BABYLON = {}));
  61461. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  61462. var BABYLON;
  61463. (function (BABYLON) {
  61464. var Internals;
  61465. (function (Internals) {
  61466. /*
  61467. * Based on jsTGALoader - Javascript loader for TGA file
  61468. * By Vincent Thibault
  61469. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  61470. */
  61471. var TGATools = (function () {
  61472. function TGATools() {
  61473. }
  61474. TGATools.GetTGAHeader = function (data) {
  61475. var offset = 0;
  61476. var header = {
  61477. id_length: data[offset++],
  61478. colormap_type: data[offset++],
  61479. image_type: data[offset++],
  61480. colormap_index: data[offset++] | data[offset++] << 8,
  61481. colormap_length: data[offset++] | data[offset++] << 8,
  61482. colormap_size: data[offset++],
  61483. origin: [
  61484. data[offset++] | data[offset++] << 8,
  61485. data[offset++] | data[offset++] << 8
  61486. ],
  61487. width: data[offset++] | data[offset++] << 8,
  61488. height: data[offset++] | data[offset++] << 8,
  61489. pixel_size: data[offset++],
  61490. flags: data[offset++]
  61491. };
  61492. return header;
  61493. };
  61494. TGATools.UploadContent = function (gl, data) {
  61495. // Not enough data to contain header ?
  61496. if (data.length < 19) {
  61497. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  61498. return;
  61499. }
  61500. // Read Header
  61501. var offset = 18;
  61502. var header = TGATools.GetTGAHeader(data);
  61503. // Assume it's a valid Targa file.
  61504. if (header.id_length + offset > data.length) {
  61505. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  61506. return;
  61507. }
  61508. // Skip not needed data
  61509. offset += header.id_length;
  61510. var use_rle = false;
  61511. var use_pal = false;
  61512. var use_rgb = false;
  61513. var use_grey = false;
  61514. // Get some informations.
  61515. switch (header.image_type) {
  61516. case TGATools._TYPE_RLE_INDEXED:
  61517. use_rle = true;
  61518. case TGATools._TYPE_INDEXED:
  61519. use_pal = true;
  61520. break;
  61521. case TGATools._TYPE_RLE_RGB:
  61522. use_rle = true;
  61523. case TGATools._TYPE_RGB:
  61524. use_rgb = true;
  61525. break;
  61526. case TGATools._TYPE_RLE_GREY:
  61527. use_rle = true;
  61528. case TGATools._TYPE_GREY:
  61529. use_grey = true;
  61530. break;
  61531. }
  61532. var pixel_data;
  61533. var numAlphaBits = header.flags & 0xf;
  61534. var pixel_size = header.pixel_size >> 3;
  61535. var pixel_total = header.width * header.height * pixel_size;
  61536. // Read palettes
  61537. var palettes;
  61538. if (use_pal) {
  61539. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  61540. }
  61541. // Read LRE
  61542. if (use_rle) {
  61543. pixel_data = new Uint8Array(pixel_total);
  61544. var c, count, i;
  61545. var localOffset = 0;
  61546. var pixels = new Uint8Array(pixel_size);
  61547. while (offset < pixel_total && localOffset < pixel_total) {
  61548. c = data[offset++];
  61549. count = (c & 0x7f) + 1;
  61550. // RLE pixels
  61551. if (c & 0x80) {
  61552. // Bind pixel tmp array
  61553. for (i = 0; i < pixel_size; ++i) {
  61554. pixels[i] = data[offset++];
  61555. }
  61556. // Copy pixel array
  61557. for (i = 0; i < count; ++i) {
  61558. pixel_data.set(pixels, localOffset + i * pixel_size);
  61559. }
  61560. localOffset += pixel_size * count;
  61561. }
  61562. else {
  61563. count *= pixel_size;
  61564. for (i = 0; i < count; ++i) {
  61565. pixel_data[localOffset + i] = data[offset++];
  61566. }
  61567. localOffset += count;
  61568. }
  61569. }
  61570. }
  61571. else {
  61572. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  61573. }
  61574. // Load to texture
  61575. var x_start, y_start, x_step, y_step, y_end, x_end;
  61576. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  61577. default:
  61578. case TGATools._ORIGIN_UL:
  61579. x_start = 0;
  61580. x_step = 1;
  61581. x_end = header.width;
  61582. y_start = 0;
  61583. y_step = 1;
  61584. y_end = header.height;
  61585. break;
  61586. case TGATools._ORIGIN_BL:
  61587. x_start = 0;
  61588. x_step = 1;
  61589. x_end = header.width;
  61590. y_start = header.height - 1;
  61591. y_step = -1;
  61592. y_end = -1;
  61593. break;
  61594. case TGATools._ORIGIN_UR:
  61595. x_start = header.width - 1;
  61596. x_step = -1;
  61597. x_end = -1;
  61598. y_start = 0;
  61599. y_step = 1;
  61600. y_end = header.height;
  61601. break;
  61602. case TGATools._ORIGIN_BR:
  61603. x_start = header.width - 1;
  61604. x_step = -1;
  61605. x_end = -1;
  61606. y_start = header.height - 1;
  61607. y_step = -1;
  61608. y_end = -1;
  61609. break;
  61610. }
  61611. // Load the specify method
  61612. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  61613. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  61614. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  61615. };
  61616. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61617. var image = pixel_data, colormap = palettes;
  61618. var width = header.width, height = header.height;
  61619. var color, i = 0, x, y;
  61620. var imageData = new Uint8Array(width * height * 4);
  61621. for (y = y_start; y !== y_end; y += y_step) {
  61622. for (x = x_start; x !== x_end; x += x_step, i++) {
  61623. color = image[i];
  61624. imageData[(x + width * y) * 4 + 3] = 255;
  61625. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  61626. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  61627. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  61628. }
  61629. }
  61630. return imageData;
  61631. };
  61632. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61633. var image = pixel_data;
  61634. var width = header.width, height = header.height;
  61635. var color, i = 0, x, y;
  61636. var imageData = new Uint8Array(width * height * 4);
  61637. for (y = y_start; y !== y_end; y += y_step) {
  61638. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61639. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  61640. imageData[(x + width * y) * 4 + 0] = (color & 0x7C00) >> 7;
  61641. imageData[(x + width * y) * 4 + 1] = (color & 0x03E0) >> 2;
  61642. imageData[(x + width * y) * 4 + 2] = (color & 0x001F) >> 3;
  61643. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  61644. }
  61645. }
  61646. return imageData;
  61647. };
  61648. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61649. var image = pixel_data;
  61650. var width = header.width, height = header.height;
  61651. var i = 0, x, y;
  61652. var imageData = new Uint8Array(width * height * 4);
  61653. for (y = y_start; y !== y_end; y += y_step) {
  61654. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  61655. imageData[(x + width * y) * 4 + 3] = 255;
  61656. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61657. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61658. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61659. }
  61660. }
  61661. return imageData;
  61662. };
  61663. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61664. var image = pixel_data;
  61665. var width = header.width, height = header.height;
  61666. var i = 0, x, y;
  61667. var imageData = new Uint8Array(width * height * 4);
  61668. for (y = y_start; y !== y_end; y += y_step) {
  61669. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  61670. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61671. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  61672. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  61673. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  61674. }
  61675. }
  61676. return imageData;
  61677. };
  61678. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61679. var image = pixel_data;
  61680. var width = header.width, height = header.height;
  61681. var color, i = 0, x, y;
  61682. var imageData = new Uint8Array(width * height * 4);
  61683. for (y = y_start; y !== y_end; y += y_step) {
  61684. for (x = x_start; x !== x_end; x += x_step, i++) {
  61685. color = image[i];
  61686. imageData[(x + width * y) * 4 + 0] = color;
  61687. imageData[(x + width * y) * 4 + 1] = color;
  61688. imageData[(x + width * y) * 4 + 2] = color;
  61689. imageData[(x + width * y) * 4 + 3] = 255;
  61690. }
  61691. }
  61692. return imageData;
  61693. };
  61694. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  61695. var image = pixel_data;
  61696. var width = header.width, height = header.height;
  61697. var i = 0, x, y;
  61698. var imageData = new Uint8Array(width * height * 4);
  61699. for (y = y_start; y !== y_end; y += y_step) {
  61700. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  61701. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  61702. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  61703. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  61704. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  61705. }
  61706. }
  61707. return imageData;
  61708. };
  61709. TGATools._TYPE_NO_DATA = 0;
  61710. TGATools._TYPE_INDEXED = 1;
  61711. TGATools._TYPE_RGB = 2;
  61712. TGATools._TYPE_GREY = 3;
  61713. TGATools._TYPE_RLE_INDEXED = 9;
  61714. TGATools._TYPE_RLE_RGB = 10;
  61715. TGATools._TYPE_RLE_GREY = 11;
  61716. TGATools._ORIGIN_MASK = 0x30;
  61717. TGATools._ORIGIN_SHIFT = 0x04;
  61718. TGATools._ORIGIN_BL = 0x00;
  61719. TGATools._ORIGIN_BR = 0x01;
  61720. TGATools._ORIGIN_UL = 0x02;
  61721. TGATools._ORIGIN_UR = 0x03;
  61722. return TGATools;
  61723. }());
  61724. Internals.TGATools = TGATools;
  61725. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  61726. })(BABYLON || (BABYLON = {}));
  61727. //# sourceMappingURL=babylon.tga.js.map
  61728. var BABYLON;
  61729. (function (BABYLON) {
  61730. var Internals;
  61731. (function (Internals) {
  61732. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  61733. // All values and structures referenced from:
  61734. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  61735. var DDS_MAGIC = 0x20534444;
  61736. 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;
  61737. var DDSCAPS_COMPLEX = 0x8, DDSCAPS_MIPMAP = 0x400000, DDSCAPS_TEXTURE = 0x1000;
  61738. 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;
  61739. var DDPF_ALPHAPIXELS = 0x1, DDPF_ALPHA = 0x2, DDPF_FOURCC = 0x4, DDPF_RGB = 0x40, DDPF_YUV = 0x200, DDPF_LUMINANCE = 0x20000;
  61740. function FourCCToInt32(value) {
  61741. return value.charCodeAt(0) +
  61742. (value.charCodeAt(1) << 8) +
  61743. (value.charCodeAt(2) << 16) +
  61744. (value.charCodeAt(3) << 24);
  61745. }
  61746. function Int32ToFourCC(value) {
  61747. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  61748. }
  61749. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  61750. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  61751. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  61752. var FOURCC_DX10 = FourCCToInt32("DX10");
  61753. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  61754. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  61755. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  61756. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  61757. var headerLengthInt = 31; // The header length in 32 bit ints
  61758. // Offsets into the header array
  61759. var off_magic = 0;
  61760. var off_size = 1;
  61761. var off_flags = 2;
  61762. var off_height = 3;
  61763. var off_width = 4;
  61764. var off_mipmapCount = 7;
  61765. var off_pfFlags = 20;
  61766. var off_pfFourCC = 21;
  61767. var off_RGBbpp = 22;
  61768. var off_RMask = 23;
  61769. var off_GMask = 24;
  61770. var off_BMask = 25;
  61771. var off_AMask = 26;
  61772. var off_caps1 = 27;
  61773. var off_caps2 = 28;
  61774. var off_caps3 = 29;
  61775. var off_caps4 = 30;
  61776. var off_dxgiFormat = 32;
  61777. ;
  61778. var DDSTools = (function () {
  61779. function DDSTools() {
  61780. }
  61781. DDSTools.GetDDSInfo = function (arrayBuffer) {
  61782. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  61783. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  61784. var mipmapCount = 1;
  61785. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  61786. mipmapCount = Math.max(1, header[off_mipmapCount]);
  61787. }
  61788. var fourCC = header[off_pfFourCC];
  61789. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  61790. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  61791. switch (fourCC) {
  61792. case FOURCC_D3DFMT_R16G16B16A16F:
  61793. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61794. break;
  61795. case FOURCC_D3DFMT_R32G32B32A32F:
  61796. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  61797. break;
  61798. case FOURCC_DX10:
  61799. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  61800. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  61801. break;
  61802. }
  61803. }
  61804. return {
  61805. width: header[off_width],
  61806. height: header[off_height],
  61807. mipmapCount: mipmapCount,
  61808. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  61809. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  61810. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  61811. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  61812. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || FOURCC_DXT1 === FOURCC_DXT5),
  61813. dxgiFormat: dxgiFormat,
  61814. textureType: textureType
  61815. };
  61816. };
  61817. DDSTools._ToHalfFloat = function (value) {
  61818. if (!DDSTools._FloatView) {
  61819. DDSTools._FloatView = new Float32Array(1);
  61820. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  61821. }
  61822. DDSTools._FloatView[0] = value;
  61823. var x = DDSTools._Int32View[0];
  61824. var bits = (x >> 16) & 0x8000; /* Get the sign */
  61825. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  61826. var e = (x >> 23) & 0xff; /* Using int is faster here */
  61827. /* If zero, or denormal, or exponent underflows too much for a denormal
  61828. * half, return signed zero. */
  61829. if (e < 103) {
  61830. return bits;
  61831. }
  61832. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  61833. if (e > 142) {
  61834. bits |= 0x7c00;
  61835. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  61836. * not Inf, so make sure we set one mantissa bit too. */
  61837. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  61838. return bits;
  61839. }
  61840. /* If exponent underflows but not too much, return a denormal */
  61841. if (e < 113) {
  61842. m |= 0x0800;
  61843. /* Extra rounding may overflow and set mantissa to 0 and exponent
  61844. * to 1, which is OK. */
  61845. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  61846. return bits;
  61847. }
  61848. bits |= ((e - 112) << 10) | (m >> 1);
  61849. bits += m & 1;
  61850. return bits;
  61851. };
  61852. DDSTools._FromHalfFloat = function (value) {
  61853. var s = (value & 0x8000) >> 15;
  61854. var e = (value & 0x7C00) >> 10;
  61855. var f = value & 0x03FF;
  61856. if (e === 0) {
  61857. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  61858. }
  61859. else if (e == 0x1F) {
  61860. return f ? NaN : ((s ? -1 : 1) * Infinity);
  61861. }
  61862. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  61863. };
  61864. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61865. var destArray = new Float32Array(dataLength);
  61866. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61867. var index = 0;
  61868. for (var y = 0; y < height; y++) {
  61869. for (var x = 0; x < width; x++) {
  61870. var srcPos = (x + y * width) * 4;
  61871. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  61872. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  61873. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  61874. if (DDSTools.StoreLODInAlphaChannel) {
  61875. destArray[index + 3] = lod;
  61876. }
  61877. else {
  61878. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  61879. }
  61880. index += 4;
  61881. }
  61882. }
  61883. return destArray;
  61884. };
  61885. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61886. if (DDSTools.StoreLODInAlphaChannel) {
  61887. var destArray = new Uint16Array(dataLength);
  61888. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61889. var index = 0;
  61890. for (var y = 0; y < height; y++) {
  61891. for (var x = 0; x < width; x++) {
  61892. var srcPos = (x + y * width) * 4;
  61893. destArray[index] = srcData[srcPos];
  61894. destArray[index + 1] = srcData[srcPos + 1];
  61895. destArray[index + 2] = srcData[srcPos + 2];
  61896. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  61897. index += 4;
  61898. }
  61899. }
  61900. return destArray;
  61901. }
  61902. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  61903. };
  61904. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61905. if (DDSTools.StoreLODInAlphaChannel) {
  61906. var destArray = new Float32Array(dataLength);
  61907. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61908. var index = 0;
  61909. for (var y = 0; y < height; y++) {
  61910. for (var x = 0; x < width; x++) {
  61911. var srcPos = (x + y * width) * 4;
  61912. destArray[index] = srcData[srcPos];
  61913. destArray[index + 1] = srcData[srcPos + 1];
  61914. destArray[index + 2] = srcData[srcPos + 2];
  61915. destArray[index + 3] = lod;
  61916. index += 4;
  61917. }
  61918. }
  61919. return destArray;
  61920. }
  61921. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  61922. };
  61923. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61924. var destArray = new Uint8Array(dataLength);
  61925. var srcData = new Float32Array(arrayBuffer, dataOffset);
  61926. var index = 0;
  61927. for (var y = 0; y < height; y++) {
  61928. for (var x = 0; x < width; x++) {
  61929. var srcPos = (x + y * width) * 4;
  61930. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  61931. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  61932. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  61933. if (DDSTools.StoreLODInAlphaChannel) {
  61934. destArray[index + 3] = lod;
  61935. }
  61936. else {
  61937. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  61938. }
  61939. index += 4;
  61940. }
  61941. }
  61942. return destArray;
  61943. };
  61944. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  61945. var destArray = new Uint8Array(dataLength);
  61946. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  61947. var index = 0;
  61948. for (var y = 0; y < height; y++) {
  61949. for (var x = 0; x < width; x++) {
  61950. var srcPos = (x + y * width) * 4;
  61951. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  61952. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  61953. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  61954. if (DDSTools.StoreLODInAlphaChannel) {
  61955. destArray[index + 3] = lod;
  61956. }
  61957. else {
  61958. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  61959. }
  61960. index += 4;
  61961. }
  61962. }
  61963. return destArray;
  61964. };
  61965. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61966. var byteArray = new Uint8Array(dataLength);
  61967. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61968. var index = 0;
  61969. for (var y = 0; y < height; y++) {
  61970. for (var x = 0; x < width; x++) {
  61971. var srcPos = (x + y * width) * 4;
  61972. byteArray[index] = srcData[srcPos + 2];
  61973. byteArray[index + 1] = srcData[srcPos + 1];
  61974. byteArray[index + 2] = srcData[srcPos];
  61975. byteArray[index + 3] = srcData[srcPos + 3];
  61976. index += 4;
  61977. }
  61978. }
  61979. return byteArray;
  61980. };
  61981. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61982. var byteArray = new Uint8Array(dataLength);
  61983. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61984. var index = 0;
  61985. for (var y = 0; y < height; y++) {
  61986. for (var x = 0; x < width; x++) {
  61987. var srcPos = (x + y * width) * 3;
  61988. byteArray[index] = srcData[srcPos + 2];
  61989. byteArray[index + 1] = srcData[srcPos + 1];
  61990. byteArray[index + 2] = srcData[srcPos];
  61991. index += 3;
  61992. }
  61993. }
  61994. return byteArray;
  61995. };
  61996. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  61997. var byteArray = new Uint8Array(dataLength);
  61998. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  61999. var index = 0;
  62000. for (var y = 0; y < height; y++) {
  62001. for (var x = 0; x < width; x++) {
  62002. var srcPos = (x + y * width);
  62003. byteArray[index] = srcData[srcPos];
  62004. index++;
  62005. }
  62006. }
  62007. return byteArray;
  62008. };
  62009. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex) {
  62010. if (lodIndex === void 0) { lodIndex = -1; }
  62011. var ext = engine.getCaps().s3tc;
  62012. var header = new Int32Array(arrayBuffer, 0, headerLengthInt), fourCC, blockBytes, internalFormat, format, width, height, dataLength, dataOffset, byteArray, mipmapCount, mip;
  62013. if (header[off_magic] != DDS_MAGIC) {
  62014. BABYLON.Tools.Error("Invalid magic number in DDS header");
  62015. return;
  62016. }
  62017. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  62018. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  62019. return;
  62020. }
  62021. if (info.isCompressed && !ext) {
  62022. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  62023. return;
  62024. }
  62025. var bpp = header[off_RGBbpp];
  62026. dataOffset = header[off_size] + 4;
  62027. var computeFormats = false;
  62028. if (info.isFourCC) {
  62029. fourCC = header[off_pfFourCC];
  62030. switch (fourCC) {
  62031. case FOURCC_DXT1:
  62032. blockBytes = 8;
  62033. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  62034. break;
  62035. case FOURCC_DXT3:
  62036. blockBytes = 16;
  62037. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  62038. break;
  62039. case FOURCC_DXT5:
  62040. blockBytes = 16;
  62041. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  62042. break;
  62043. case FOURCC_D3DFMT_R16G16B16A16F:
  62044. computeFormats = true;
  62045. break;
  62046. case FOURCC_D3DFMT_R32G32B32A32F:
  62047. computeFormats = true;
  62048. break;
  62049. case FOURCC_DX10:
  62050. // There is an additionnal header so dataOffset need to be changed
  62051. dataOffset += 5 * 4; // 5 uints
  62052. var supported = false;
  62053. switch (info.dxgiFormat) {
  62054. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  62055. computeFormats = true;
  62056. supported = true;
  62057. break;
  62058. case DXGI_FORMAT_B8G8R8X8_UNORM:
  62059. info.isRGB = true;
  62060. info.isFourCC = false;
  62061. bpp = 32;
  62062. supported = true;
  62063. break;
  62064. }
  62065. if (supported) {
  62066. break;
  62067. }
  62068. default:
  62069. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  62070. return;
  62071. }
  62072. }
  62073. if (computeFormats) {
  62074. format = engine._getWebGLTextureType(info.textureType);
  62075. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62076. }
  62077. mipmapCount = 1;
  62078. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  62079. mipmapCount = Math.max(1, header[off_mipmapCount]);
  62080. }
  62081. for (var face = 0; face < faces; face++) {
  62082. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62083. width = header[off_width];
  62084. height = header[off_height];
  62085. for (mip = 0; mip < mipmapCount; ++mip) {
  62086. if (lodIndex === -1 || lodIndex === mip) {
  62087. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  62088. var i = (lodIndex === -1) ? mip : 0;
  62089. if (!info.isCompressed && info.isFourCC) {
  62090. dataLength = width * height * 4;
  62091. var floatArray;
  62092. if (engine.badOS || engine.badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) {
  62093. if (bpp === 128) {
  62094. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62095. }
  62096. else if (bpp === 64) {
  62097. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62098. }
  62099. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  62100. format = engine._getWebGLTextureType(info.textureType);
  62101. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62102. }
  62103. else {
  62104. if (bpp === 128) {
  62105. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62106. }
  62107. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  62108. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62109. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  62110. format = engine._getWebGLTextureType(info.textureType);
  62111. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  62112. }
  62113. else {
  62114. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  62115. }
  62116. }
  62117. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  62118. }
  62119. else if (info.isRGB) {
  62120. if (bpp === 24) {
  62121. dataLength = width * height * 3;
  62122. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62123. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  62124. }
  62125. else {
  62126. dataLength = width * height * 4;
  62127. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62128. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  62129. }
  62130. }
  62131. else if (info.isLuminance) {
  62132. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  62133. var unpaddedRowSize = width;
  62134. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  62135. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  62136. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  62137. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  62138. }
  62139. else {
  62140. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  62141. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  62142. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  62143. }
  62144. }
  62145. dataOffset += width * height * (bpp / 8);
  62146. width *= 0.5;
  62147. height *= 0.5;
  62148. width = Math.max(1.0, width);
  62149. height = Math.max(1.0, height);
  62150. }
  62151. }
  62152. };
  62153. DDSTools.StoreLODInAlphaChannel = false;
  62154. return DDSTools;
  62155. }());
  62156. Internals.DDSTools = DDSTools;
  62157. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62158. })(BABYLON || (BABYLON = {}));
  62159. //# sourceMappingURL=babylon.dds.js.map
  62160. var BABYLON;
  62161. (function (BABYLON) {
  62162. var Internals;
  62163. (function (Internals) {
  62164. /**
  62165. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  62166. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  62167. */
  62168. var KhronosTextureContainer = (function () {
  62169. /**
  62170. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  62171. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  62172. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  62173. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  62174. */
  62175. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  62176. this.arrayBuffer = arrayBuffer;
  62177. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  62178. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  62179. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  62180. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  62181. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  62182. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  62183. BABYLON.Tools.Error("texture missing KTX identifier");
  62184. return;
  62185. }
  62186. // load the reset of the header in native 32 bit int
  62187. var header = new Int32Array(this.arrayBuffer, 12, 13);
  62188. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  62189. var oppositeEndianess = header[0] === 0x01020304;
  62190. // read all the header elements in order they exist in the file, without modification (sans endainness)
  62191. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  62192. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  62193. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  62194. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  62195. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  62196. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  62197. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  62198. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  62199. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  62200. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  62201. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  62202. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  62203. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  62204. if (this.glType !== 0) {
  62205. BABYLON.Tools.Error("only compressed formats currently supported");
  62206. return;
  62207. }
  62208. else {
  62209. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  62210. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  62211. }
  62212. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  62213. BABYLON.Tools.Error("only 2D textures currently supported");
  62214. return;
  62215. }
  62216. if (this.numberOfArrayElements !== 0) {
  62217. BABYLON.Tools.Error("texture arrays not currently supported");
  62218. return;
  62219. }
  62220. if (this.numberOfFaces !== facesExpected) {
  62221. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  62222. return;
  62223. }
  62224. // we now have a completely validated file, so could use existence of loadType as success
  62225. // would need to make this more elaborate & adjust checks above to support more than one load type
  62226. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  62227. }
  62228. // not as fast hardware based, but will probably never need to use
  62229. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  62230. return ((val & 0xFF) << 24)
  62231. | ((val & 0xFF00) << 8)
  62232. | ((val >> 8) & 0xFF00)
  62233. | ((val >> 24) & 0xFF);
  62234. };
  62235. /**
  62236. * It is assumed that the texture has already been created & is currently bound
  62237. */
  62238. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  62239. switch (this.loadType) {
  62240. case KhronosTextureContainer.COMPRESSED_2D:
  62241. this._upload2DCompressedLevels(gl, loadMipmaps);
  62242. break;
  62243. case KhronosTextureContainer.TEX_2D:
  62244. case KhronosTextureContainer.COMPRESSED_3D:
  62245. case KhronosTextureContainer.TEX_3D:
  62246. }
  62247. };
  62248. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  62249. // initialize width & height for level 1
  62250. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  62251. var width = this.pixelWidth;
  62252. var height = this.pixelHeight;
  62253. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  62254. for (var level = 0; level < mipmapCount; level++) {
  62255. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  62256. for (var face = 0; face < this.numberOfFaces; face++) {
  62257. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  62258. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  62259. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  62260. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  62261. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  62262. }
  62263. width = Math.max(1.0, width * 0.5);
  62264. height = Math.max(1.0, height * 0.5);
  62265. }
  62266. };
  62267. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  62268. // load types
  62269. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  62270. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  62271. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  62272. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  62273. return KhronosTextureContainer;
  62274. }());
  62275. Internals.KhronosTextureContainer = KhronosTextureContainer;
  62276. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  62277. })(BABYLON || (BABYLON = {}));
  62278. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  62279. var BABYLON;
  62280. (function (BABYLON) {
  62281. var DynamicFloatArrayElementInfo = (function () {
  62282. function DynamicFloatArrayElementInfo() {
  62283. }
  62284. return DynamicFloatArrayElementInfo;
  62285. }());
  62286. BABYLON.DynamicFloatArrayElementInfo = DynamicFloatArrayElementInfo;
  62287. /**
  62288. * 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.
  62289. * The intent is to maintain through time data that will be bound to a WebGlBuffer with the ability to change add/remove elements.
  62290. * It was first built to efficiently maintain the WebGlBuffer that contain instancing based data.
  62291. * 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.
  62292. * 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.
  62293. * 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".
  62294. */
  62295. var DynamicFloatArray = (function () {
  62296. /**
  62297. * Construct an instance of the dynamic float array
  62298. * @param stride size of one element in float (i.e. not bytes!)
  62299. * @param initialElementCount the number of available entries at construction
  62300. */
  62301. function DynamicFloatArray(stride, initialElementCount) {
  62302. this.compareValueOffset = null;
  62303. this.sortingAscending = true;
  62304. this._stride = stride;
  62305. this.buffer = new Float32Array(stride * initialElementCount);
  62306. this._lastUsed = 0;
  62307. this._firstFree = 0;
  62308. this._allEntries = new Array(initialElementCount);
  62309. this._freeEntries = new Array(initialElementCount);
  62310. for (var i = 0; i < initialElementCount; i++) {
  62311. var element = new DynamicFloatArrayElementInfo();
  62312. element.offset = i * stride;
  62313. this._allEntries[i] = element;
  62314. this._freeEntries[initialElementCount - i - 1] = element;
  62315. }
  62316. }
  62317. /**
  62318. * Allocate an element in the array.
  62319. * @return the element info instance that contains the offset into the main buffer of the element's location.
  62320. * Beware, this offset may change when you call pack()
  62321. */
  62322. DynamicFloatArray.prototype.allocElement = function () {
  62323. if (this._freeEntries.length === 0) {
  62324. this._growBuffer();
  62325. }
  62326. var el = this._freeEntries.pop();
  62327. this._lastUsed = Math.max(el.offset, this._lastUsed);
  62328. if (el.offset === this._firstFree) {
  62329. if (this._freeEntries.length > 0) {
  62330. this._firstFree = this._freeEntries[this._freeEntries.length - 1].offset;
  62331. }
  62332. else {
  62333. this._firstFree += this._stride;
  62334. }
  62335. }
  62336. return el;
  62337. };
  62338. /**
  62339. * Free the element corresponding to the given element info
  62340. * @param elInfo the element that describe the allocated element
  62341. */
  62342. DynamicFloatArray.prototype.freeElement = function (elInfo) {
  62343. this._firstFree = Math.min(elInfo.offset, this._firstFree);
  62344. this._freeEntries.push(elInfo);
  62345. };
  62346. /**
  62347. * This method will pack all the used elements into a linear sequence and put all the free space at the end.
  62348. * 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().
  62349. * @return the subArray that is the view of the used elements area, you can use it as a source to update a WebGLBuffer
  62350. */
  62351. DynamicFloatArray.prototype.pack = function () {
  62352. // no free slot? no need to pack
  62353. if (this._freeEntries.length === 0) {
  62354. return this.buffer;
  62355. }
  62356. // If the buffer is already packed the last used will always be lower than the first free
  62357. // 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.
  62358. if (this._lastUsed < this._firstFree) {
  62359. var elementsBuffer_1 = this.buffer.subarray(0, this._lastUsed + this._stride);
  62360. return elementsBuffer_1;
  62361. }
  62362. var s = this._stride;
  62363. // 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
  62364. var lastFree = new DynamicFloatArrayElementInfo();
  62365. lastFree.offset = this.totalElementCount * s;
  62366. this._freeEntries.push(lastFree);
  62367. var sortedFree = this._freeEntries.sort(function (a, b) { return a.offset - b.offset; });
  62368. var sortedAll = this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62369. var firstFreeSlotOffset = sortedFree[0].offset;
  62370. var freeZoneSize = 1;
  62371. var occupiedZoneSize = (this.usedElementCount + 1) * s;
  62372. var prevOffset = sortedFree[0].offset;
  62373. for (var i = 1; i < sortedFree.length; i++) {
  62374. // 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
  62375. if (firstFreeSlotOffset >= occupiedZoneSize) {
  62376. break;
  62377. }
  62378. var curFree = sortedFree[i];
  62379. var curOffset = curFree.offset;
  62380. // Compute the distance between this offset and the previous
  62381. var distance = curOffset - prevOffset;
  62382. // If the distance is the stride size, they are adjacent, it good, move to the next
  62383. if (distance === s) {
  62384. // Free zone is one element bigger
  62385. ++freeZoneSize;
  62386. // as we're about to iterate to the next, the cur becomes the previous...
  62387. prevOffset = curOffset;
  62388. continue;
  62389. }
  62390. // Distance is bigger, which means there's x element between the previous free and this one
  62391. var usedRange = (distance / s) - 1;
  62392. // Two cases the free zone is smaller than the data to move or bigger
  62393. // Copy what can fit in the free zone
  62394. var curMoveOffset = curOffset - s;
  62395. var copyCount = Math.min(freeZoneSize, usedRange);
  62396. for (var j = 0; j < copyCount; j++) {
  62397. var freeI = firstFreeSlotOffset / s;
  62398. var curI = curMoveOffset / s;
  62399. var moveEl = sortedAll[curI];
  62400. this._moveElement(moveEl, firstFreeSlotOffset);
  62401. var replacedEl = sortedAll[freeI];
  62402. // set the offset of the element we replaced with a value that will make it discard at the end of the method
  62403. replacedEl.offset = curMoveOffset;
  62404. // Swap the element we moved and the one it replaced in the sorted array to reflect the action we've made
  62405. sortedAll[freeI] = moveEl;
  62406. sortedAll[curI] = replacedEl;
  62407. curMoveOffset -= s;
  62408. firstFreeSlotOffset += s;
  62409. }
  62410. // Free Zone is smaller or equal so it's no longer a free zone, set the new one to the current location
  62411. if (freeZoneSize <= usedRange) {
  62412. firstFreeSlotOffset = curMoveOffset + s;
  62413. freeZoneSize = 1 + copyCount;
  62414. }
  62415. else {
  62416. freeZoneSize = ((curOffset - firstFreeSlotOffset) / s) + 1;
  62417. }
  62418. // as we're about to iterate to the next, the cur becomes the previous...
  62419. prevOffset = curOffset;
  62420. }
  62421. var elementsBuffer = this.buffer.subarray(0, firstFreeSlotOffset);
  62422. this._lastUsed = firstFreeSlotOffset - s;
  62423. this._firstFree = firstFreeSlotOffset;
  62424. sortedFree.pop(); // Remove the last free because that's the one we added at the start of the method
  62425. this._freeEntries = sortedFree.sort(function (a, b) { return b.offset - a.offset; });
  62426. this._allEntries = sortedAll;
  62427. return elementsBuffer;
  62428. };
  62429. DynamicFloatArray.prototype._moveElement = function (element, destOffset) {
  62430. for (var i = 0; i < this._stride; i++) {
  62431. this.buffer[destOffset + i] = this.buffer[element.offset + i];
  62432. }
  62433. element.offset = destOffset;
  62434. };
  62435. DynamicFloatArray.prototype._growBuffer = function () {
  62436. // Allocate the new buffer with 50% more entries, copy the content of the current one
  62437. var newElCount = Math.floor(this.totalElementCount * 1.5);
  62438. var newBuffer = new Float32Array(newElCount * this._stride);
  62439. newBuffer.set(this.buffer);
  62440. var curCount = this.totalElementCount;
  62441. var addedCount = newElCount - this.totalElementCount;
  62442. for (var i = 0; i < addedCount; i++) {
  62443. var element = new DynamicFloatArrayElementInfo();
  62444. element.offset = (curCount + i) * this.stride;
  62445. this._allEntries.push(element);
  62446. this._freeEntries[addedCount - i - 1] = element;
  62447. }
  62448. this._firstFree = curCount * this.stride;
  62449. this.buffer = newBuffer;
  62450. };
  62451. Object.defineProperty(DynamicFloatArray.prototype, "totalElementCount", {
  62452. /**
  62453. * Get the total count of entries that can fit in the current buffer
  62454. * @returns the elements count
  62455. */
  62456. get: function () {
  62457. return this._allEntries.length;
  62458. },
  62459. enumerable: true,
  62460. configurable: true
  62461. });
  62462. Object.defineProperty(DynamicFloatArray.prototype, "freeElementCount", {
  62463. /**
  62464. * Get the count of free entries that can still be allocated without resizing the buffer
  62465. * @returns the free elements count
  62466. */
  62467. get: function () {
  62468. return this._freeEntries.length;
  62469. },
  62470. enumerable: true,
  62471. configurable: true
  62472. });
  62473. Object.defineProperty(DynamicFloatArray.prototype, "usedElementCount", {
  62474. /**
  62475. * Get the count of allocated elements
  62476. * @returns the allocated elements count
  62477. */
  62478. get: function () {
  62479. return this._allEntries.length - this._freeEntries.length;
  62480. },
  62481. enumerable: true,
  62482. configurable: true
  62483. });
  62484. Object.defineProperty(DynamicFloatArray.prototype, "stride", {
  62485. /**
  62486. * Return the size of one element in float
  62487. * @returns the size in float
  62488. */
  62489. get: function () {
  62490. return this._stride;
  62491. },
  62492. enumerable: true,
  62493. configurable: true
  62494. });
  62495. DynamicFloatArray.prototype.sort = function () {
  62496. var _this = this;
  62497. if (!this.compareValueOffset) {
  62498. throw new Error("The DynamicFloatArray.sort() method needs a valid 'compareValueOffset' property");
  62499. }
  62500. var count = this.usedElementCount;
  62501. // Do we have to (re)create the sort table?
  62502. if (!this._sortTable || this._sortTable.length < count) {
  62503. // 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...
  62504. var newCount = Math.min(this.totalElementCount, count * 2);
  62505. this._sortTable = new Array(newCount);
  62506. }
  62507. if (!this._sortedTable || this._sortedTable.length !== count) {
  62508. this._sortedTable = new Array(count);
  62509. }
  62510. // Because, you know...
  62511. this.pack();
  62512. //let stride = this.stride;
  62513. //for (let i = 0; i < count; i++) {
  62514. // let si = this._sortTable[i];
  62515. // if (!si) {
  62516. // si = new SortInfo();
  62517. // this._sortTable[i] = si;
  62518. // }
  62519. // si.entry = this._allEntries[i];
  62520. // si.compareData = this.buffer[si.entry.offset + this.compareValueOffset];
  62521. // si.swapedOffset = null;
  62522. // this._sortedTable[i] = si;
  62523. //}
  62524. var curOffset = 0;
  62525. var stride = this.stride;
  62526. for (var i = 0; i < count; i++, curOffset += stride) {
  62527. var si = this._sortTable[i];
  62528. if (!si) {
  62529. si = new SortInfo();
  62530. this._sortTable[i] = si;
  62531. }
  62532. si.compareData = this.buffer[curOffset + this.compareValueOffset];
  62533. si.offset = curOffset;
  62534. si.swapedOffset = null;
  62535. this._sortedTable[i] = si;
  62536. }
  62537. // Let's sort the sorted table, we want to keep a track of the original one (that's why we have two buffers)
  62538. if (this.sortingAscending) {
  62539. this._sortedTable.sort(function (a, b) { return a.compareData - b.compareData; });
  62540. }
  62541. else {
  62542. this._sortedTable.sort(function (a, b) { return b.compareData - a.compareData; });
  62543. }
  62544. var swapElements = function (src, dst) {
  62545. for (var i = 0; i < stride; i++) {
  62546. var tps = _this.buffer[dst + i];
  62547. _this.buffer[dst + i] = _this.buffer[src + i];
  62548. _this.buffer[src + i] = tps;
  62549. }
  62550. };
  62551. // 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:
  62552. // 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),
  62553. // and I still want something with a good algorithm complexity.
  62554. // 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,
  62555. // we need sortTable for that, it contains the original layout of SortInfo object, not the sorted one.
  62556. // The best way is to use an extra field in SortInfo, because potentially every element can be replaced.
  62557. // 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
  62558. // until we find a SortInfo object without a swapedOffset which means we got the right location
  62559. // 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
  62560. // than a double allocation of the whole float32Array or a O(n²/2) typical algorithm.
  62561. for (var i = 0; i < count; i++) {
  62562. // Get the element to move
  62563. var sourceSI = this._sortedTable[i];
  62564. var destSI = this._sortTable[i];
  62565. var sourceOff = sourceSI.offset;
  62566. // If the source changed location, find the new one
  62567. if (sourceSI.swapedOffset) {
  62568. // Follow the swapedOffset until there's none, it will mean that curSI contains the new location in its offset member
  62569. var curSI = sourceSI;
  62570. while (curSI.swapedOffset) {
  62571. curSI = this._sortTable[curSI.swapedOffset / stride];
  62572. }
  62573. // Finally get the right location
  62574. sourceOff = curSI.offset;
  62575. }
  62576. // Tag the element being replaced with its new location
  62577. destSI.swapedOffset = sourceOff;
  62578. // Swap elements (only if needed)
  62579. if (sourceOff !== destSI.offset) {
  62580. swapElements(sourceOff, destSI.offset);
  62581. }
  62582. // Update the offset in the corresponding DFAE
  62583. //sourceSI.entry.offset = destSI.entry.offset;
  62584. this._allEntries[sourceSI.offset / stride].offset = destSI.offset;
  62585. }
  62586. this._allEntries.sort(function (a, b) { return a.offset - b.offset; });
  62587. return true;
  62588. };
  62589. return DynamicFloatArray;
  62590. }());
  62591. BABYLON.DynamicFloatArray = DynamicFloatArray;
  62592. var SortInfo = (function () {
  62593. function SortInfo() {
  62594. this.compareData = this.offset = this.swapedOffset = null;
  62595. }
  62596. return SortInfo;
  62597. }());
  62598. })(BABYLON || (BABYLON = {}));
  62599. //# sourceMappingURL=babylon.dynamicFloatArray.js.map
  62600. var BABYLON;
  62601. (function (BABYLON) {
  62602. var Debug;
  62603. (function (Debug) {
  62604. /**
  62605. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  62606. */
  62607. var SkeletonViewer = (function () {
  62608. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  62609. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  62610. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  62611. this.skeleton = skeleton;
  62612. this.mesh = mesh;
  62613. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  62614. this.renderingGroupId = renderingGroupId;
  62615. this.color = BABYLON.Color3.White();
  62616. this._debugLines = [];
  62617. this._isEnabled = false;
  62618. this._scene = scene;
  62619. this.update();
  62620. this._renderFunction = this.update.bind(this);
  62621. }
  62622. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  62623. get: function () {
  62624. return this._isEnabled;
  62625. },
  62626. set: function (value) {
  62627. if (this._isEnabled === value) {
  62628. return;
  62629. }
  62630. this._isEnabled = value;
  62631. if (value) {
  62632. this._scene.registerBeforeRender(this._renderFunction);
  62633. }
  62634. else {
  62635. this._scene.unregisterBeforeRender(this._renderFunction);
  62636. }
  62637. },
  62638. enumerable: true,
  62639. configurable: true
  62640. });
  62641. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  62642. if (x === void 0) { x = 0; }
  62643. if (y === void 0) { y = 0; }
  62644. if (z === void 0) { z = 0; }
  62645. var tmat = BABYLON.Tmp.Matrix[0];
  62646. var parentBone = bone.getParent();
  62647. tmat.copyFrom(bone.getLocalMatrix());
  62648. if (x !== 0 || y !== 0 || z !== 0) {
  62649. var tmat2 = BABYLON.Tmp.Matrix[1];
  62650. BABYLON.Matrix.IdentityToRef(tmat2);
  62651. tmat2.m[12] = x;
  62652. tmat2.m[13] = y;
  62653. tmat2.m[14] = z;
  62654. tmat2.multiplyToRef(tmat, tmat);
  62655. }
  62656. if (parentBone) {
  62657. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  62658. }
  62659. tmat.multiplyToRef(meshMat, tmat);
  62660. position.x = tmat.m[12];
  62661. position.y = tmat.m[13];
  62662. position.z = tmat.m[14];
  62663. };
  62664. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  62665. var len = bones.length;
  62666. var meshPos = this.mesh.position;
  62667. for (var i = 0; i < len; i++) {
  62668. var bone = bones[i];
  62669. var points = this._debugLines[i];
  62670. if (!points) {
  62671. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62672. this._debugLines[i] = points;
  62673. }
  62674. this._getBonePosition(points[0], bone, meshMat);
  62675. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  62676. points[0].subtractInPlace(meshPos);
  62677. points[1].subtractInPlace(meshPos);
  62678. }
  62679. };
  62680. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  62681. var len = bones.length;
  62682. var boneNum = 0;
  62683. var meshPos = this.mesh.position;
  62684. for (var i = len - 1; i >= 0; i--) {
  62685. var childBone = bones[i];
  62686. var parentBone = childBone.getParent();
  62687. if (!parentBone) {
  62688. continue;
  62689. }
  62690. var points = this._debugLines[boneNum];
  62691. if (!points) {
  62692. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62693. this._debugLines[boneNum] = points;
  62694. }
  62695. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  62696. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  62697. points[0].subtractInPlace(meshPos);
  62698. points[1].subtractInPlace(meshPos);
  62699. boneNum++;
  62700. }
  62701. };
  62702. SkeletonViewer.prototype.update = function () {
  62703. if (this.autoUpdateBonesMatrices) {
  62704. this.skeleton.computeAbsoluteTransforms();
  62705. }
  62706. if (this.skeleton.bones[0].length === undefined) {
  62707. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62708. }
  62709. else {
  62710. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  62711. }
  62712. if (!this._debugMesh) {
  62713. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true }, this._scene);
  62714. this._debugMesh.renderingGroupId = this.renderingGroupId;
  62715. }
  62716. else {
  62717. BABYLON.MeshBuilder.CreateLineSystem(null, { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  62718. }
  62719. this._debugMesh.position.copyFrom(this.mesh.position);
  62720. this._debugMesh.color = this.color;
  62721. };
  62722. SkeletonViewer.prototype.dispose = function () {
  62723. if (this._debugMesh) {
  62724. this.isEnabled = false;
  62725. this._debugMesh.dispose();
  62726. this._debugMesh = null;
  62727. }
  62728. };
  62729. return SkeletonViewer;
  62730. }());
  62731. Debug.SkeletonViewer = SkeletonViewer;
  62732. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62733. })(BABYLON || (BABYLON = {}));
  62734. //# sourceMappingURL=babylon.skeletonViewer.js.map
  62735. var BABYLON;
  62736. (function (BABYLON) {
  62737. var Debug;
  62738. (function (Debug) {
  62739. var AxesViewer = (function () {
  62740. function AxesViewer(scene, scaleLines) {
  62741. if (scaleLines === void 0) { scaleLines = 1; }
  62742. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62743. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62744. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  62745. this.scaleLines = 1;
  62746. this.scaleLines = scaleLines;
  62747. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  62748. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  62749. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  62750. this._xmesh.renderingGroupId = 2;
  62751. this._ymesh.renderingGroupId = 2;
  62752. this._zmesh.renderingGroupId = 2;
  62753. this._xmesh.material.checkReadyOnlyOnce = true;
  62754. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  62755. this._ymesh.material.checkReadyOnlyOnce = true;
  62756. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  62757. this._zmesh.material.checkReadyOnlyOnce = true;
  62758. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  62759. this.scene = scene;
  62760. }
  62761. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  62762. var scaleLines = this.scaleLines;
  62763. this._xmesh.position.copyFrom(position);
  62764. this._ymesh.position.copyFrom(position);
  62765. this._zmesh.position.copyFrom(position);
  62766. var point2 = this._xline[1];
  62767. point2.x = xaxis.x * scaleLines;
  62768. point2.y = xaxis.y * scaleLines;
  62769. point2.z = xaxis.z * scaleLines;
  62770. BABYLON.Mesh.CreateLines(null, this._xline, null, null, this._xmesh);
  62771. point2 = this._yline[1];
  62772. point2.x = yaxis.x * scaleLines;
  62773. point2.y = yaxis.y * scaleLines;
  62774. point2.z = yaxis.z * scaleLines;
  62775. BABYLON.Mesh.CreateLines(null, this._yline, null, null, this._ymesh);
  62776. point2 = this._zline[1];
  62777. point2.x = zaxis.x * scaleLines;
  62778. point2.y = zaxis.y * scaleLines;
  62779. point2.z = zaxis.z * scaleLines;
  62780. BABYLON.Mesh.CreateLines(null, this._zline, null, null, this._zmesh);
  62781. };
  62782. AxesViewer.prototype.dispose = function () {
  62783. if (this._xmesh) {
  62784. this._xmesh.dispose();
  62785. this._ymesh.dispose();
  62786. this._zmesh.dispose();
  62787. this._xmesh = null;
  62788. this._ymesh = null;
  62789. this._zmesh = null;
  62790. this._xline = null;
  62791. this._yline = null;
  62792. this._zline = null;
  62793. this.scene = null;
  62794. }
  62795. };
  62796. return AxesViewer;
  62797. }());
  62798. Debug.AxesViewer = AxesViewer;
  62799. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62800. })(BABYLON || (BABYLON = {}));
  62801. //# sourceMappingURL=babylon.axesViewer.js.map
  62802. var BABYLON;
  62803. (function (BABYLON) {
  62804. var Debug;
  62805. (function (Debug) {
  62806. var BoneAxesViewer = (function (_super) {
  62807. __extends(BoneAxesViewer, _super);
  62808. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  62809. if (scaleLines === void 0) { scaleLines = 1; }
  62810. var _this = _super.call(this, scene, scaleLines) || this;
  62811. _this.pos = BABYLON.Vector3.Zero();
  62812. _this.xaxis = BABYLON.Vector3.Zero();
  62813. _this.yaxis = BABYLON.Vector3.Zero();
  62814. _this.zaxis = BABYLON.Vector3.Zero();
  62815. _this.mesh = mesh;
  62816. _this.bone = bone;
  62817. return _this;
  62818. }
  62819. BoneAxesViewer.prototype.update = function () {
  62820. var bone = this.bone;
  62821. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  62822. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  62823. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  62824. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  62825. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  62826. };
  62827. BoneAxesViewer.prototype.dispose = function () {
  62828. if (this.pos) {
  62829. this.pos = null;
  62830. this.xaxis = null;
  62831. this.yaxis = null;
  62832. this.zaxis = null;
  62833. this.mesh = null;
  62834. this.bone = null;
  62835. _super.prototype.dispose.call(this);
  62836. }
  62837. };
  62838. return BoneAxesViewer;
  62839. }(Debug.AxesViewer));
  62840. Debug.BoneAxesViewer = BoneAxesViewer;
  62841. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  62842. })(BABYLON || (BABYLON = {}));
  62843. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  62844. var BABYLON;
  62845. (function (BABYLON) {
  62846. var RayHelper = (function () {
  62847. function RayHelper(ray) {
  62848. this.ray = ray;
  62849. }
  62850. RayHelper.CreateAndShow = function (ray, scene, color) {
  62851. var helper = new RayHelper(ray);
  62852. helper.show(scene, color);
  62853. return helper;
  62854. };
  62855. RayHelper.prototype.show = function (scene, color) {
  62856. if (!this._renderFunction) {
  62857. var ray = this.ray;
  62858. this._renderFunction = this._render.bind(this);
  62859. this._scene = scene;
  62860. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  62861. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  62862. this._scene.registerBeforeRender(this._renderFunction);
  62863. }
  62864. if (color) {
  62865. this._renderLine.color.copyFrom(color);
  62866. }
  62867. };
  62868. RayHelper.prototype.hide = function () {
  62869. if (this._renderFunction) {
  62870. this._scene.unregisterBeforeRender(this._renderFunction);
  62871. this._scene = null;
  62872. this._renderFunction = null;
  62873. this._renderLine.dispose();
  62874. this._renderLine = null;
  62875. this._renderPoints = null;
  62876. }
  62877. };
  62878. RayHelper.prototype._render = function () {
  62879. var ray = this.ray;
  62880. var point = this._renderPoints[1];
  62881. var len = Math.min(ray.length, 1000000);
  62882. point.copyFrom(ray.direction);
  62883. point.scaleInPlace(len);
  62884. point.addInPlace(ray.origin);
  62885. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  62886. };
  62887. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  62888. this._attachedToMesh = mesh;
  62889. var ray = this.ray;
  62890. if (!ray.direction) {
  62891. ray.direction = BABYLON.Vector3.Zero();
  62892. }
  62893. if (!ray.origin) {
  62894. ray.origin = BABYLON.Vector3.Zero();
  62895. }
  62896. if (length) {
  62897. ray.length = length;
  62898. }
  62899. if (!meshSpaceOrigin) {
  62900. meshSpaceOrigin = BABYLON.Vector3.Zero();
  62901. }
  62902. if (!meshSpaceDirection) {
  62903. // -1 so that this will work with Mesh.lookAt
  62904. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  62905. }
  62906. if (!this._meshSpaceDirection) {
  62907. this._meshSpaceDirection = meshSpaceDirection.clone();
  62908. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  62909. }
  62910. else {
  62911. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  62912. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  62913. }
  62914. if (!this._updateToMeshFunction) {
  62915. this._updateToMeshFunction = this._updateToMesh.bind(this);
  62916. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  62917. }
  62918. this._updateToMesh();
  62919. };
  62920. RayHelper.prototype.detachFromMesh = function () {
  62921. if (this._attachedToMesh) {
  62922. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  62923. this._attachedToMesh = null;
  62924. this._updateToMeshFunction = null;
  62925. }
  62926. };
  62927. RayHelper.prototype._updateToMesh = function () {
  62928. var ray = this.ray;
  62929. if (this._attachedToMesh._isDisposed) {
  62930. this.detachFromMesh();
  62931. return;
  62932. }
  62933. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  62934. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  62935. };
  62936. RayHelper.prototype.dispose = function () {
  62937. this.hide();
  62938. this.detachFromMesh();
  62939. this.ray = null;
  62940. };
  62941. return RayHelper;
  62942. }());
  62943. BABYLON.RayHelper = RayHelper;
  62944. })(BABYLON || (BABYLON = {}));
  62945. //# sourceMappingURL=babylon.rayHelper.js.map
  62946. var BABYLON;
  62947. (function (BABYLON) {
  62948. var DebugLayer = (function () {
  62949. function DebugLayer(scene) {
  62950. this._scene = scene;
  62951. }
  62952. /** Creates the inspector window. */
  62953. DebugLayer.prototype._createInspector = function (config) {
  62954. if (config === void 0) { config = {}; }
  62955. var popup = config.popup || false;
  62956. var initialTab = config.initialTab || 0;
  62957. var parentElement = config.parentElement || null;
  62958. if (!this._inspector) {
  62959. this._inspector = new INSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  62960. } // else nothing to do,; instance is already existing
  62961. };
  62962. DebugLayer.prototype.isVisible = function () {
  62963. if (!this._inspector) {
  62964. return false;
  62965. }
  62966. return true;
  62967. };
  62968. DebugLayer.prototype.hide = function () {
  62969. if (this._inspector) {
  62970. try {
  62971. this._inspector.dispose();
  62972. }
  62973. catch (e) {
  62974. // If the inspector has been removed directly from the inspector tool
  62975. }
  62976. this._inspector = null;
  62977. }
  62978. };
  62979. DebugLayer.prototype.show = function (config) {
  62980. if (config === void 0) { config = {}; }
  62981. if (typeof INSPECTOR == 'undefined') {
  62982. // Load inspector and add it to the DOM
  62983. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  62984. }
  62985. else {
  62986. // Otherwise creates the inspector
  62987. this._createInspector(config);
  62988. }
  62989. };
  62990. // Get protocol used - http or https
  62991. DebugLayer.InspectorURL = window.location.href.split('/')[0] + '//preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  62992. return DebugLayer;
  62993. }());
  62994. BABYLON.DebugLayer = DebugLayer;
  62995. })(BABYLON || (BABYLON = {}));
  62996. //# sourceMappingURL=babylon.debugLayer.js.map
  62997. var BABYLON;
  62998. (function (BABYLON) {
  62999. var Debug;
  63000. (function (Debug) {
  63001. var PhysicsViewer = (function () {
  63002. function PhysicsViewer(scene) {
  63003. this._impostors = [];
  63004. this._meshes = [];
  63005. this._numMeshes = 0;
  63006. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  63007. this._physicsEnginePlugin = this._scene.getPhysicsEngine().getPhysicsPlugin();
  63008. }
  63009. PhysicsViewer.prototype._updateDebugMeshes = function () {
  63010. var plugin = this._physicsEnginePlugin;
  63011. for (var i = 0; i < this._numMeshes; i++) {
  63012. if (this._impostors[i].isDisposed) {
  63013. this.hideImpostor(this._impostors[i--]);
  63014. }
  63015. else {
  63016. plugin.syncMeshWithImpostor(this._meshes[i], this._impostors[i]);
  63017. }
  63018. }
  63019. };
  63020. PhysicsViewer.prototype.showImpostor = function (impostor) {
  63021. for (var i = 0; i < this._numMeshes; i++) {
  63022. if (this._impostors[i] == impostor) {
  63023. return;
  63024. }
  63025. }
  63026. var debugMesh = this._getDebugMesh(impostor, this._scene);
  63027. if (debugMesh) {
  63028. this._impostors[this._numMeshes] = impostor;
  63029. this._meshes[this._numMeshes] = debugMesh;
  63030. if (this._numMeshes === 0) {
  63031. this._renderFunction = this._updateDebugMeshes.bind(this);
  63032. this._scene.registerBeforeRender(this._renderFunction);
  63033. }
  63034. this._numMeshes++;
  63035. }
  63036. };
  63037. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  63038. var removed = false;
  63039. for (var i = 0; i < this._numMeshes; i++) {
  63040. if (this._impostors[i] == impostor) {
  63041. this._scene.removeMesh(this._meshes[i]);
  63042. this._meshes[i].dispose();
  63043. this._numMeshes--;
  63044. if (this._numMeshes > 0) {
  63045. this._meshes[i] = this._meshes[this._numMeshes];
  63046. this._impostors[i] = this._impostors[this._numMeshes];
  63047. this._meshes[this._numMeshes] = null;
  63048. this._impostors[this._numMeshes] = null;
  63049. }
  63050. else {
  63051. this._meshes[0] = null;
  63052. this._impostors[0] = null;
  63053. }
  63054. removed = true;
  63055. break;
  63056. }
  63057. }
  63058. if (removed && this._numMeshes === 0) {
  63059. this._scene.unregisterBeforeRender(this._renderFunction);
  63060. }
  63061. };
  63062. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  63063. if (!this._debugMaterial) {
  63064. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  63065. this._debugMaterial.wireframe = true;
  63066. }
  63067. return this._debugMaterial;
  63068. };
  63069. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  63070. if (!this._debugBoxMesh) {
  63071. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  63072. this._debugBoxMesh.renderingGroupId = 1;
  63073. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63074. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  63075. scene.removeMesh(this._debugBoxMesh);
  63076. }
  63077. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  63078. };
  63079. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  63080. if (!this._debugSphereMesh) {
  63081. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  63082. this._debugSphereMesh.renderingGroupId = 1;
  63083. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  63084. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  63085. scene.removeMesh(this._debugSphereMesh);
  63086. }
  63087. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  63088. };
  63089. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  63090. var body = impostor.physicsBody;
  63091. var shape = body.shapes[0];
  63092. var mesh;
  63093. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  63094. mesh = this._getDebugBoxMesh(scene);
  63095. impostor.getBoxSizeToRef(mesh.scaling);
  63096. }
  63097. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  63098. mesh = this._getDebugSphereMesh(scene);
  63099. var radius = impostor.getRadius();
  63100. mesh.scaling.x = radius * 2;
  63101. mesh.scaling.y = radius * 2;
  63102. mesh.scaling.z = radius * 2;
  63103. }
  63104. return mesh;
  63105. };
  63106. PhysicsViewer.prototype.dispose = function () {
  63107. for (var i = 0; i < this._numMeshes; i++) {
  63108. this.hideImpostor(this._impostors[i]);
  63109. }
  63110. if (this._debugBoxMesh) {
  63111. this._debugBoxMesh.dispose();
  63112. }
  63113. if (this._debugSphereMesh) {
  63114. this._debugSphereMesh.dispose();
  63115. }
  63116. if (this._debugMaterial) {
  63117. this._debugMaterial.dispose();
  63118. }
  63119. this._impostors.length = 0;
  63120. this._scene = null;
  63121. this._physicsEnginePlugin = null;
  63122. };
  63123. return PhysicsViewer;
  63124. }());
  63125. Debug.PhysicsViewer = PhysicsViewer;
  63126. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  63127. })(BABYLON || (BABYLON = {}));
  63128. //# sourceMappingURL=babylon.physicsViewer.js.map
  63129. var BABYLON;
  63130. (function (BABYLON) {
  63131. var BoundingBoxRenderer = (function () {
  63132. function BoundingBoxRenderer(scene) {
  63133. this.frontColor = new BABYLON.Color3(1, 1, 1);
  63134. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  63135. this.showBackLines = true;
  63136. this.renderList = new BABYLON.SmartArray(32);
  63137. this._vertexBuffers = {};
  63138. this._scene = scene;
  63139. }
  63140. BoundingBoxRenderer.prototype._prepareRessources = function () {
  63141. if (this._colorShader) {
  63142. return;
  63143. }
  63144. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  63145. attributes: [BABYLON.VertexBuffer.PositionKind],
  63146. uniforms: ["world", "viewProjection", "color"]
  63147. });
  63148. var engine = this._scene.getEngine();
  63149. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  63150. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  63151. 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]);
  63152. };
  63153. BoundingBoxRenderer.prototype.reset = function () {
  63154. this.renderList.reset();
  63155. };
  63156. BoundingBoxRenderer.prototype.render = function () {
  63157. if (this.renderList.length === 0) {
  63158. return;
  63159. }
  63160. this._prepareRessources();
  63161. if (!this._colorShader.isReady()) {
  63162. return;
  63163. }
  63164. var engine = this._scene.getEngine();
  63165. engine.setDepthWrite(false);
  63166. this._colorShader._preBind();
  63167. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  63168. var boundingBox = this.renderList.data[boundingBoxIndex];
  63169. var min = boundingBox.minimum;
  63170. var max = boundingBox.maximum;
  63171. var diff = max.subtract(min);
  63172. var median = min.add(diff.scale(0.5));
  63173. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63174. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63175. .multiply(boundingBox.getWorldMatrix());
  63176. // VBOs
  63177. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63178. if (this.showBackLines) {
  63179. // Back
  63180. engine.setDepthFunctionToGreaterOrEqual();
  63181. this._scene.resetCachedMaterial();
  63182. this._colorShader.setColor4("color", this.backColor.toColor4());
  63183. this._colorShader.bind(worldMatrix);
  63184. // Draw order
  63185. engine.draw(false, 0, 24);
  63186. }
  63187. // Front
  63188. engine.setDepthFunctionToLess();
  63189. this._scene.resetCachedMaterial();
  63190. this._colorShader.setColor4("color", this.frontColor.toColor4());
  63191. this._colorShader.bind(worldMatrix);
  63192. // Draw order
  63193. engine.draw(false, 0, 24);
  63194. }
  63195. this._colorShader.unbind();
  63196. engine.setDepthFunctionToLessOrEqual();
  63197. engine.setDepthWrite(true);
  63198. };
  63199. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  63200. this._prepareRessources();
  63201. if (!this._colorShader.isReady()) {
  63202. return;
  63203. }
  63204. var engine = this._scene.getEngine();
  63205. engine.setDepthWrite(false);
  63206. engine.setColorWrite(false);
  63207. this._colorShader._preBind();
  63208. var boundingBox = mesh._boundingInfo.boundingBox;
  63209. var min = boundingBox.minimum;
  63210. var max = boundingBox.maximum;
  63211. var diff = max.subtract(min);
  63212. var median = min.add(diff.scale(0.5));
  63213. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  63214. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  63215. .multiply(boundingBox.getWorldMatrix());
  63216. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  63217. engine.setDepthFunctionToLess();
  63218. this._scene.resetCachedMaterial();
  63219. this._colorShader.bind(worldMatrix);
  63220. engine.draw(false, 0, 24);
  63221. this._colorShader.unbind();
  63222. engine.setDepthFunctionToLessOrEqual();
  63223. engine.setDepthWrite(true);
  63224. engine.setColorWrite(true);
  63225. };
  63226. BoundingBoxRenderer.prototype.dispose = function () {
  63227. if (!this._colorShader) {
  63228. return;
  63229. }
  63230. this.renderList.dispose();
  63231. this._colorShader.dispose();
  63232. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  63233. if (buffer) {
  63234. buffer.dispose();
  63235. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  63236. }
  63237. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  63238. };
  63239. return BoundingBoxRenderer;
  63240. }());
  63241. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  63242. })(BABYLON || (BABYLON = {}));
  63243. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  63244. var BABYLON;
  63245. (function (BABYLON) {
  63246. var MorphTarget = (function () {
  63247. function MorphTarget(name, influence) {
  63248. if (influence === void 0) { influence = 0; }
  63249. this.name = name;
  63250. this.animations = new Array();
  63251. this.onInfluenceChanged = new BABYLON.Observable();
  63252. this.influence = influence;
  63253. }
  63254. Object.defineProperty(MorphTarget.prototype, "influence", {
  63255. get: function () {
  63256. return this._influence;
  63257. },
  63258. set: function (influence) {
  63259. if (this._influence === influence) {
  63260. return;
  63261. }
  63262. var previous = this._influence;
  63263. this._influence = influence;
  63264. if (this.onInfluenceChanged.hasObservers) {
  63265. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  63266. }
  63267. },
  63268. enumerable: true,
  63269. configurable: true
  63270. });
  63271. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  63272. get: function () {
  63273. return this._normals !== undefined;
  63274. },
  63275. enumerable: true,
  63276. configurable: true
  63277. });
  63278. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  63279. get: function () {
  63280. return this._tangents !== undefined;
  63281. },
  63282. enumerable: true,
  63283. configurable: true
  63284. });
  63285. MorphTarget.prototype.setPositions = function (data) {
  63286. this._positions = new Float32Array(data);
  63287. };
  63288. MorphTarget.prototype.getPositions = function () {
  63289. return this._positions;
  63290. };
  63291. MorphTarget.prototype.setNormals = function (data) {
  63292. this._normals = new Float32Array(data);
  63293. };
  63294. MorphTarget.prototype.getNormals = function () {
  63295. return this._normals;
  63296. };
  63297. MorphTarget.prototype.setTangents = function (data) {
  63298. this._tangents = new Float32Array(data);
  63299. };
  63300. MorphTarget.prototype.getTangents = function () {
  63301. return this._tangents;
  63302. };
  63303. /**
  63304. * Serializes the current target into a Serialization object.
  63305. * Returns the serialized object.
  63306. */
  63307. MorphTarget.prototype.serialize = function () {
  63308. var serializationObject = {};
  63309. serializationObject.name = this.name;
  63310. serializationObject.influence = this.influence;
  63311. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  63312. if (this.hasNormals) {
  63313. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  63314. }
  63315. if (this.hasTangents) {
  63316. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  63317. }
  63318. return serializationObject;
  63319. };
  63320. // Statics
  63321. MorphTarget.Parse = function (serializationObject) {
  63322. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  63323. result.setPositions(serializationObject.positions);
  63324. if (serializationObject.normals) {
  63325. result.setNormals(serializationObject.normals);
  63326. }
  63327. if (serializationObject.tangents) {
  63328. result.setTangents(serializationObject.tangents);
  63329. }
  63330. return result;
  63331. };
  63332. MorphTarget.FromMesh = function (mesh, name, influence) {
  63333. if (!name) {
  63334. name = mesh.name;
  63335. }
  63336. var result = new MorphTarget(name, influence);
  63337. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  63338. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  63339. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  63340. }
  63341. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  63342. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  63343. }
  63344. return result;
  63345. };
  63346. return MorphTarget;
  63347. }());
  63348. BABYLON.MorphTarget = MorphTarget;
  63349. })(BABYLON || (BABYLON = {}));
  63350. //# sourceMappingURL=babylon.morphTarget.js.map
  63351. var BABYLON;
  63352. (function (BABYLON) {
  63353. var MorphTargetManager = (function () {
  63354. function MorphTargetManager(scene) {
  63355. this._targets = new Array();
  63356. this._targetObservable = new Array();
  63357. this._activeTargets = new BABYLON.SmartArray(16);
  63358. this._supportsNormals = false;
  63359. this._supportsTangents = false;
  63360. this._vertexCount = 0;
  63361. this._uniqueId = 0;
  63362. this._tempInfluences = new Array();
  63363. if (!scene) {
  63364. scene = BABYLON.Engine.LastCreatedScene;
  63365. }
  63366. this._scene = scene;
  63367. this._scene.morphTargetManagers.push(this);
  63368. this._uniqueId = scene.getUniqueId();
  63369. }
  63370. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  63371. get: function () {
  63372. return this._uniqueId;
  63373. },
  63374. enumerable: true,
  63375. configurable: true
  63376. });
  63377. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  63378. get: function () {
  63379. return this._vertexCount;
  63380. },
  63381. enumerable: true,
  63382. configurable: true
  63383. });
  63384. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  63385. get: function () {
  63386. return this._supportsNormals;
  63387. },
  63388. enumerable: true,
  63389. configurable: true
  63390. });
  63391. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  63392. get: function () {
  63393. return this._supportsTangents;
  63394. },
  63395. enumerable: true,
  63396. configurable: true
  63397. });
  63398. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  63399. get: function () {
  63400. return this._targets.length;
  63401. },
  63402. enumerable: true,
  63403. configurable: true
  63404. });
  63405. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  63406. get: function () {
  63407. return this._activeTargets.length;
  63408. },
  63409. enumerable: true,
  63410. configurable: true
  63411. });
  63412. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  63413. get: function () {
  63414. return this._influences;
  63415. },
  63416. enumerable: true,
  63417. configurable: true
  63418. });
  63419. MorphTargetManager.prototype.getActiveTarget = function (index) {
  63420. return this._activeTargets.data[index];
  63421. };
  63422. MorphTargetManager.prototype.getTarget = function (index) {
  63423. return this._targets[index];
  63424. };
  63425. MorphTargetManager.prototype.addTarget = function (target) {
  63426. var _this = this;
  63427. if (this._vertexCount) {
  63428. if (this._vertexCount !== target.getPositions().length / 3) {
  63429. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  63430. return;
  63431. }
  63432. }
  63433. this._targets.push(target);
  63434. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  63435. _this._syncActiveTargets(needUpdate);
  63436. }));
  63437. this._syncActiveTargets(true);
  63438. };
  63439. MorphTargetManager.prototype.removeTarget = function (target) {
  63440. var index = this._targets.indexOf(target);
  63441. if (index >= 0) {
  63442. this._targets.splice(index, 1);
  63443. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  63444. this._vertexCount = 0;
  63445. this._syncActiveTargets(true);
  63446. }
  63447. };
  63448. /**
  63449. * Serializes the current manager into a Serialization object.
  63450. * Returns the serialized object.
  63451. */
  63452. MorphTargetManager.prototype.serialize = function () {
  63453. var serializationObject = {};
  63454. serializationObject.id = this.uniqueId;
  63455. serializationObject.targets = [];
  63456. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63457. var target = _a[_i];
  63458. serializationObject.targets.push(target.serialize());
  63459. }
  63460. return serializationObject;
  63461. };
  63462. MorphTargetManager.prototype._onInfluenceChanged = function (needUpdate) {
  63463. this._syncActiveTargets(needUpdate);
  63464. };
  63465. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  63466. var influenceCount = 0;
  63467. this._activeTargets.reset();
  63468. this._supportsNormals = true;
  63469. this._supportsTangents = true;
  63470. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  63471. var target = _a[_i];
  63472. if (target.influence > 0) {
  63473. this._activeTargets.push(target);
  63474. this._tempInfluences[influenceCount++] = target.influence;
  63475. this._supportsNormals = this._supportsNormals && target.hasNormals;
  63476. this._supportsTangents = this._supportsTangents && target.hasTangents;
  63477. if (this._vertexCount === 0) {
  63478. this._vertexCount = target.getPositions().length / 3;
  63479. }
  63480. }
  63481. }
  63482. if (!this._influences || this._influences.length !== influenceCount) {
  63483. this._influences = new Float32Array(influenceCount);
  63484. }
  63485. for (var index = 0; index < influenceCount; index++) {
  63486. this._influences[index] = this._tempInfluences[index];
  63487. }
  63488. if (needUpdate) {
  63489. // Flag meshes as dirty to resync with the active targets
  63490. for (var _b = 0, _c = this._scene.meshes; _b < _c.length; _b++) {
  63491. var mesh = _c[_b];
  63492. if (mesh.morphTargetManager === this) {
  63493. mesh._syncGeometryWithMorphTargetManager();
  63494. }
  63495. }
  63496. }
  63497. };
  63498. // Statics
  63499. MorphTargetManager.Parse = function (serializationObject, scene) {
  63500. var result = new MorphTargetManager(scene);
  63501. result._uniqueId = serializationObject.id;
  63502. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  63503. var targetData = _a[_i];
  63504. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  63505. }
  63506. return result;
  63507. };
  63508. return MorphTargetManager;
  63509. }());
  63510. BABYLON.MorphTargetManager = MorphTargetManager;
  63511. })(BABYLON || (BABYLON = {}));
  63512. //# sourceMappingURL=babylon.morphTargetManager.js.map
  63513. var BABYLON;
  63514. (function (BABYLON) {
  63515. /**
  63516. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  63517. * It can help converting any input color in a desired output one. This can then be used to create effects
  63518. * from sepia, black and white to sixties or futuristic rendering...
  63519. *
  63520. * The only supported format is currently 3dl.
  63521. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  63522. */
  63523. var ColorGradingTexture = (function (_super) {
  63524. __extends(ColorGradingTexture, _super);
  63525. /**
  63526. * Instantiates a ColorGradingTexture from the following parameters.
  63527. *
  63528. * @param url The location of the color gradind data (currently only supporting 3dl)
  63529. * @param scene The scene the texture will be used in
  63530. */
  63531. function ColorGradingTexture(url, scene) {
  63532. var _this = _super.call(this, scene) || this;
  63533. if (!url) {
  63534. return _this;
  63535. }
  63536. _this._textureMatrix = BABYLON.Matrix.Identity();
  63537. _this.name = url;
  63538. _this.url = url;
  63539. _this.hasAlpha = false;
  63540. _this.isCube = false;
  63541. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63542. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63543. _this.anisotropicFilteringLevel = 1;
  63544. _this._texture = _this._getFromCache(url, true);
  63545. if (!_this._texture) {
  63546. if (!scene.useDelayedTextureLoading) {
  63547. _this.loadTexture();
  63548. }
  63549. else {
  63550. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63551. }
  63552. }
  63553. return _this;
  63554. }
  63555. /**
  63556. * Returns the texture matrix used in most of the material.
  63557. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  63558. */
  63559. ColorGradingTexture.prototype.getTextureMatrix = function () {
  63560. return this._textureMatrix;
  63561. };
  63562. /**
  63563. * Occurs when the file being loaded is a .3dl LUT file.
  63564. */
  63565. ColorGradingTexture.prototype.load3dlTexture = function () {
  63566. var _this = this;
  63567. var mipLevels = 0;
  63568. var floatArrayView = null;
  63569. var texture = this.getScene().getEngine().createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  63570. this._texture = texture;
  63571. var callback = function (text) {
  63572. var data;
  63573. var tempData;
  63574. var line;
  63575. var lines = text.split('\n');
  63576. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  63577. var maxColor = 0;
  63578. for (var i = 0; i < lines.length; i++) {
  63579. line = lines[i];
  63580. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  63581. continue;
  63582. if (line.indexOf('#') === 0)
  63583. continue;
  63584. var words = line.split(" ");
  63585. if (size === 0) {
  63586. // Number of space + one
  63587. size = words.length;
  63588. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  63589. tempData = new Float32Array(size * size * size * 4);
  63590. continue;
  63591. }
  63592. if (size != 0) {
  63593. var r = Math.max(parseInt(words[0]), 0);
  63594. var g = Math.max(parseInt(words[1]), 0);
  63595. var b = Math.max(parseInt(words[2]), 0);
  63596. maxColor = Math.max(r, maxColor);
  63597. maxColor = Math.max(g, maxColor);
  63598. maxColor = Math.max(b, maxColor);
  63599. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  63600. tempData[pixelStorageIndex + 0] = r;
  63601. tempData[pixelStorageIndex + 1] = g;
  63602. tempData[pixelStorageIndex + 2] = b;
  63603. pixelIndexSlice++;
  63604. if (pixelIndexSlice % size == 0) {
  63605. pixelIndexH++;
  63606. pixelIndexSlice = 0;
  63607. if (pixelIndexH % size == 0) {
  63608. pixelIndexW++;
  63609. pixelIndexH = 0;
  63610. }
  63611. }
  63612. }
  63613. }
  63614. for (var i = 0; i < tempData.length; i++) {
  63615. if (i > 0 && (i + 1) % 4 === 0) {
  63616. data[i] = 255;
  63617. }
  63618. else {
  63619. var value = tempData[i];
  63620. data[i] = (value / maxColor * 255);
  63621. }
  63622. }
  63623. texture.updateSize(size * size, size);
  63624. _this.getScene().getEngine().updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  63625. };
  63626. BABYLON.Tools.LoadFile(this.url, callback);
  63627. return this._texture;
  63628. };
  63629. /**
  63630. * Starts the loading process of the texture.
  63631. */
  63632. ColorGradingTexture.prototype.loadTexture = function () {
  63633. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  63634. this.load3dlTexture();
  63635. }
  63636. };
  63637. /**
  63638. * Clones the color gradind texture.
  63639. */
  63640. ColorGradingTexture.prototype.clone = function () {
  63641. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  63642. // Base texture
  63643. newTexture.level = this.level;
  63644. return newTexture;
  63645. };
  63646. /**
  63647. * Called during delayed load for textures.
  63648. */
  63649. ColorGradingTexture.prototype.delayLoad = function () {
  63650. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63651. return;
  63652. }
  63653. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63654. this._texture = this._getFromCache(this.url, true);
  63655. if (!this._texture) {
  63656. this.loadTexture();
  63657. }
  63658. };
  63659. /**
  63660. * Parses a color grading texture serialized by Babylon.
  63661. * @param parsedTexture The texture information being parsedTexture
  63662. * @param scene The scene to load the texture in
  63663. * @param rootUrl The root url of the data assets to load
  63664. * @return A color gradind texture
  63665. */
  63666. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63667. var texture = null;
  63668. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  63669. texture = new BABYLON.ColorGradingTexture(parsedTexture.name, scene);
  63670. texture.name = parsedTexture.name;
  63671. texture.level = parsedTexture.level;
  63672. }
  63673. return texture;
  63674. };
  63675. /**
  63676. * Serializes the LUT texture to json format.
  63677. */
  63678. ColorGradingTexture.prototype.serialize = function () {
  63679. if (!this.name) {
  63680. return null;
  63681. }
  63682. var serializationObject = {};
  63683. serializationObject.name = this.name;
  63684. serializationObject.level = this.level;
  63685. serializationObject.customType = "BABYLON.ColorGradingTexture";
  63686. return serializationObject;
  63687. };
  63688. /**
  63689. * Empty line regex stored for GC.
  63690. */
  63691. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  63692. return ColorGradingTexture;
  63693. }(BABYLON.BaseTexture));
  63694. BABYLON.ColorGradingTexture = ColorGradingTexture;
  63695. })(BABYLON || (BABYLON = {}));
  63696. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  63697. var BABYLON;
  63698. (function (BABYLON) {
  63699. /**
  63700. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  63701. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  63702. * 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;
  63703. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  63704. */
  63705. var ColorCurves = (function () {
  63706. function ColorCurves() {
  63707. this._dirty = true;
  63708. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  63709. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  63710. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63711. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  63712. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  63713. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  63714. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  63715. this._globalHue = 30;
  63716. this._globalDensity = 0;
  63717. this._globalSaturation = 0;
  63718. this._globalExposure = 0;
  63719. this._highlightsHue = 30;
  63720. this._highlightsDensity = 0;
  63721. this._highlightsSaturation = 0;
  63722. this._highlightsExposure = 0;
  63723. this._midtonesHue = 30;
  63724. this._midtonesDensity = 0;
  63725. this._midtonesSaturation = 0;
  63726. this._midtonesExposure = 0;
  63727. this._shadowsHue = 30;
  63728. this._shadowsDensity = 0;
  63729. this._shadowsSaturation = 0;
  63730. this._shadowsExposure = 0;
  63731. }
  63732. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  63733. /**
  63734. * Gets the global Hue value.
  63735. * 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).
  63736. */
  63737. get: function () {
  63738. return this._globalHue;
  63739. },
  63740. /**
  63741. * Sets the global Hue value.
  63742. * 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).
  63743. */
  63744. set: function (value) {
  63745. this._globalHue = value;
  63746. this._dirty = true;
  63747. },
  63748. enumerable: true,
  63749. configurable: true
  63750. });
  63751. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  63752. /**
  63753. * Gets the global Density value.
  63754. * 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.
  63755. * Values less than zero provide a filter of opposite hue.
  63756. */
  63757. get: function () {
  63758. return this._globalDensity;
  63759. },
  63760. /**
  63761. * Sets the global Density value.
  63762. * 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.
  63763. * Values less than zero provide a filter of opposite hue.
  63764. */
  63765. set: function (value) {
  63766. this._globalDensity = value;
  63767. this._dirty = true;
  63768. },
  63769. enumerable: true,
  63770. configurable: true
  63771. });
  63772. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  63773. /**
  63774. * Gets the global Saturation value.
  63775. * 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.
  63776. */
  63777. get: function () {
  63778. return this._globalSaturation;
  63779. },
  63780. /**
  63781. * Sets the global Saturation value.
  63782. * 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.
  63783. */
  63784. set: function (value) {
  63785. this._globalSaturation = value;
  63786. this._dirty = true;
  63787. },
  63788. enumerable: true,
  63789. configurable: true
  63790. });
  63791. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  63792. /**
  63793. * Gets the highlights Hue value.
  63794. * 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).
  63795. */
  63796. get: function () {
  63797. return this._highlightsHue;
  63798. },
  63799. /**
  63800. * Sets the highlights Hue value.
  63801. * 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).
  63802. */
  63803. set: function (value) {
  63804. this._highlightsHue = value;
  63805. this._dirty = true;
  63806. },
  63807. enumerable: true,
  63808. configurable: true
  63809. });
  63810. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  63811. /**
  63812. * Gets the highlights Density value.
  63813. * 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.
  63814. * Values less than zero provide a filter of opposite hue.
  63815. */
  63816. get: function () {
  63817. return this._highlightsDensity;
  63818. },
  63819. /**
  63820. * Sets the highlights Density value.
  63821. * 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.
  63822. * Values less than zero provide a filter of opposite hue.
  63823. */
  63824. set: function (value) {
  63825. this._highlightsDensity = value;
  63826. this._dirty = true;
  63827. },
  63828. enumerable: true,
  63829. configurable: true
  63830. });
  63831. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  63832. /**
  63833. * Gets the highlights Saturation value.
  63834. * 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.
  63835. */
  63836. get: function () {
  63837. return this._highlightsSaturation;
  63838. },
  63839. /**
  63840. * Sets the highlights Saturation value.
  63841. * 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.
  63842. */
  63843. set: function (value) {
  63844. this._highlightsSaturation = value;
  63845. this._dirty = true;
  63846. },
  63847. enumerable: true,
  63848. configurable: true
  63849. });
  63850. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  63851. /**
  63852. * Gets the highlights Exposure value.
  63853. * 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.
  63854. */
  63855. get: function () {
  63856. return this._highlightsExposure;
  63857. },
  63858. /**
  63859. * Sets the highlights Exposure value.
  63860. * 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.
  63861. */
  63862. set: function (value) {
  63863. this._highlightsExposure = value;
  63864. this._dirty = true;
  63865. },
  63866. enumerable: true,
  63867. configurable: true
  63868. });
  63869. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  63870. /**
  63871. * Gets the midtones Hue value.
  63872. * 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).
  63873. */
  63874. get: function () {
  63875. return this._midtonesHue;
  63876. },
  63877. /**
  63878. * Sets the midtones Hue value.
  63879. * 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).
  63880. */
  63881. set: function (value) {
  63882. this._midtonesHue = value;
  63883. this._dirty = true;
  63884. },
  63885. enumerable: true,
  63886. configurable: true
  63887. });
  63888. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  63889. /**
  63890. * Gets the midtones Density value.
  63891. * 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.
  63892. * Values less than zero provide a filter of opposite hue.
  63893. */
  63894. get: function () {
  63895. return this._midtonesDensity;
  63896. },
  63897. /**
  63898. * Sets the midtones Density value.
  63899. * 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.
  63900. * Values less than zero provide a filter of opposite hue.
  63901. */
  63902. set: function (value) {
  63903. this._midtonesDensity = value;
  63904. this._dirty = true;
  63905. },
  63906. enumerable: true,
  63907. configurable: true
  63908. });
  63909. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  63910. /**
  63911. * Gets the midtones Saturation value.
  63912. * 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.
  63913. */
  63914. get: function () {
  63915. return this._midtonesSaturation;
  63916. },
  63917. /**
  63918. * Sets the midtones Saturation value.
  63919. * 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.
  63920. */
  63921. set: function (value) {
  63922. this._midtonesSaturation = value;
  63923. this._dirty = true;
  63924. },
  63925. enumerable: true,
  63926. configurable: true
  63927. });
  63928. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  63929. /**
  63930. * Gets the midtones Exposure value.
  63931. * 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.
  63932. */
  63933. get: function () {
  63934. return this._midtonesExposure;
  63935. },
  63936. /**
  63937. * Sets the midtones Exposure value.
  63938. * 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.
  63939. */
  63940. set: function (value) {
  63941. this._midtonesExposure = value;
  63942. this._dirty = true;
  63943. },
  63944. enumerable: true,
  63945. configurable: true
  63946. });
  63947. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  63948. /**
  63949. * Gets the shadows Hue value.
  63950. * 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).
  63951. */
  63952. get: function () {
  63953. return this._shadowsHue;
  63954. },
  63955. /**
  63956. * Sets the shadows Hue value.
  63957. * 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).
  63958. */
  63959. set: function (value) {
  63960. this._shadowsHue = value;
  63961. this._dirty = true;
  63962. },
  63963. enumerable: true,
  63964. configurable: true
  63965. });
  63966. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  63967. /**
  63968. * Gets the shadows Density value.
  63969. * 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.
  63970. * Values less than zero provide a filter of opposite hue.
  63971. */
  63972. get: function () {
  63973. return this._shadowsDensity;
  63974. },
  63975. /**
  63976. * Sets the shadows Density value.
  63977. * 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.
  63978. * Values less than zero provide a filter of opposite hue.
  63979. */
  63980. set: function (value) {
  63981. this._shadowsDensity = value;
  63982. this._dirty = true;
  63983. },
  63984. enumerable: true,
  63985. configurable: true
  63986. });
  63987. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  63988. /**
  63989. * Gets the shadows Saturation value.
  63990. * 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.
  63991. */
  63992. get: function () {
  63993. return this._shadowsSaturation;
  63994. },
  63995. /**
  63996. * Sets the shadows Saturation value.
  63997. * 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.
  63998. */
  63999. set: function (value) {
  64000. this._shadowsSaturation = value;
  64001. this._dirty = true;
  64002. },
  64003. enumerable: true,
  64004. configurable: true
  64005. });
  64006. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  64007. /**
  64008. * Gets the shadows Exposure value.
  64009. * 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.
  64010. */
  64011. get: function () {
  64012. return this._shadowsExposure;
  64013. },
  64014. /**
  64015. * Sets the shadows Exposure value.
  64016. * 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.
  64017. */
  64018. set: function (value) {
  64019. this._shadowsExposure = value;
  64020. this._dirty = true;
  64021. },
  64022. enumerable: true,
  64023. configurable: true
  64024. });
  64025. ColorCurves.prototype.getClassName = function () {
  64026. return "ColorCurves";
  64027. };
  64028. /**
  64029. * Binds the color curves to the shader.
  64030. * @param colorCurves The color curve to bind
  64031. * @param effect The effect to bind to
  64032. */
  64033. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  64034. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  64035. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  64036. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  64037. if (colorCurves._dirty) {
  64038. colorCurves._dirty = false;
  64039. // Fill in global info.
  64040. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  64041. // Compute highlights info.
  64042. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  64043. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  64044. // Compute midtones info.
  64045. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  64046. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  64047. // Compute shadows info.
  64048. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  64049. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  64050. // Compute deltas (neutral is midtones).
  64051. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  64052. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  64053. }
  64054. if (effect) {
  64055. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  64056. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  64057. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  64058. }
  64059. };
  64060. /**
  64061. * Prepare the list of uniforms associated with the ColorCurves effects.
  64062. * @param uniformsList The list of uniforms used in the effect
  64063. */
  64064. ColorCurves.PrepareUniforms = function (uniformsList) {
  64065. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  64066. };
  64067. /**
  64068. * Returns color grading data based on a hue, density, saturation and exposure value.
  64069. * @param filterHue The hue of the color filter.
  64070. * @param filterDensity The density of the color filter.
  64071. * @param saturation The saturation.
  64072. * @param exposure The exposure.
  64073. * @param result The result data container.
  64074. */
  64075. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  64076. if (hue == null) {
  64077. return;
  64078. }
  64079. hue = ColorCurves.clamp(hue, 0, 360);
  64080. density = ColorCurves.clamp(density, -100, 100);
  64081. saturation = ColorCurves.clamp(saturation, -100, 100);
  64082. exposure = ColorCurves.clamp(exposure, -100, 100);
  64083. // Remap the slider/config filter density with non-linear mapping and also scale by half
  64084. // so that the maximum filter density is only 50% control. This provides fine control
  64085. // for small values and reasonable range.
  64086. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  64087. density *= 0.5;
  64088. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  64089. if (density < 0) {
  64090. density *= -1;
  64091. hue = (hue + 180) % 360;
  64092. }
  64093. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  64094. result.scaleToRef(2, result);
  64095. result.a = 1 + 0.01 * saturation;
  64096. };
  64097. /**
  64098. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  64099. * @param value The input slider value in range [-100,100].
  64100. * @returns Adjusted value.
  64101. */
  64102. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  64103. value /= 100;
  64104. var x = Math.abs(value);
  64105. x = Math.pow(x, 2);
  64106. if (value < 0) {
  64107. x *= -1;
  64108. }
  64109. x *= 100;
  64110. return x;
  64111. };
  64112. /**
  64113. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  64114. * @param hue The hue (H) input.
  64115. * @param saturation The saturation (S) input.
  64116. * @param brightness The brightness (B) input.
  64117. * @result An RGBA color represented as Vector4.
  64118. */
  64119. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  64120. var h = ColorCurves.clamp(hue, 0, 360);
  64121. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  64122. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  64123. if (s === 0) {
  64124. result.r = v;
  64125. result.g = v;
  64126. result.b = v;
  64127. }
  64128. else {
  64129. // sector 0 to 5
  64130. h /= 60;
  64131. var i = Math.floor(h);
  64132. // fractional part of h
  64133. var f = h - i;
  64134. var p = v * (1 - s);
  64135. var q = v * (1 - s * f);
  64136. var t = v * (1 - s * (1 - f));
  64137. switch (i) {
  64138. case 0:
  64139. result.r = v;
  64140. result.g = t;
  64141. result.b = p;
  64142. break;
  64143. case 1:
  64144. result.r = q;
  64145. result.g = v;
  64146. result.b = p;
  64147. break;
  64148. case 2:
  64149. result.r = p;
  64150. result.g = v;
  64151. result.b = t;
  64152. break;
  64153. case 3:
  64154. result.r = p;
  64155. result.g = q;
  64156. result.b = v;
  64157. break;
  64158. case 4:
  64159. result.r = t;
  64160. result.g = p;
  64161. result.b = v;
  64162. break;
  64163. default:// case 5:
  64164. result.r = v;
  64165. result.g = p;
  64166. result.b = q;
  64167. break;
  64168. }
  64169. }
  64170. result.a = 1;
  64171. };
  64172. /**
  64173. * Returns a value clamped between min and max
  64174. * @param value The value to clamp
  64175. * @param min The minimum of value
  64176. * @param max The maximum of value
  64177. * @returns The clamped value.
  64178. */
  64179. ColorCurves.clamp = function (value, min, max) {
  64180. return Math.min(Math.max(value, min), max);
  64181. };
  64182. /**
  64183. * Clones the current color curve instance.
  64184. * @return The cloned curves
  64185. */
  64186. ColorCurves.prototype.clone = function () {
  64187. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  64188. };
  64189. /**
  64190. * Serializes the current color curve instance to a json representation.
  64191. * @return a JSON representation
  64192. */
  64193. ColorCurves.prototype.serialize = function () {
  64194. return BABYLON.SerializationHelper.Serialize(this);
  64195. };
  64196. /**
  64197. * Parses the color curve from a json representation.
  64198. * @param source the JSON source to parse
  64199. * @return The parsed curves
  64200. */
  64201. ColorCurves.Parse = function (source) {
  64202. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  64203. };
  64204. __decorate([
  64205. BABYLON.serialize()
  64206. ], ColorCurves.prototype, "_globalHue", void 0);
  64207. __decorate([
  64208. BABYLON.serialize()
  64209. ], ColorCurves.prototype, "_globalDensity", void 0);
  64210. __decorate([
  64211. BABYLON.serialize()
  64212. ], ColorCurves.prototype, "_globalSaturation", void 0);
  64213. __decorate([
  64214. BABYLON.serialize()
  64215. ], ColorCurves.prototype, "_globalExposure", void 0);
  64216. __decorate([
  64217. BABYLON.serialize()
  64218. ], ColorCurves.prototype, "_highlightsHue", void 0);
  64219. __decorate([
  64220. BABYLON.serialize()
  64221. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  64222. __decorate([
  64223. BABYLON.serialize()
  64224. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  64225. __decorate([
  64226. BABYLON.serialize()
  64227. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  64228. __decorate([
  64229. BABYLON.serialize()
  64230. ], ColorCurves.prototype, "_midtonesHue", void 0);
  64231. __decorate([
  64232. BABYLON.serialize()
  64233. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  64234. __decorate([
  64235. BABYLON.serialize()
  64236. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  64237. __decorate([
  64238. BABYLON.serialize()
  64239. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  64240. return ColorCurves;
  64241. }());
  64242. BABYLON.ColorCurves = ColorCurves;
  64243. })(BABYLON || (BABYLON = {}));
  64244. //# sourceMappingURL=babylon.colorCurves.js.map
  64245. var BABYLON;
  64246. (function (BABYLON) {
  64247. var Octree = (function () {
  64248. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  64249. if (maxDepth === void 0) { maxDepth = 2; }
  64250. this.maxDepth = maxDepth;
  64251. this.dynamicContent = new Array();
  64252. this._maxBlockCapacity = maxBlockCapacity || 64;
  64253. this._selectionContent = new BABYLON.SmartArray(1024);
  64254. this._creationFunc = creationFunc;
  64255. }
  64256. // Methods
  64257. Octree.prototype.update = function (worldMin, worldMax, entries) {
  64258. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  64259. };
  64260. Octree.prototype.addMesh = function (entry) {
  64261. for (var index = 0; index < this.blocks.length; index++) {
  64262. var block = this.blocks[index];
  64263. block.addEntry(entry);
  64264. }
  64265. };
  64266. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  64267. this._selectionContent.reset();
  64268. for (var index = 0; index < this.blocks.length; index++) {
  64269. var block = this.blocks[index];
  64270. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  64271. }
  64272. if (allowDuplicate) {
  64273. this._selectionContent.concat(this.dynamicContent);
  64274. }
  64275. else {
  64276. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64277. }
  64278. return this._selectionContent;
  64279. };
  64280. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  64281. this._selectionContent.reset();
  64282. for (var index = 0; index < this.blocks.length; index++) {
  64283. var block = this.blocks[index];
  64284. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  64285. }
  64286. if (allowDuplicate) {
  64287. this._selectionContent.concat(this.dynamicContent);
  64288. }
  64289. else {
  64290. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64291. }
  64292. return this._selectionContent;
  64293. };
  64294. Octree.prototype.intersectsRay = function (ray) {
  64295. this._selectionContent.reset();
  64296. for (var index = 0; index < this.blocks.length; index++) {
  64297. var block = this.blocks[index];
  64298. block.intersectsRay(ray, this._selectionContent);
  64299. }
  64300. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  64301. return this._selectionContent;
  64302. };
  64303. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  64304. target.blocks = new Array();
  64305. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  64306. // Segmenting space
  64307. for (var x = 0; x < 2; x++) {
  64308. for (var y = 0; y < 2; y++) {
  64309. for (var z = 0; z < 2; z++) {
  64310. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  64311. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  64312. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  64313. block.addEntries(entries);
  64314. target.blocks.push(block);
  64315. }
  64316. }
  64317. }
  64318. };
  64319. Octree.CreationFuncForMeshes = function (entry, block) {
  64320. if (!entry.isBlocked && entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64321. block.entries.push(entry);
  64322. }
  64323. };
  64324. Octree.CreationFuncForSubMeshes = function (entry, block) {
  64325. if (entry.getBoundingInfo().boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  64326. block.entries.push(entry);
  64327. }
  64328. };
  64329. return Octree;
  64330. }());
  64331. BABYLON.Octree = Octree;
  64332. })(BABYLON || (BABYLON = {}));
  64333. //# sourceMappingURL=babylon.octree.js.map
  64334. var BABYLON;
  64335. (function (BABYLON) {
  64336. var OctreeBlock = (function () {
  64337. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  64338. this.entries = new Array();
  64339. this._boundingVectors = new Array();
  64340. this._capacity = capacity;
  64341. this._depth = depth;
  64342. this._maxDepth = maxDepth;
  64343. this._creationFunc = creationFunc;
  64344. this._minPoint = minPoint;
  64345. this._maxPoint = maxPoint;
  64346. this._boundingVectors.push(minPoint.clone());
  64347. this._boundingVectors.push(maxPoint.clone());
  64348. this._boundingVectors.push(minPoint.clone());
  64349. this._boundingVectors[2].x = maxPoint.x;
  64350. this._boundingVectors.push(minPoint.clone());
  64351. this._boundingVectors[3].y = maxPoint.y;
  64352. this._boundingVectors.push(minPoint.clone());
  64353. this._boundingVectors[4].z = maxPoint.z;
  64354. this._boundingVectors.push(maxPoint.clone());
  64355. this._boundingVectors[5].z = minPoint.z;
  64356. this._boundingVectors.push(maxPoint.clone());
  64357. this._boundingVectors[6].x = minPoint.x;
  64358. this._boundingVectors.push(maxPoint.clone());
  64359. this._boundingVectors[7].y = minPoint.y;
  64360. }
  64361. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  64362. // Property
  64363. get: function () {
  64364. return this._capacity;
  64365. },
  64366. enumerable: true,
  64367. configurable: true
  64368. });
  64369. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  64370. get: function () {
  64371. return this._minPoint;
  64372. },
  64373. enumerable: true,
  64374. configurable: true
  64375. });
  64376. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  64377. get: function () {
  64378. return this._maxPoint;
  64379. },
  64380. enumerable: true,
  64381. configurable: true
  64382. });
  64383. // Methods
  64384. OctreeBlock.prototype.addEntry = function (entry) {
  64385. if (this.blocks) {
  64386. for (var index = 0; index < this.blocks.length; index++) {
  64387. var block = this.blocks[index];
  64388. block.addEntry(entry);
  64389. }
  64390. return;
  64391. }
  64392. this._creationFunc(entry, this);
  64393. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  64394. this.createInnerBlocks();
  64395. }
  64396. };
  64397. OctreeBlock.prototype.addEntries = function (entries) {
  64398. for (var index = 0; index < entries.length; index++) {
  64399. var mesh = entries[index];
  64400. this.addEntry(mesh);
  64401. }
  64402. };
  64403. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  64404. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  64405. if (this.blocks) {
  64406. for (var index = 0; index < this.blocks.length; index++) {
  64407. var block = this.blocks[index];
  64408. block.select(frustumPlanes, selection, allowDuplicate);
  64409. }
  64410. return;
  64411. }
  64412. if (allowDuplicate) {
  64413. selection.concat(this.entries);
  64414. }
  64415. else {
  64416. selection.concatWithNoDuplicate(this.entries);
  64417. }
  64418. }
  64419. };
  64420. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  64421. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  64422. if (this.blocks) {
  64423. for (var index = 0; index < this.blocks.length; index++) {
  64424. var block = this.blocks[index];
  64425. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  64426. }
  64427. return;
  64428. }
  64429. if (allowDuplicate) {
  64430. selection.concat(this.entries);
  64431. }
  64432. else {
  64433. selection.concatWithNoDuplicate(this.entries);
  64434. }
  64435. }
  64436. };
  64437. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  64438. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  64439. if (this.blocks) {
  64440. for (var index = 0; index < this.blocks.length; index++) {
  64441. var block = this.blocks[index];
  64442. block.intersectsRay(ray, selection);
  64443. }
  64444. return;
  64445. }
  64446. selection.concatWithNoDuplicate(this.entries);
  64447. }
  64448. };
  64449. OctreeBlock.prototype.createInnerBlocks = function () {
  64450. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  64451. };
  64452. return OctreeBlock;
  64453. }());
  64454. BABYLON.OctreeBlock = OctreeBlock;
  64455. })(BABYLON || (BABYLON = {}));
  64456. //# sourceMappingURL=babylon.octreeBlock.js.map
  64457. var BABYLON;
  64458. (function (BABYLON) {
  64459. var SIMDVector3 = (function () {
  64460. function SIMDVector3() {
  64461. }
  64462. SIMDVector3.TransformCoordinatesToRefSIMD = function (vector, transformation, result) {
  64463. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD(vector.x, vector.y, vector.z, transformation, result);
  64464. };
  64465. SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD = function (x, y, z, transformation, result) {
  64466. var m = transformation.m;
  64467. var m0 = SIMD.Float32x4.load(m, 0);
  64468. var m1 = SIMD.Float32x4.load(m, 4);
  64469. var m2 = SIMD.Float32x4.load(m, 8);
  64470. var m3 = SIMD.Float32x4.load(m, 12);
  64471. 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));
  64472. r = SIMD.Float32x4.div(r, SIMD.Float32x4.swizzle(r, 3, 3, 3, 3));
  64473. result.x = SIMD.Float32x4.extractLane(r, 0);
  64474. result.y = SIMD.Float32x4.extractLane(r, 1);
  64475. result.z = SIMD.Float32x4.extractLane(r, 2);
  64476. };
  64477. return SIMDVector3;
  64478. }());
  64479. var SIMDMatrix = (function () {
  64480. function SIMDMatrix() {
  64481. }
  64482. SIMDMatrix.prototype.multiplyToArraySIMD = function (other, result, offset) {
  64483. var tm = this.m;
  64484. var om = other.m;
  64485. var m0 = SIMD.Float32x4.load(om, 0);
  64486. var m1 = SIMD.Float32x4.load(om, 4);
  64487. var m2 = SIMD.Float32x4.load(om, 8);
  64488. var m3 = SIMD.Float32x4.load(om, 12);
  64489. for (var i = 0; i < 16; i += 4) {
  64490. 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)))));
  64491. }
  64492. return this;
  64493. };
  64494. SIMDMatrix.prototype.invertToRefSIMD = function (other) {
  64495. var src = this.m;
  64496. var dest = other.m;
  64497. // Load the 4 rows
  64498. var src0 = SIMD.Float32x4.load(src, 0);
  64499. var src1 = SIMD.Float32x4.load(src, 4);
  64500. var src2 = SIMD.Float32x4.load(src, 8);
  64501. var src3 = SIMD.Float32x4.load(src, 12);
  64502. // Transpose the source matrix. Sort of. Not a true transpose operation
  64503. var tmp1 = SIMD.Float32x4.shuffle(src0, src1, 0, 1, 4, 5);
  64504. var row1 = SIMD.Float32x4.shuffle(src2, src3, 0, 1, 4, 5);
  64505. var row0 = SIMD.Float32x4.shuffle(tmp1, row1, 0, 2, 4, 6);
  64506. row1 = SIMD.Float32x4.shuffle(row1, tmp1, 1, 3, 5, 7);
  64507. tmp1 = SIMD.Float32x4.shuffle(src0, src1, 2, 3, 6, 7);
  64508. var row3 = SIMD.Float32x4.shuffle(src2, src3, 2, 3, 6, 7);
  64509. var row2 = SIMD.Float32x4.shuffle(tmp1, row3, 0, 2, 4, 6);
  64510. row3 = SIMD.Float32x4.shuffle(row3, tmp1, 1, 3, 5, 7);
  64511. // This is a true transposition, but it will lead to an incorrect result
  64512. //tmp1 = shuffle(src0, src1, 0, 1, 4, 5);
  64513. //tmp2 = shuffle(src2, src3, 0, 1, 4, 5);
  64514. //row0 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64515. //row1 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64516. //tmp1 = shuffle(src0, src1, 2, 3, 6, 7);
  64517. //tmp2 = shuffle(src2, src3, 2, 3, 6, 7);
  64518. //row2 = shuffle(tmp1, tmp2, 0, 2, 4, 6);
  64519. //row3 = shuffle(tmp1, tmp2, 1, 3, 5, 7);
  64520. // ----
  64521. tmp1 = SIMD.Float32x4.mul(row2, row3);
  64522. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64523. var minor0 = SIMD.Float32x4.mul(row1, tmp1);
  64524. var minor1 = SIMD.Float32x4.mul(row0, tmp1);
  64525. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64526. minor0 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row1, tmp1), minor0);
  64527. minor1 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor1);
  64528. minor1 = SIMD.Float32x4.swizzle(minor1, 2, 3, 0, 1); // 0x4E = 01001110
  64529. // ----
  64530. tmp1 = SIMD.Float32x4.mul(row1, row2);
  64531. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64532. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor0);
  64533. var minor3 = SIMD.Float32x4.mul(row0, tmp1);
  64534. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64535. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row3, tmp1));
  64536. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor3);
  64537. minor3 = SIMD.Float32x4.swizzle(minor3, 2, 3, 0, 1); // 0x4E = 01001110
  64538. // ----
  64539. tmp1 = SIMD.Float32x4.mul(SIMD.Float32x4.swizzle(row1, 2, 3, 0, 1), row3); // 0x4E = 01001110
  64540. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64541. row2 = SIMD.Float32x4.swizzle(row2, 2, 3, 0, 1); // 0x4E = 01001110
  64542. minor0 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor0);
  64543. var minor2 = SIMD.Float32x4.mul(row0, tmp1);
  64544. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64545. minor0 = SIMD.Float32x4.sub(minor0, SIMD.Float32x4.mul(row2, tmp1));
  64546. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row0, tmp1), minor2);
  64547. minor2 = SIMD.Float32x4.swizzle(minor2, 2, 3, 0, 1); // 0x4E = 01001110
  64548. // ----
  64549. tmp1 = SIMD.Float32x4.mul(row0, row1);
  64550. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64551. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64552. minor3 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row2, tmp1), minor3);
  64553. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64554. minor2 = SIMD.Float32x4.sub(SIMD.Float32x4.mul(row3, tmp1), minor2);
  64555. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row2, tmp1));
  64556. // ----
  64557. tmp1 = SIMD.Float32x4.mul(row0, row3);
  64558. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64559. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row2, tmp1));
  64560. minor2 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor2);
  64561. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64562. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row2, tmp1), minor1);
  64563. minor2 = SIMD.Float32x4.sub(minor2, SIMD.Float32x4.mul(row1, tmp1));
  64564. // ----
  64565. tmp1 = SIMD.Float32x4.mul(row0, row2);
  64566. tmp1 = SIMD.Float32x4.swizzle(tmp1, 1, 0, 3, 2); // 0xB1 = 10110001
  64567. minor1 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row3, tmp1), minor1);
  64568. minor3 = SIMD.Float32x4.sub(minor3, SIMD.Float32x4.mul(row1, tmp1));
  64569. tmp1 = SIMD.Float32x4.swizzle(tmp1, 2, 3, 0, 1); // 0x4E = 01001110
  64570. minor1 = SIMD.Float32x4.sub(minor1, SIMD.Float32x4.mul(row3, tmp1));
  64571. minor3 = SIMD.Float32x4.add(SIMD.Float32x4.mul(row1, tmp1), minor3);
  64572. // Compute determinant
  64573. var det = SIMD.Float32x4.mul(row0, minor0);
  64574. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 2, 3, 0, 1), det); // 0x4E = 01001110
  64575. det = SIMD.Float32x4.add(SIMD.Float32x4.swizzle(det, 1, 0, 3, 2), det); // 0xB1 = 10110001
  64576. tmp1 = SIMD.Float32x4.reciprocalApproximation(det);
  64577. det = SIMD.Float32x4.sub(SIMD.Float32x4.add(tmp1, tmp1), SIMD.Float32x4.mul(det, SIMD.Float32x4.mul(tmp1, tmp1)));
  64578. det = SIMD.Float32x4.swizzle(det, 0, 0, 0, 0);
  64579. // These shuffles aren't necessary if the faulty transposition is done
  64580. // up at the top of this function.
  64581. //minor0 =SIMD.Float32x4.swizzle(minor0, 2, 1, 0, 3);
  64582. //minor1 =SIMD.Float32x4.swizzle(minor1, 2, 1, 0, 3);
  64583. //minor2 =SIMD.Float32x4.swizzle(minor2, 2, 1, 0, 3);
  64584. //minor3 =SIMD.Float32x4.swizzle(minor3, 2, 1, 0, 3);
  64585. // Compute final values by multiplying with 1/det
  64586. SIMD.Float32x4.store(dest, 0, SIMD.Float32x4.mul(det, minor0));
  64587. SIMD.Float32x4.store(dest, 4, SIMD.Float32x4.mul(det, minor1));
  64588. SIMD.Float32x4.store(dest, 8, minor2 = SIMD.Float32x4.mul(det, minor2));
  64589. SIMD.Float32x4.store(dest, 12, SIMD.Float32x4.mul(det, minor3));
  64590. return this;
  64591. };
  64592. SIMDMatrix.LookAtLHToRefSIMD = function (eyeRef, targetRef, upRef, result) {
  64593. var out = result.m;
  64594. var center = SIMD.Float32x4(targetRef.x, targetRef.y, targetRef.z, 0.0);
  64595. var eye = SIMD.Float32x4(eyeRef.x, eyeRef.y, eyeRef.z, 0.0);
  64596. var up = SIMD.Float32x4(upRef.x, upRef.y, upRef.z, 0.0);
  64597. // cc.kmVec3Subtract(f, pCenter, pEye);
  64598. var f = SIMD.Float32x4.sub(center, eye);
  64599. // cc.kmVec3Normalize(f, f);
  64600. var tmp = SIMD.Float32x4.mul(f, f);
  64601. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64602. f = SIMD.Float32x4.mul(f, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64603. // cc.kmVec3Assign(up, pUp);
  64604. // cc.kmVec3Normalize(up, up);
  64605. tmp = SIMD.Float32x4.mul(up, up);
  64606. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64607. up = SIMD.Float32x4.mul(up, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64608. // cc.kmVec3Cross(s, f, up);
  64609. 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)));
  64610. // cc.kmVec3Normalize(s, s);
  64611. tmp = SIMD.Float32x4.mul(s, s);
  64612. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64613. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64614. // cc.kmVec3Cross(u, s, f);
  64615. 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)));
  64616. // cc.kmVec3Normalize(s, s);
  64617. tmp = SIMD.Float32x4.mul(s, s);
  64618. tmp = SIMD.Float32x4.add(tmp, SIMD.Float32x4.add(SIMD.Float32x4.swizzle(tmp, 1, 2, 0, 3), SIMD.Float32x4.swizzle(tmp, 2, 0, 1, 3)));
  64619. s = SIMD.Float32x4.mul(s, SIMD.Float32x4.reciprocalSqrtApproximation(tmp));
  64620. var zero = SIMD.Float32x4.splat(0.0);
  64621. s = SIMD.Float32x4.neg(s);
  64622. var tmp01 = SIMD.Float32x4.shuffle(s, u, 0, 1, 4, 5);
  64623. var tmp23 = SIMD.Float32x4.shuffle(f, zero, 0, 1, 4, 5);
  64624. var a0 = SIMD.Float32x4.shuffle(tmp01, tmp23, 0, 2, 4, 6);
  64625. var a1 = SIMD.Float32x4.shuffle(tmp01, tmp23, 1, 3, 5, 7);
  64626. 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);
  64627. var a3 = SIMD.Float32x4(0.0, 0.0, 0.0, 1.0);
  64628. var b = SIMD.Float32x4(1.0, 0.0, 0.0, 0.0);
  64629. 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)))));
  64630. b = SIMD.Float32x4(0.0, 1.0, 0.0, 0.0);
  64631. 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)))));
  64632. b = SIMD.Float32x4(0.0, 0.0, 1.0, 0.0);
  64633. 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)))));
  64634. b = SIMD.Float32x4.replaceLane(SIMD.Float32x4.neg(eye), 3, 1.0);
  64635. 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)))));
  64636. };
  64637. return SIMDMatrix;
  64638. }());
  64639. var previousMultiplyToArray = BABYLON.Matrix.prototype.multiplyToArray;
  64640. var previousInvertToRef = BABYLON.Matrix.prototype.invertToRef;
  64641. var previousLookAtLHToRef = BABYLON.Matrix.LookAtLHToRef;
  64642. var previousTransformCoordinatesToRef = BABYLON.Vector3.TransformCoordinatesToRef;
  64643. var previousTransformCoordinatesFromFloatsToRef = BABYLON.Vector3.TransformCoordinatesFromFloatsToRef;
  64644. var SIMDHelper = (function () {
  64645. function SIMDHelper() {
  64646. }
  64647. Object.defineProperty(SIMDHelper, "IsEnabled", {
  64648. get: function () {
  64649. return SIMDHelper._isEnabled;
  64650. },
  64651. enumerable: true,
  64652. configurable: true
  64653. });
  64654. SIMDHelper.DisableSIMD = function () {
  64655. // Replace functions
  64656. BABYLON.Matrix.prototype.multiplyToArray = previousMultiplyToArray;
  64657. BABYLON.Matrix.prototype.invertToRef = previousInvertToRef;
  64658. BABYLON.Matrix.LookAtLHToRef = previousLookAtLHToRef;
  64659. BABYLON.Vector3.TransformCoordinatesToRef = previousTransformCoordinatesToRef;
  64660. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = previousTransformCoordinatesFromFloatsToRef;
  64661. SIMDHelper._isEnabled = false;
  64662. };
  64663. SIMDHelper.EnableSIMD = function () {
  64664. if (self.SIMD === undefined) {
  64665. return;
  64666. }
  64667. // check if polyfills needed
  64668. if (!self.Math.fround) {
  64669. self.Math.fround = (function (array) { return function (x) {
  64670. return array[0] = x, array[0];
  64671. }; })(new Float32Array(1));
  64672. }
  64673. if (!self.Math.imul) {
  64674. self.Math.imul = function (a, b) {
  64675. var ah = (a >>> 16) & 0xffff;
  64676. var al = a & 0xffff;
  64677. var bh = (b >>> 16) & 0xffff;
  64678. var bl = b & 0xffff;
  64679. // the shift by 0 fixes the sign on the high part
  64680. // the final |0 converts the unsigned value into a signed value
  64681. return ((al * bl) + (((ah * bl + al * bh) << 16) >>> 0) | 0);
  64682. };
  64683. }
  64684. // Replace functions
  64685. BABYLON.Matrix.prototype.multiplyToArray = SIMDMatrix.prototype.multiplyToArraySIMD;
  64686. BABYLON.Matrix.prototype.invertToRef = SIMDMatrix.prototype.invertToRefSIMD;
  64687. BABYLON.Matrix.LookAtLHToRef = SIMDMatrix.LookAtLHToRefSIMD;
  64688. BABYLON.Vector3.TransformCoordinatesToRef = SIMDVector3.TransformCoordinatesToRefSIMD;
  64689. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef = SIMDVector3.TransformCoordinatesFromFloatsToRefSIMD;
  64690. SIMDHelper._isEnabled = true;
  64691. };
  64692. SIMDHelper._isEnabled = false;
  64693. return SIMDHelper;
  64694. }());
  64695. BABYLON.SIMDHelper = SIMDHelper;
  64696. })(BABYLON || (BABYLON = {}));
  64697. //# sourceMappingURL=babylon.math.SIMD.js.map
  64698. var BABYLON;
  64699. (function (BABYLON) {
  64700. var VRDistortionCorrectionPostProcess = (function (_super) {
  64701. __extends(VRDistortionCorrectionPostProcess, _super);
  64702. //ANY
  64703. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  64704. var _this = _super.call(this, name, "vrDistortionCorrection", [
  64705. 'LensCenter',
  64706. 'Scale',
  64707. 'ScaleIn',
  64708. 'HmdWarpParam'
  64709. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE, null, null) || this;
  64710. _this._isRightEye = isRightEye;
  64711. _this._distortionFactors = vrMetrics.distortionK;
  64712. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  64713. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  64714. _this.onSizeChangedObservable.add(function () {
  64715. _this.aspectRatio = _this.width * .5 / _this.height;
  64716. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  64717. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  64718. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  64719. });
  64720. _this.onApplyObservable.add(function (effect) {
  64721. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  64722. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  64723. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  64724. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  64725. });
  64726. return _this;
  64727. }
  64728. return VRDistortionCorrectionPostProcess;
  64729. }(BABYLON.PostProcess));
  64730. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  64731. })(BABYLON || (BABYLON = {}));
  64732. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  64733. var BABYLON;
  64734. (function (BABYLON) {
  64735. var AnaglyphPostProcess = (function (_super) {
  64736. __extends(AnaglyphPostProcess, _super);
  64737. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  64738. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  64739. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64740. _this.onApplyObservable.add(function (effect) {
  64741. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  64742. });
  64743. return _this;
  64744. }
  64745. return AnaglyphPostProcess;
  64746. }(BABYLON.PostProcess));
  64747. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  64748. })(BABYLON || (BABYLON = {}));
  64749. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  64750. var BABYLON;
  64751. (function (BABYLON) {
  64752. var StereoscopicInterlacePostProcess = (function (_super) {
  64753. __extends(StereoscopicInterlacePostProcess, _super);
  64754. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  64755. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  64756. _this._passedProcess = rigCameras[0]._rigPostProcess;
  64757. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64758. _this.onSizeChangedObservable.add(function () {
  64759. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  64760. });
  64761. _this.onApplyObservable.add(function (effect) {
  64762. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  64763. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  64764. });
  64765. return _this;
  64766. }
  64767. return StereoscopicInterlacePostProcess;
  64768. }(BABYLON.PostProcess));
  64769. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  64770. })(BABYLON || (BABYLON = {}));
  64771. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  64772. var BABYLON;
  64773. (function (BABYLON) {
  64774. var FreeCameraDeviceOrientationInput = (function () {
  64775. function FreeCameraDeviceOrientationInput() {
  64776. var _this = this;
  64777. this._screenOrientationAngle = 0;
  64778. this._screenQuaternion = new BABYLON.Quaternion();
  64779. this._alpha = 0;
  64780. this._beta = 0;
  64781. this._gamma = 0;
  64782. this._orientationChanged = function () {
  64783. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  64784. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  64785. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  64786. };
  64787. this._deviceOrientation = function (evt) {
  64788. _this._alpha = evt.alpha;
  64789. _this._beta = evt.beta;
  64790. _this._gamma = evt.gamma;
  64791. };
  64792. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  64793. this._orientationChanged();
  64794. }
  64795. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  64796. get: function () {
  64797. return this._camera;
  64798. },
  64799. set: function (camera) {
  64800. this._camera = camera;
  64801. if (this._camera != null && !this._camera.rotationQuaternion) {
  64802. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  64803. }
  64804. },
  64805. enumerable: true,
  64806. configurable: true
  64807. });
  64808. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64809. window.addEventListener("orientationchange", this._orientationChanged);
  64810. window.addEventListener("deviceorientation", this._deviceOrientation);
  64811. //In certain cases, the attach control is called AFTER orientation was changed,
  64812. //So this is needed.
  64813. this._orientationChanged();
  64814. };
  64815. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  64816. window.removeEventListener("orientationchange", this._orientationChanged);
  64817. window.removeEventListener("deviceorientation", this._deviceOrientation);
  64818. };
  64819. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  64820. //if no device orientation provided, don't update the rotation.
  64821. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  64822. if (!this._alpha)
  64823. return;
  64824. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  64825. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  64826. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  64827. //Mirror on XY Plane
  64828. this._camera.rotationQuaternion.z *= -1;
  64829. this._camera.rotationQuaternion.w *= -1;
  64830. };
  64831. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  64832. return "FreeCameraDeviceOrientationInput";
  64833. };
  64834. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  64835. return "deviceOrientation";
  64836. };
  64837. return FreeCameraDeviceOrientationInput;
  64838. }());
  64839. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  64840. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  64841. })(BABYLON || (BABYLON = {}));
  64842. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  64843. var BABYLON;
  64844. (function (BABYLON) {
  64845. var ArcRotateCameraVRDeviceOrientationInput = (function () {
  64846. function ArcRotateCameraVRDeviceOrientationInput() {
  64847. this.alphaCorrection = 1;
  64848. this.betaCorrection = 1;
  64849. this.gammaCorrection = 1;
  64850. this._alpha = 0;
  64851. this._beta = 0;
  64852. this._gamma = 0;
  64853. this._dirty = false;
  64854. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  64855. }
  64856. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  64857. this.camera.attachControl(element, noPreventDefault);
  64858. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  64859. };
  64860. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  64861. var camera = this.camera;
  64862. this._alpha = +evt.alpha | 0;
  64863. this._beta = +evt.beta | 0;
  64864. this._gamma = +evt.gamma | 0;
  64865. this._dirty = true;
  64866. };
  64867. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  64868. if (this._dirty) {
  64869. this._dirty = false;
  64870. if (this._gamma < 0) {
  64871. this._gamma = 180 + this._gamma;
  64872. }
  64873. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  64874. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  64875. }
  64876. };
  64877. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  64878. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  64879. };
  64880. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  64881. return "ArcRotateCameraVRDeviceOrientationInput";
  64882. };
  64883. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  64884. return "VRDeviceOrientation";
  64885. };
  64886. return ArcRotateCameraVRDeviceOrientationInput;
  64887. }());
  64888. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  64889. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  64890. })(BABYLON || (BABYLON = {}));
  64891. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  64892. var BABYLON;
  64893. (function (BABYLON) {
  64894. var VRCameraMetrics = (function () {
  64895. function VRCameraMetrics() {
  64896. this.compensateDistortion = true;
  64897. }
  64898. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  64899. get: function () {
  64900. return this.hResolution / (2 * this.vResolution);
  64901. },
  64902. enumerable: true,
  64903. configurable: true
  64904. });
  64905. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  64906. get: function () {
  64907. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  64908. },
  64909. enumerable: true,
  64910. configurable: true
  64911. });
  64912. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  64913. get: function () {
  64914. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64915. var h = (4 * meters) / this.hScreenSize;
  64916. return BABYLON.Matrix.Translation(h, 0, 0);
  64917. },
  64918. enumerable: true,
  64919. configurable: true
  64920. });
  64921. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  64922. get: function () {
  64923. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  64924. var h = (4 * meters) / this.hScreenSize;
  64925. return BABYLON.Matrix.Translation(-h, 0, 0);
  64926. },
  64927. enumerable: true,
  64928. configurable: true
  64929. });
  64930. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  64931. get: function () {
  64932. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  64933. },
  64934. enumerable: true,
  64935. configurable: true
  64936. });
  64937. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  64938. get: function () {
  64939. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  64940. },
  64941. enumerable: true,
  64942. configurable: true
  64943. });
  64944. VRCameraMetrics.GetDefault = function () {
  64945. var result = new VRCameraMetrics();
  64946. result.hResolution = 1280;
  64947. result.vResolution = 800;
  64948. result.hScreenSize = 0.149759993;
  64949. result.vScreenSize = 0.0935999975;
  64950. result.vScreenCenter = 0.0467999987;
  64951. result.eyeToScreenDistance = 0.0410000011;
  64952. result.lensSeparationDistance = 0.0635000020;
  64953. result.interpupillaryDistance = 0.0640000030;
  64954. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  64955. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  64956. result.postProcessScaleFactor = 1.714605507808412;
  64957. result.lensCenterOffset = 0.151976421;
  64958. return result;
  64959. };
  64960. return VRCameraMetrics;
  64961. }());
  64962. BABYLON.VRCameraMetrics = VRCameraMetrics;
  64963. })(BABYLON || (BABYLON = {}));
  64964. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  64965. var BABYLON;
  64966. (function (BABYLON) {
  64967. var WebVRFreeCamera = (function (_super) {
  64968. __extends(WebVRFreeCamera, _super);
  64969. function WebVRFreeCamera(name, position, scene, webVROptions) {
  64970. if (webVROptions === void 0) { webVROptions = {}; }
  64971. var _this = _super.call(this, name, position, scene) || this;
  64972. _this.webVROptions = webVROptions;
  64973. _this._vrDevice = null;
  64974. _this.rawPose = null;
  64975. _this._vrEnabled = false;
  64976. _this._specsVersion = 1.1;
  64977. _this._attached = false;
  64978. _this._positionOffset = BABYLON.Vector3.Zero();
  64979. _this._descendants = [];
  64980. _this.devicePosition = BABYLON.Vector3.Zero();
  64981. _this.deviceScaleFactor = 1;
  64982. _this.controllers = [];
  64983. _this.onControllersAttachedObservable = new BABYLON.Observable();
  64984. _this.rigParenting = true; // should the rig cameras be used as parent instead of this camera.
  64985. _this.minZ = 0.1;
  64986. //legacy support - the compensation boolean was removed.
  64987. if (arguments.length === 5) {
  64988. _this.webVROptions = arguments[4];
  64989. }
  64990. // default webVR options
  64991. if (_this.webVROptions.trackPosition == undefined) {
  64992. _this.webVROptions.trackPosition = true;
  64993. }
  64994. if (_this.webVROptions.controllerMeshes == undefined) {
  64995. _this.webVROptions.controllerMeshes = true;
  64996. }
  64997. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  64998. _this.webVROptions.defaultLightingOnControllers = true;
  64999. }
  65000. _this.rotationQuaternion = new BABYLON.Quaternion();
  65001. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  65002. if (_this.webVROptions && _this.webVROptions.positionScale) {
  65003. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  65004. }
  65005. //enable VR
  65006. _this.getEngine().initWebVR();
  65007. //check specs version
  65008. if (!window.VRFrameData) {
  65009. _this._specsVersion = 1.0;
  65010. _this._frameData = {};
  65011. }
  65012. else {
  65013. _this._frameData = new VRFrameData();
  65014. }
  65015. _this.getEngine().getVRDevice(_this.webVROptions.displayName, function (device) {
  65016. if (!device) {
  65017. return;
  65018. }
  65019. _this._vrEnabled = true;
  65020. _this._vrDevice = device;
  65021. //reset the rig parameters.
  65022. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  65023. if (_this._attached) {
  65024. _this.getEngine().enableVR(_this._vrDevice);
  65025. }
  65026. });
  65027. /**
  65028. * The idea behind the following lines:
  65029. * objects that have the camera as parent should actually have the rig cameras as a parent.
  65030. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  65031. * the second will not show it correctly.
  65032. *
  65033. * To solve this - each object that has the camera as parent will be added to a protected array.
  65034. * When the rig camera renders, it will take this array and set all of those to be its children.
  65035. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  65036. * Amazing!
  65037. */
  65038. scene.onBeforeCameraRenderObservable.add(function (camera) {
  65039. if (camera.parent === _this && _this.rigParenting) {
  65040. _this._descendants = _this.getDescendants(true, function (n) {
  65041. // don't take the cameras or the controllers!
  65042. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  65043. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  65044. return !isController && !isRigCamera;
  65045. });
  65046. _this._descendants.forEach(function (node) {
  65047. node.parent = camera;
  65048. });
  65049. }
  65050. });
  65051. scene.onAfterCameraRenderObservable.add(function (camera) {
  65052. if (camera.parent === _this && _this.rigParenting) {
  65053. _this._descendants.forEach(function (node) {
  65054. node.parent = _this;
  65055. });
  65056. }
  65057. });
  65058. return _this;
  65059. }
  65060. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  65061. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  65062. var gp = _a[_i];
  65063. if (gp.hand === name) {
  65064. return gp;
  65065. }
  65066. }
  65067. return undefined;
  65068. };
  65069. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  65070. get: function () {
  65071. if (!this._leftController) {
  65072. this._leftController = this.getControllerByName("left");
  65073. }
  65074. return this._leftController;
  65075. },
  65076. enumerable: true,
  65077. configurable: true
  65078. });
  65079. ;
  65080. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  65081. get: function () {
  65082. if (!this._rightController) {
  65083. this._rightController = this.getControllerByName("right");
  65084. }
  65085. return this._rightController;
  65086. },
  65087. enumerable: true,
  65088. configurable: true
  65089. });
  65090. ;
  65091. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  65092. if (length === void 0) { length = 100; }
  65093. if (this.leftCamera) {
  65094. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.position.add(this.devicePosition)); // Need the actual rendered camera
  65095. }
  65096. else {
  65097. return _super.prototype.getForwardRay.call(this, length);
  65098. }
  65099. };
  65100. WebVRFreeCamera.prototype._checkInputs = function () {
  65101. if (this._vrEnabled) {
  65102. if (this._specsVersion === 1.1) {
  65103. this._vrDevice.getFrameData(this._frameData);
  65104. }
  65105. else {
  65106. //backwards comp
  65107. var pose = this._vrDevice.getPose();
  65108. this._frameData.pose = pose;
  65109. }
  65110. this.updateFromDevice(this._frameData.pose);
  65111. }
  65112. _super.prototype._checkInputs.call(this);
  65113. };
  65114. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  65115. if (poseData && poseData.orientation) {
  65116. this.rawPose = poseData;
  65117. this.deviceRotationQuaternion.copyFromFloats(this.rawPose.orientation[0], this.rawPose.orientation[1], -this.rawPose.orientation[2], -this.rawPose.orientation[3]);
  65118. if (this.getScene().useRightHandedSystem) {
  65119. this.deviceRotationQuaternion.z *= -1;
  65120. this.deviceRotationQuaternion.w *= -1;
  65121. }
  65122. if (this.webVROptions.trackPosition && this.rawPose.position) {
  65123. this.devicePosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  65124. if (this.getScene().useRightHandedSystem) {
  65125. this.devicePosition.z *= -1;
  65126. }
  65127. }
  65128. }
  65129. };
  65130. /**
  65131. * WebVR's attach control will start broadcasting frames to the device.
  65132. * Note that in certain browsers (chrome for example) this function must be called
  65133. * within a user-interaction callback. Example:
  65134. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  65135. *
  65136. * @param {HTMLElement} element
  65137. * @param {boolean} [noPreventDefault]
  65138. *
  65139. * @memberOf WebVRFreeCamera
  65140. */
  65141. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  65142. _super.prototype.attachControl.call(this, element, noPreventDefault);
  65143. this._attached = true;
  65144. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  65145. if (this._vrEnabled) {
  65146. this.getEngine().enableVR(this._vrDevice);
  65147. }
  65148. // try to attach the controllers, if found.
  65149. this.initControllers();
  65150. };
  65151. WebVRFreeCamera.prototype.detachControl = function (element) {
  65152. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  65153. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  65154. _super.prototype.detachControl.call(this, element);
  65155. this._vrEnabled = false;
  65156. this._attached = false;
  65157. this.getEngine().disableVR();
  65158. };
  65159. WebVRFreeCamera.prototype.getClassName = function () {
  65160. return "WebVRFreeCamera";
  65161. };
  65162. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  65163. //uses the vrDisplay's "resetPose()".
  65164. //pitch and roll won't be affected.
  65165. this._vrDevice.resetPose();
  65166. };
  65167. WebVRFreeCamera.prototype._updateRigCameras = function () {
  65168. var camLeft = this._rigCameras[0];
  65169. var camRight = this._rigCameras[1];
  65170. camLeft.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65171. camRight.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  65172. camLeft.position.copyFrom(this.devicePosition);
  65173. camRight.position.copyFrom(this.devicePosition);
  65174. };
  65175. /**
  65176. * This function is called by the two RIG cameras.
  65177. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  65178. */
  65179. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  65180. var _this = this;
  65181. //WebVR 1.0
  65182. if (this._cameraRigParams["specs"] === 1.0) {
  65183. this._updateCameraRotationMatrix();
  65184. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65185. // Computing target and final matrix
  65186. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65187. if (this.getScene().useRightHandedSystem) {
  65188. BABYLON.Matrix.LookAtRHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65189. }
  65190. else {
  65191. BABYLON.Matrix.LookAtLHToRef(this.position, this._currentTarget, this.upVector, this._webvrViewMatrix);
  65192. }
  65193. //now move the eye in the right direction
  65194. var eyeParams = this._cameraRigParams["eyeParameters"];
  65195. var offset = eyeParams.offset;
  65196. // it will actually always be 0, but just in case
  65197. if (this.getScene().useRightHandedSystem) {
  65198. offset[2] *= -1;
  65199. }
  65200. BABYLON.Matrix.TranslationToRef(-offset[0], offset[1], -offset[2], BABYLON.Tmp.Matrix[0]);
  65201. this._webvrViewMatrix.multiplyToRef(BABYLON.Tmp.Matrix[0], this._webvrViewMatrix);
  65202. }
  65203. else {
  65204. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  65205. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  65206. if (!this.getScene().useRightHandedSystem) {
  65207. [2, 6, 8, 9, 14].forEach(function (num) {
  65208. _this._webvrViewMatrix.m[num] *= -1;
  65209. });
  65210. }
  65211. // update the camera rotation matrix
  65212. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  65213. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  65214. // Computing target and final matrix
  65215. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  65216. }
  65217. var parentCamera = this._cameraRigParams["parentCamera"];
  65218. // should the view matrix be updated with scale and position offset?
  65219. if (parentCamera.deviceScaleFactor !== 1) {
  65220. this._webvrViewMatrix.invert();
  65221. // scale the position, if set
  65222. if (parentCamera.deviceScaleFactor) {
  65223. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  65224. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  65225. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  65226. }
  65227. this._webvrViewMatrix.invert();
  65228. }
  65229. return this._webvrViewMatrix;
  65230. };
  65231. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  65232. var _this = this;
  65233. if (this._cameraRigParams["specs"] === 1.0) {
  65234. var eyeParams = this._cameraRigParams["eyeParameters"];
  65235. // deprecated!!
  65236. BABYLON.Matrix.PerspectiveFovWebVRToRef(eyeParams.fieldOfView, this.minZ, this.maxZ, this._projectionMatrix, this.getScene().useRightHandedSystem);
  65237. }
  65238. else {
  65239. var parentCamera = this.parent;
  65240. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  65241. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  65242. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  65243. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  65244. //babylon compatible matrix
  65245. if (!this.getScene().useRightHandedSystem) {
  65246. [8, 9, 10, 11].forEach(function (num) {
  65247. _this._projectionMatrix.m[num] *= -1;
  65248. });
  65249. }
  65250. }
  65251. return this._projectionMatrix;
  65252. };
  65253. WebVRFreeCamera.prototype.initControllers = function () {
  65254. var _this = this;
  65255. this.controllers = [];
  65256. var manager = this.getScene().gamepadManager;
  65257. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  65258. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65259. var webVrController = gamepad;
  65260. var index = _this.controllers.indexOf(webVrController);
  65261. if (index === -1) {
  65262. // we are good
  65263. return;
  65264. }
  65265. _this.controllers.splice(index, 1);
  65266. }
  65267. });
  65268. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  65269. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  65270. var webVrController = gamepad;
  65271. if (_this.webVROptions.controllerMeshes) {
  65272. webVrController.initControllerMesh(_this.getScene(), function (loadedMesh) {
  65273. if (_this.webVROptions.defaultLightingOnControllers) {
  65274. if (!_this._lightOnControllers) {
  65275. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  65276. }
  65277. loadedMesh.getChildren().forEach(function (mesh) {
  65278. _this._lightOnControllers.includedOnlyMeshes.push(mesh);
  65279. });
  65280. }
  65281. });
  65282. }
  65283. webVrController.attachToPoseControlledCamera(_this);
  65284. // since this is async - sanity check. Is the controller already stored?
  65285. if (_this.controllers.indexOf(webVrController) === -1) {
  65286. //add to the controllers array
  65287. _this.controllers.push(webVrController);
  65288. //did we find enough controllers? Great! let the developer know.
  65289. if (_this.controllers.length >= 2) {
  65290. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  65291. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  65292. // So we're overriding setting left & right manually to be sure
  65293. var firstViveWandDetected = false;
  65294. for (var i = 0; i < _this.controllers.length; i++) {
  65295. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  65296. if (!firstViveWandDetected) {
  65297. firstViveWandDetected = true;
  65298. _this.controllers[i].hand = "left";
  65299. }
  65300. else {
  65301. _this.controllers[i].hand = "right";
  65302. }
  65303. }
  65304. }
  65305. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  65306. }
  65307. }
  65308. }
  65309. });
  65310. };
  65311. return WebVRFreeCamera;
  65312. }(BABYLON.FreeCamera));
  65313. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  65314. })(BABYLON || (BABYLON = {}));
  65315. //# sourceMappingURL=babylon.webVRCamera.js.map
  65316. /// <reference path="babylon.freeCamera.ts" />
  65317. var BABYLON;
  65318. (function (BABYLON) {
  65319. // We're mainly based on the logic defined into the FreeCamera code
  65320. var DeviceOrientationCamera = (function (_super) {
  65321. __extends(DeviceOrientationCamera, _super);
  65322. function DeviceOrientationCamera(name, position, scene) {
  65323. var _this = _super.call(this, name, position, scene) || this;
  65324. _this._quaternionCache = new BABYLON.Quaternion();
  65325. _this.inputs.addDeviceOrientation();
  65326. return _this;
  65327. }
  65328. DeviceOrientationCamera.prototype.getClassName = function () {
  65329. return "DeviceOrientationCamera";
  65330. };
  65331. DeviceOrientationCamera.prototype._checkInputs = function () {
  65332. _super.prototype._checkInputs.call(this);
  65333. this._quaternionCache.copyFrom(this.rotationQuaternion);
  65334. if (this._initialQuaternion) {
  65335. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65336. }
  65337. };
  65338. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  65339. var _this = this;
  65340. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  65341. //can only work if this camera has a rotation quaternion already.
  65342. if (!this.rotationQuaternion)
  65343. return;
  65344. if (!this._initialQuaternion) {
  65345. this._initialQuaternion = new BABYLON.Quaternion();
  65346. }
  65347. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  65348. ['x', 'y', 'z'].forEach(function (axisName) {
  65349. if (!axis[axisName]) {
  65350. _this._initialQuaternion[axisName] = 0;
  65351. }
  65352. else {
  65353. _this._initialQuaternion[axisName] *= -1;
  65354. }
  65355. });
  65356. this._initialQuaternion.normalize();
  65357. //force rotation update
  65358. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  65359. };
  65360. return DeviceOrientationCamera;
  65361. }(BABYLON.FreeCamera));
  65362. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  65363. })(BABYLON || (BABYLON = {}));
  65364. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  65365. var BABYLON;
  65366. (function (BABYLON) {
  65367. var VRDeviceOrientationFreeCamera = (function (_super) {
  65368. __extends(VRDeviceOrientationFreeCamera, _super);
  65369. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65370. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65371. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65372. var _this = _super.call(this, name, position, scene) || this;
  65373. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65374. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65375. return _this;
  65376. }
  65377. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  65378. return "VRDeviceOrientationFreeCamera";
  65379. };
  65380. return VRDeviceOrientationFreeCamera;
  65381. }(BABYLON.DeviceOrientationCamera));
  65382. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  65383. var VRDeviceOrientationGamepadCamera = (function (_super) {
  65384. __extends(VRDeviceOrientationGamepadCamera, _super);
  65385. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  65386. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65387. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65388. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  65389. _this.inputs.addGamepad();
  65390. return _this;
  65391. }
  65392. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  65393. return "VRDeviceOrientationGamepadCamera";
  65394. };
  65395. return VRDeviceOrientationGamepadCamera;
  65396. }(VRDeviceOrientationFreeCamera));
  65397. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  65398. var VRDeviceOrientationArcRotateCamera = (function (_super) {
  65399. __extends(VRDeviceOrientationArcRotateCamera, _super);
  65400. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  65401. if (compensateDistortion === void 0) { compensateDistortion = true; }
  65402. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  65403. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65404. vrCameraMetrics.compensateDistortion = compensateDistortion;
  65405. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  65406. _this.inputs.addVRDeviceOrientation();
  65407. return _this;
  65408. }
  65409. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  65410. return "VRDeviceOrientationArcRotateCamera";
  65411. };
  65412. return VRDeviceOrientationArcRotateCamera;
  65413. }(BABYLON.ArcRotateCamera));
  65414. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  65415. })(BABYLON || (BABYLON = {}));
  65416. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  65417. /// <reference path="babylon.freeCamera.ts" />
  65418. /// <reference path="babylon.arcRotateCamera.ts" />
  65419. /// <reference path="babylon.gamepadCamera.ts" />
  65420. /// <reference path="babylon.universalCamera.ts" />
  65421. var BABYLON;
  65422. (function (BABYLON) {
  65423. var AnaglyphFreeCamera = (function (_super) {
  65424. __extends(AnaglyphFreeCamera, _super);
  65425. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  65426. var _this = _super.call(this, name, position, scene) || this;
  65427. _this.interaxialDistance = interaxialDistance;
  65428. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65429. return _this;
  65430. }
  65431. AnaglyphFreeCamera.prototype.getClassName = function () {
  65432. return "AnaglyphFreeCamera";
  65433. };
  65434. return AnaglyphFreeCamera;
  65435. }(BABYLON.FreeCamera));
  65436. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  65437. var AnaglyphArcRotateCamera = (function (_super) {
  65438. __extends(AnaglyphArcRotateCamera, _super);
  65439. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  65440. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65441. _this.interaxialDistance = interaxialDistance;
  65442. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65443. return _this;
  65444. }
  65445. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  65446. return "AnaglyphArcRotateCamera";
  65447. };
  65448. return AnaglyphArcRotateCamera;
  65449. }(BABYLON.ArcRotateCamera));
  65450. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  65451. var AnaglyphGamepadCamera = (function (_super) {
  65452. __extends(AnaglyphGamepadCamera, _super);
  65453. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  65454. var _this = _super.call(this, name, position, scene) || this;
  65455. _this.interaxialDistance = interaxialDistance;
  65456. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65457. return _this;
  65458. }
  65459. AnaglyphGamepadCamera.prototype.getClassName = function () {
  65460. return "AnaglyphGamepadCamera";
  65461. };
  65462. return AnaglyphGamepadCamera;
  65463. }(BABYLON.GamepadCamera));
  65464. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  65465. var AnaglyphUniversalCamera = (function (_super) {
  65466. __extends(AnaglyphUniversalCamera, _super);
  65467. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  65468. var _this = _super.call(this, name, position, scene) || this;
  65469. _this.interaxialDistance = interaxialDistance;
  65470. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  65471. return _this;
  65472. }
  65473. AnaglyphUniversalCamera.prototype.getClassName = function () {
  65474. return "AnaglyphUniversalCamera";
  65475. };
  65476. return AnaglyphUniversalCamera;
  65477. }(BABYLON.UniversalCamera));
  65478. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  65479. var StereoscopicFreeCamera = (function (_super) {
  65480. __extends(StereoscopicFreeCamera, _super);
  65481. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65482. var _this = _super.call(this, name, position, scene) || this;
  65483. _this.interaxialDistance = interaxialDistance;
  65484. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65485. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65486. return _this;
  65487. }
  65488. StereoscopicFreeCamera.prototype.getClassName = function () {
  65489. return "StereoscopicFreeCamera";
  65490. };
  65491. return StereoscopicFreeCamera;
  65492. }(BABYLON.FreeCamera));
  65493. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  65494. var StereoscopicArcRotateCamera = (function (_super) {
  65495. __extends(StereoscopicArcRotateCamera, _super);
  65496. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  65497. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  65498. _this.interaxialDistance = interaxialDistance;
  65499. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65500. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65501. return _this;
  65502. }
  65503. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  65504. return "StereoscopicArcRotateCamera";
  65505. };
  65506. return StereoscopicArcRotateCamera;
  65507. }(BABYLON.ArcRotateCamera));
  65508. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  65509. var StereoscopicGamepadCamera = (function (_super) {
  65510. __extends(StereoscopicGamepadCamera, _super);
  65511. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65512. var _this = _super.call(this, name, position, scene) || this;
  65513. _this.interaxialDistance = interaxialDistance;
  65514. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65515. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65516. return _this;
  65517. }
  65518. StereoscopicGamepadCamera.prototype.getClassName = function () {
  65519. return "StereoscopicGamepadCamera";
  65520. };
  65521. return StereoscopicGamepadCamera;
  65522. }(BABYLON.GamepadCamera));
  65523. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  65524. var StereoscopicUniversalCamera = (function (_super) {
  65525. __extends(StereoscopicUniversalCamera, _super);
  65526. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  65527. var _this = _super.call(this, name, position, scene) || this;
  65528. _this.interaxialDistance = interaxialDistance;
  65529. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  65530. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  65531. return _this;
  65532. }
  65533. StereoscopicUniversalCamera.prototype.getClassName = function () {
  65534. return "StereoscopicUniversalCamera";
  65535. };
  65536. return StereoscopicUniversalCamera;
  65537. }(BABYLON.UniversalCamera));
  65538. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  65539. })(BABYLON || (BABYLON = {}));
  65540. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  65541. var BABYLON;
  65542. (function (BABYLON) {
  65543. var VRExperienceHelper = (function () {
  65544. function VRExperienceHelper(scene, webVROptions) {
  65545. if (webVROptions === void 0) { webVROptions = {}; }
  65546. var _this = this;
  65547. this.webVROptions = webVROptions;
  65548. this._webVRsupportedAndReady = false;
  65549. this._isInVRMode = false;
  65550. this._scene = scene;
  65551. if (!this._scene.activeCamera) {
  65552. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", new BABYLON.Vector3(0, 2, 0), scene);
  65553. }
  65554. else {
  65555. var newCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._scene.activeCamera.position, scene);
  65556. if (scene.activeCamera.rotation) {
  65557. newCamera.rotation = scene.activeCamera.rotation.clone();
  65558. }
  65559. this._scene.activeCamera = newCamera;
  65560. }
  65561. this._position = this._scene.activeCamera.position;
  65562. this._canvas = scene.getEngine().getRenderingCanvas();
  65563. this._scene.activeCamera.attachControl(this._canvas);
  65564. this._btnVR = document.createElement("BUTTON");
  65565. this._btnVR.className = "babylonVRicon";
  65566. this._btnVR.id = "babylonVRiconbtn";
  65567. this._btnVR.title = "Click to switch to VR";
  65568. var css = ".babylonVRicon { position: absolute; right: 20px; height: 50px; width: 80px; background-color: rgba(51,51,51,0.7); background-image: url(data:image/svg+xml;charset=UTF-8,%3Csvg%20xmlns%3D%22http%3A//www.w3.org/2000/svg%22%20width%3D%222048%22%20height%3D%221152%22%20viewBox%3D%220%200%202048%201152%22%20version%3D%221.1%22%3E%3Cpath%20transform%3D%22rotate%28180%201024%2C576.0000000000001%29%22%20d%3D%22m1109%2C896q17%2C0%2030%2C-12t13%2C-30t-12.5%2C-30.5t-30.5%2C-12.5l-170%2C0q-18%2C0%20-30.5%2C12.5t-12.5%2C30.5t13%2C30t30%2C12l170%2C0zm-85%2C256q59%2C0%20132.5%2C-1.5t154.5%2C-5.5t164.5%2C-11.5t163%2C-20t150%2C-30t124.5%2C-41.5q23%2C-11%2042%2C-24t38%2C-30q27%2C-25%2041%2C-61.5t14%2C-72.5l0%2C-257q0%2C-123%20-47%2C-232t-128%2C-190t-190%2C-128t-232%2C-47l-81%2C0q-37%2C0%20-68.5%2C14t-60.5%2C34.5t-55.5%2C45t-53%2C45t-53%2C34.5t-55.5%2C14t-55.5%2C-14t-53%2C-34.5t-53%2C-45t-55.5%2C-45t-60.5%2C-34.5t-68.5%2C-14l-81%2C0q-123%2C0%20-232%2C47t-190%2C128t-128%2C190t-47%2C232l0%2C257q0%2C68%2038%2C115t97%2C73q54%2C24%20124.5%2C41.5t150%2C30t163%2C20t164.5%2C11.5t154.5%2C5.5t132.5%2C1.5zm939%2C-298q0%2C39%20-24.5%2C67t-58.5%2C42q-54%2C23%20-122%2C39.5t-143.5%2C28t-155.5%2C19t-157%2C11t-148.5%2C5t-129.5%2C1.5q-59%2C0%20-130%2C-1.5t-148%2C-5t-157%2C-11t-155.5%2C-19t-143.5%2C-28t-122%2C-39.5q-34%2C-14%20-58.5%2C-42t-24.5%2C-67l0%2C-257q0%2C-106%2040.5%2C-199t110%2C-162.5t162.5%2C-109.5t199%2C-40l81%2C0q27%2C0%2052%2C14t50%2C34.5t51%2C44.5t55.5%2C44.5t63.5%2C34.5t74%2C14t74%2C-14t63.5%2C-34.5t55.5%2C-44.5t51%2C-44.5t50%2C-34.5t52%2C-14l14%2C0q37%2C0%2070%2C0.5t64.5%2C4.5t63.5%2C12t68%2C23q71%2C30%20128.5%2C78.5t98.5%2C110t63.5%2C133.5t22.5%2C149l0%2C257z%22%20fill%3D%22white%22%20/%3E%3C/svg%3E%0A); background-size: 80%; background-repeat:no-repeat; background-position: center; border: none; outline: none; transition: transform 0.125s ease-out } .babylonVRicon:hover { transform: scale(1.05) } .babylonVRicon:active {background-color: rgba(51,51,51,1) } .babylonVRicon:focus {background-color: rgba(51,51,51,1) }";
  65569. var style = document.createElement('style');
  65570. style.appendChild(document.createTextNode(css));
  65571. document.getElementsByTagName('head')[0].appendChild(style);
  65572. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  65573. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  65574. window.addEventListener("resize", function () {
  65575. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  65576. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  65577. });
  65578. // Exiting VR mode using 'ESC' key on desktop
  65579. document.addEventListener("keydown", function (event) {
  65580. if (event.keyCode === 27 && _this._isInVRMode) {
  65581. _this.exitVR();
  65582. }
  65583. });
  65584. // Exiting VR mode double tapping the touch screen
  65585. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  65586. if (_this._isInVRMode) {
  65587. _this.exitVR();
  65588. }
  65589. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  65590. if (navigator.getVRDisplays) {
  65591. navigator.getVRDisplays().then(function (headsets) {
  65592. if (headsets.length > 0) {
  65593. scene.getEngine().initWebVR();
  65594. _this._webVRsupportedAndReady = true;
  65595. }
  65596. document.body.appendChild(_this._btnVR);
  65597. });
  65598. }
  65599. else {
  65600. document.body.appendChild(this._btnVR);
  65601. }
  65602. this._btnVR.addEventListener("click", function () {
  65603. _this.enterVR();
  65604. });
  65605. }
  65606. VRExperienceHelper.prototype.enterVR = function () {
  65607. this._scene.activeCamera.dispose();
  65608. // If WebVR is supported and a headset is connected
  65609. if (this._webVRsupportedAndReady) {
  65610. this._scene.activeCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene);
  65611. }
  65612. else {
  65613. this._scene.activeCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  65614. this._scene.getEngine().switchFullscreen(true);
  65615. }
  65616. this._scene.activeCamera.attachControl(this._canvas);
  65617. this._isInVRMode = true;
  65618. this._btnVR.style.display = "none";
  65619. };
  65620. VRExperienceHelper.prototype.exitVR = function () {
  65621. if (this._webVRsupportedAndReady) {
  65622. this._scene.getEngine().disableVR();
  65623. }
  65624. if (this._scene.activeCamera) {
  65625. this._position = this._scene.activeCamera.position;
  65626. this._scene.activeCamera.dispose();
  65627. }
  65628. this._scene.activeCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position, this._scene);
  65629. this._scene.activeCamera.attachControl(this._canvas);
  65630. this._isInVRMode = false;
  65631. this._btnVR.style.display = "";
  65632. };
  65633. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  65634. get: function () {
  65635. return this._position;
  65636. },
  65637. set: function (value) {
  65638. this._position = value;
  65639. this._scene.activeCamera.position = value;
  65640. },
  65641. enumerable: true,
  65642. configurable: true
  65643. });
  65644. VRExperienceHelper.prototype.dispose = function () {
  65645. if (this._isInVRMode) {
  65646. this.exitVR();
  65647. }
  65648. document.body.removeChild(this._btnVR);
  65649. };
  65650. VRExperienceHelper.prototype.getClassName = function () {
  65651. return "VRExperienceHelper";
  65652. };
  65653. return VRExperienceHelper;
  65654. }());
  65655. BABYLON.VRExperienceHelper = VRExperienceHelper;
  65656. })(BABYLON || (BABYLON = {}));
  65657. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  65658. // Mainly based on these 2 articles :
  65659. // 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
  65660. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  65661. var BABYLON;
  65662. (function (BABYLON) {
  65663. var JoystickAxis;
  65664. (function (JoystickAxis) {
  65665. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  65666. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  65667. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  65668. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  65669. var VirtualJoystick = (function () {
  65670. function VirtualJoystick(leftJoystick) {
  65671. var _this = this;
  65672. if (leftJoystick) {
  65673. this._leftJoystick = true;
  65674. }
  65675. else {
  65676. this._leftJoystick = false;
  65677. }
  65678. this._joystickIndex = VirtualJoystick._globalJoystickIndex;
  65679. VirtualJoystick._globalJoystickIndex++;
  65680. // By default left & right arrow keys are moving the X
  65681. // and up & down keys are moving the Y
  65682. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65683. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65684. this.reverseLeftRight = false;
  65685. this.reverseUpDown = false;
  65686. // collections of pointers
  65687. this._touches = new BABYLON.StringDictionary();
  65688. this.deltaPosition = BABYLON.Vector3.Zero();
  65689. this._joystickSensibility = 25;
  65690. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65691. this._rotationSpeed = 25;
  65692. this._inverseRotationSpeed = 1 / (this._rotationSpeed / 1000);
  65693. this._rotateOnAxisRelativeToMesh = false;
  65694. this._onResize = function (evt) {
  65695. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65696. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65697. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  65698. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  65699. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  65700. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvasHeight / 2;
  65701. };
  65702. // injecting a canvas element on top of the canvas 3D game
  65703. if (!VirtualJoystick.vjCanvas) {
  65704. window.addEventListener("resize", this._onResize, false);
  65705. VirtualJoystick.vjCanvas = document.createElement("canvas");
  65706. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  65707. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  65708. VirtualJoystick.vjCanvas.width = window.innerWidth;
  65709. VirtualJoystick.vjCanvas.height = window.innerHeight;
  65710. VirtualJoystick.vjCanvas.style.width = "100%";
  65711. VirtualJoystick.vjCanvas.style.height = "100%";
  65712. VirtualJoystick.vjCanvas.style.position = "absolute";
  65713. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  65714. VirtualJoystick.vjCanvas.style.top = "0px";
  65715. VirtualJoystick.vjCanvas.style.left = "0px";
  65716. VirtualJoystick.vjCanvas.style.zIndex = "5";
  65717. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  65718. // Support for jQuery PEP polyfill
  65719. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  65720. VirtualJoystick.vjCanvasContext = VirtualJoystick.vjCanvas.getContext('2d');
  65721. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  65722. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65723. document.body.appendChild(VirtualJoystick.vjCanvas);
  65724. }
  65725. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  65726. VirtualJoystick.halfHeight = VirtualJoystick.vjCanvas.height / 2;
  65727. this.pressed = false;
  65728. // default joystick color
  65729. this._joystickColor = "cyan";
  65730. this._joystickPointerID = -1;
  65731. // current joystick position
  65732. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  65733. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  65734. // origin joystick position
  65735. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  65736. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  65737. this._onPointerDownHandlerRef = function (evt) {
  65738. _this._onPointerDown(evt);
  65739. };
  65740. this._onPointerMoveHandlerRef = function (evt) {
  65741. _this._onPointerMove(evt);
  65742. };
  65743. this._onPointerOutHandlerRef = function (evt) {
  65744. _this._onPointerUp(evt);
  65745. };
  65746. this._onPointerUpHandlerRef = function (evt) {
  65747. _this._onPointerUp(evt);
  65748. };
  65749. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  65750. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  65751. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  65752. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  65753. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  65754. evt.preventDefault(); // Disables system menu
  65755. }, false);
  65756. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65757. }
  65758. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  65759. this._joystickSensibility = newJoystickSensibility;
  65760. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  65761. };
  65762. VirtualJoystick.prototype._onPointerDown = function (e) {
  65763. var positionOnScreenCondition;
  65764. e.preventDefault();
  65765. if (this._leftJoystick === true) {
  65766. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  65767. }
  65768. else {
  65769. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  65770. }
  65771. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  65772. // First contact will be dedicated to the virtual joystick
  65773. this._joystickPointerID = e.pointerId;
  65774. this._joystickPointerStartPos.x = e.clientX;
  65775. this._joystickPointerStartPos.y = e.clientY;
  65776. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  65777. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  65778. this._deltaJoystickVector.x = 0;
  65779. this._deltaJoystickVector.y = 0;
  65780. this.pressed = true;
  65781. this._touches.add(e.pointerId.toString(), e);
  65782. }
  65783. else {
  65784. // You can only trigger the action buttons with a joystick declared
  65785. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  65786. this._action();
  65787. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  65788. }
  65789. }
  65790. };
  65791. VirtualJoystick.prototype._onPointerMove = function (e) {
  65792. // If the current pointer is the one associated to the joystick (first touch contact)
  65793. if (this._joystickPointerID == e.pointerId) {
  65794. this._joystickPointerPos.x = e.clientX;
  65795. this._joystickPointerPos.y = e.clientY;
  65796. this._deltaJoystickVector = this._joystickPointerPos.clone();
  65797. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  65798. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  65799. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  65800. switch (this._axisTargetedByLeftAndRight) {
  65801. case JoystickAxis.X:
  65802. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  65803. break;
  65804. case JoystickAxis.Y:
  65805. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  65806. break;
  65807. case JoystickAxis.Z:
  65808. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  65809. break;
  65810. }
  65811. var directionUpDown = this.reverseUpDown ? 1 : -1;
  65812. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  65813. switch (this._axisTargetedByUpAndDown) {
  65814. case JoystickAxis.X:
  65815. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  65816. break;
  65817. case JoystickAxis.Y:
  65818. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  65819. break;
  65820. case JoystickAxis.Z:
  65821. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  65822. break;
  65823. }
  65824. }
  65825. else {
  65826. var data = this._touches.get(e.pointerId.toString());
  65827. if (data) {
  65828. data.x = e.clientX;
  65829. data.y = e.clientY;
  65830. }
  65831. }
  65832. };
  65833. VirtualJoystick.prototype._onPointerUp = function (e) {
  65834. if (this._joystickPointerID == e.pointerId) {
  65835. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  65836. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  65837. this._joystickPointerID = -1;
  65838. this.pressed = false;
  65839. }
  65840. else {
  65841. var touch = this._touches.get(e.pointerId.toString());
  65842. if (touch) {
  65843. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65844. }
  65845. }
  65846. this._deltaJoystickVector.x = 0;
  65847. this._deltaJoystickVector.y = 0;
  65848. this._touches.remove(e.pointerId.toString());
  65849. };
  65850. /**
  65851. * Change the color of the virtual joystick
  65852. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  65853. */
  65854. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  65855. this._joystickColor = newColor;
  65856. };
  65857. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  65858. this._action = action;
  65859. };
  65860. // Define which axis you'd like to control for left & right
  65861. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  65862. switch (axis) {
  65863. case JoystickAxis.X:
  65864. case JoystickAxis.Y:
  65865. case JoystickAxis.Z:
  65866. this._axisTargetedByLeftAndRight = axis;
  65867. break;
  65868. default:
  65869. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  65870. break;
  65871. }
  65872. };
  65873. // Define which axis you'd like to control for up & down
  65874. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  65875. switch (axis) {
  65876. case JoystickAxis.X:
  65877. case JoystickAxis.Y:
  65878. case JoystickAxis.Z:
  65879. this._axisTargetedByUpAndDown = axis;
  65880. break;
  65881. default:
  65882. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  65883. break;
  65884. }
  65885. };
  65886. VirtualJoystick.prototype._clearCanvas = function () {
  65887. if (this._leftJoystick) {
  65888. VirtualJoystick.vjCanvasContext.clearRect(0, 0, VirtualJoystick.vjCanvasWidth / 2, VirtualJoystick.vjCanvasHeight);
  65889. }
  65890. else {
  65891. VirtualJoystick.vjCanvasContext.clearRect(VirtualJoystick.vjCanvasWidth / 2, 0, VirtualJoystick.vjCanvasWidth, VirtualJoystick.vjCanvasHeight);
  65892. }
  65893. };
  65894. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  65895. var _this = this;
  65896. if (this.pressed) {
  65897. this._touches.forEach(function (key, touch) {
  65898. if (touch.pointerId === _this._joystickPointerID) {
  65899. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  65900. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  65901. VirtualJoystick.vjCanvasContext.beginPath();
  65902. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65903. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65904. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  65905. VirtualJoystick.vjCanvasContext.stroke();
  65906. VirtualJoystick.vjCanvasContext.closePath();
  65907. VirtualJoystick.vjCanvasContext.beginPath();
  65908. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65909. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  65910. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  65911. VirtualJoystick.vjCanvasContext.stroke();
  65912. VirtualJoystick.vjCanvasContext.closePath();
  65913. VirtualJoystick.vjCanvasContext.beginPath();
  65914. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  65915. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  65916. VirtualJoystick.vjCanvasContext.stroke();
  65917. VirtualJoystick.vjCanvasContext.closePath();
  65918. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  65919. }
  65920. else {
  65921. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  65922. VirtualJoystick.vjCanvasContext.beginPath();
  65923. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  65924. VirtualJoystick.vjCanvasContext.beginPath();
  65925. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  65926. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  65927. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  65928. VirtualJoystick.vjCanvasContext.stroke();
  65929. VirtualJoystick.vjCanvasContext.closePath();
  65930. touch.prevX = touch.x;
  65931. touch.prevY = touch.y;
  65932. }
  65933. ;
  65934. });
  65935. }
  65936. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  65937. };
  65938. VirtualJoystick.prototype.releaseCanvas = function () {
  65939. if (VirtualJoystick.vjCanvas) {
  65940. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  65941. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  65942. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  65943. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  65944. window.removeEventListener("resize", this._onResize);
  65945. document.body.removeChild(VirtualJoystick.vjCanvas);
  65946. VirtualJoystick.vjCanvas = null;
  65947. }
  65948. };
  65949. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  65950. VirtualJoystick._globalJoystickIndex = 0;
  65951. return VirtualJoystick;
  65952. }());
  65953. BABYLON.VirtualJoystick = VirtualJoystick;
  65954. })(BABYLON || (BABYLON = {}));
  65955. //# sourceMappingURL=babylon.virtualJoystick.js.map
  65956. var BABYLON;
  65957. (function (BABYLON) {
  65958. // We're mainly based on the logic defined into the FreeCamera code
  65959. var VirtualJoysticksCamera = (function (_super) {
  65960. __extends(VirtualJoysticksCamera, _super);
  65961. function VirtualJoysticksCamera(name, position, scene) {
  65962. var _this = _super.call(this, name, position, scene) || this;
  65963. _this.inputs.addVirtualJoystick();
  65964. return _this;
  65965. }
  65966. VirtualJoysticksCamera.prototype.getClassName = function () {
  65967. return "VirtualJoysticksCamera";
  65968. };
  65969. return VirtualJoysticksCamera;
  65970. }(BABYLON.FreeCamera));
  65971. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  65972. })(BABYLON || (BABYLON = {}));
  65973. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  65974. var BABYLON;
  65975. (function (BABYLON) {
  65976. var FreeCameraVirtualJoystickInput = (function () {
  65977. function FreeCameraVirtualJoystickInput() {
  65978. }
  65979. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  65980. return this._leftjoystick;
  65981. };
  65982. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  65983. return this._rightjoystick;
  65984. };
  65985. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  65986. if (this._leftjoystick) {
  65987. var camera = this.camera;
  65988. var speed = camera._computeLocalCameraSpeed() * 50;
  65989. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  65990. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  65991. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  65992. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  65993. if (!this._leftjoystick.pressed) {
  65994. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  65995. }
  65996. if (!this._rightjoystick.pressed) {
  65997. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  65998. }
  65999. }
  66000. };
  66001. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  66002. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  66003. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  66004. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  66005. this._leftjoystick.setJoystickSensibility(0.15);
  66006. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  66007. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  66008. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  66009. this._rightjoystick.reverseUpDown = true;
  66010. this._rightjoystick.setJoystickSensibility(0.05);
  66011. this._rightjoystick.setJoystickColor("yellow");
  66012. };
  66013. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  66014. this._leftjoystick.releaseCanvas();
  66015. this._rightjoystick.releaseCanvas();
  66016. };
  66017. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  66018. return "FreeCameraVirtualJoystickInput";
  66019. };
  66020. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  66021. return "virtualJoystick";
  66022. };
  66023. return FreeCameraVirtualJoystickInput;
  66024. }());
  66025. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  66026. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  66027. })(BABYLON || (BABYLON = {}));
  66028. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  66029. var BABYLON;
  66030. (function (BABYLON) {
  66031. var SimplificationSettings = (function () {
  66032. function SimplificationSettings(quality, distance, optimizeMesh) {
  66033. this.quality = quality;
  66034. this.distance = distance;
  66035. this.optimizeMesh = optimizeMesh;
  66036. }
  66037. return SimplificationSettings;
  66038. }());
  66039. BABYLON.SimplificationSettings = SimplificationSettings;
  66040. var SimplificationQueue = (function () {
  66041. function SimplificationQueue() {
  66042. this.running = false;
  66043. this._simplificationArray = [];
  66044. }
  66045. SimplificationQueue.prototype.addTask = function (task) {
  66046. this._simplificationArray.push(task);
  66047. };
  66048. SimplificationQueue.prototype.executeNext = function () {
  66049. var task = this._simplificationArray.pop();
  66050. if (task) {
  66051. this.running = true;
  66052. this.runSimplification(task);
  66053. }
  66054. else {
  66055. this.running = false;
  66056. }
  66057. };
  66058. SimplificationQueue.prototype.runSimplification = function (task) {
  66059. var _this = this;
  66060. if (task.parallelProcessing) {
  66061. //parallel simplifier
  66062. task.settings.forEach(function (setting) {
  66063. var simplifier = _this.getSimplifier(task);
  66064. simplifier.simplify(setting, function (newMesh) {
  66065. task.mesh.addLODLevel(setting.distance, newMesh);
  66066. newMesh.isVisible = true;
  66067. //check if it is the last
  66068. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  66069. //all done, run the success callback.
  66070. task.successCallback();
  66071. }
  66072. _this.executeNext();
  66073. });
  66074. });
  66075. }
  66076. else {
  66077. //single simplifier.
  66078. var simplifier = this.getSimplifier(task);
  66079. var runDecimation = function (setting, callback) {
  66080. simplifier.simplify(setting, function (newMesh) {
  66081. task.mesh.addLODLevel(setting.distance, newMesh);
  66082. newMesh.isVisible = true;
  66083. //run the next quality level
  66084. callback();
  66085. });
  66086. };
  66087. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  66088. runDecimation(task.settings[loop.index], function () {
  66089. loop.executeNext();
  66090. });
  66091. }, function () {
  66092. //execution ended, run the success callback.
  66093. if (task.successCallback) {
  66094. task.successCallback();
  66095. }
  66096. _this.executeNext();
  66097. });
  66098. }
  66099. };
  66100. SimplificationQueue.prototype.getSimplifier = function (task) {
  66101. switch (task.simplificationType) {
  66102. case SimplificationType.QUADRATIC:
  66103. default:
  66104. return new QuadraticErrorSimplification(task.mesh);
  66105. }
  66106. };
  66107. return SimplificationQueue;
  66108. }());
  66109. BABYLON.SimplificationQueue = SimplificationQueue;
  66110. /**
  66111. * The implemented types of simplification.
  66112. * At the moment only Quadratic Error Decimation is implemented.
  66113. */
  66114. var SimplificationType;
  66115. (function (SimplificationType) {
  66116. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  66117. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  66118. var DecimationTriangle = (function () {
  66119. function DecimationTriangle(vertices) {
  66120. this.vertices = vertices;
  66121. this.error = new Array(4);
  66122. this.deleted = false;
  66123. this.isDirty = false;
  66124. this.deletePending = false;
  66125. this.borderFactor = 0;
  66126. }
  66127. return DecimationTriangle;
  66128. }());
  66129. BABYLON.DecimationTriangle = DecimationTriangle;
  66130. var DecimationVertex = (function () {
  66131. function DecimationVertex(position, id) {
  66132. this.position = position;
  66133. this.id = id;
  66134. this.isBorder = true;
  66135. this.q = new QuadraticMatrix();
  66136. this.triangleCount = 0;
  66137. this.triangleStart = 0;
  66138. this.originalOffsets = [];
  66139. }
  66140. DecimationVertex.prototype.updatePosition = function (newPosition) {
  66141. this.position.copyFrom(newPosition);
  66142. };
  66143. return DecimationVertex;
  66144. }());
  66145. BABYLON.DecimationVertex = DecimationVertex;
  66146. var QuadraticMatrix = (function () {
  66147. function QuadraticMatrix(data) {
  66148. this.data = new Array(10);
  66149. for (var i = 0; i < 10; ++i) {
  66150. if (data && data[i]) {
  66151. this.data[i] = data[i];
  66152. }
  66153. else {
  66154. this.data[i] = 0;
  66155. }
  66156. }
  66157. }
  66158. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  66159. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  66160. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  66161. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  66162. return det;
  66163. };
  66164. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  66165. for (var i = 0; i < 10; ++i) {
  66166. this.data[i] += matrix.data[i];
  66167. }
  66168. };
  66169. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  66170. for (var i = 0; i < 10; ++i) {
  66171. this.data[i] += data[i];
  66172. }
  66173. };
  66174. QuadraticMatrix.prototype.add = function (matrix) {
  66175. var m = new QuadraticMatrix();
  66176. for (var i = 0; i < 10; ++i) {
  66177. m.data[i] = this.data[i] + matrix.data[i];
  66178. }
  66179. return m;
  66180. };
  66181. QuadraticMatrix.FromData = function (a, b, c, d) {
  66182. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  66183. };
  66184. //returning an array to avoid garbage collection
  66185. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  66186. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  66187. };
  66188. return QuadraticMatrix;
  66189. }());
  66190. BABYLON.QuadraticMatrix = QuadraticMatrix;
  66191. var Reference = (function () {
  66192. function Reference(vertexId, triangleId) {
  66193. this.vertexId = vertexId;
  66194. this.triangleId = triangleId;
  66195. }
  66196. return Reference;
  66197. }());
  66198. BABYLON.Reference = Reference;
  66199. /**
  66200. * An implementation of the Quadratic Error simplification algorithm.
  66201. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  66202. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  66203. * @author RaananW
  66204. */
  66205. var QuadraticErrorSimplification = (function () {
  66206. function QuadraticErrorSimplification(_mesh) {
  66207. this._mesh = _mesh;
  66208. this.initialized = false;
  66209. this.syncIterations = 5000;
  66210. this.aggressiveness = 7;
  66211. this.decimationIterations = 100;
  66212. this.boundingBoxEpsilon = BABYLON.Epsilon;
  66213. }
  66214. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  66215. var _this = this;
  66216. this.initDecimatedMesh();
  66217. //iterating through the submeshes array, one after the other.
  66218. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  66219. _this.initWithMesh(loop.index, function () {
  66220. _this.runDecimation(settings, loop.index, function () {
  66221. loop.executeNext();
  66222. });
  66223. }, settings.optimizeMesh);
  66224. }, function () {
  66225. setTimeout(function () {
  66226. successCallback(_this._reconstructedMesh);
  66227. }, 0);
  66228. });
  66229. };
  66230. QuadraticErrorSimplification.prototype.isTriangleOnBoundingBox = function (triangle) {
  66231. var _this = this;
  66232. var gCount = 0;
  66233. triangle.vertices.forEach(function (vertex) {
  66234. var count = 0;
  66235. var vPos = vertex.position;
  66236. var bbox = _this._mesh.getBoundingInfo().boundingBox;
  66237. if (bbox.maximum.x - vPos.x < _this.boundingBoxEpsilon || vPos.x - bbox.minimum.x > _this.boundingBoxEpsilon)
  66238. ++count;
  66239. if (bbox.maximum.y === vPos.y || vPos.y === bbox.minimum.y)
  66240. ++count;
  66241. if (bbox.maximum.z === vPos.z || vPos.z === bbox.minimum.z)
  66242. ++count;
  66243. if (count > 1) {
  66244. ++gCount;
  66245. }
  66246. ;
  66247. });
  66248. if (gCount > 1) {
  66249. console.log(triangle, gCount);
  66250. }
  66251. return gCount > 1;
  66252. };
  66253. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  66254. var _this = this;
  66255. var targetCount = ~~(this.triangles.length * settings.quality);
  66256. var deletedTriangles = 0;
  66257. var triangleCount = this.triangles.length;
  66258. var iterationFunction = function (iteration, callback) {
  66259. setTimeout(function () {
  66260. if (iteration % 5 === 0) {
  66261. _this.updateMesh(iteration === 0);
  66262. }
  66263. for (var i = 0; i < _this.triangles.length; ++i) {
  66264. _this.triangles[i].isDirty = false;
  66265. }
  66266. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  66267. var trianglesIterator = function (i) {
  66268. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  66269. var t = _this.triangles[tIdx];
  66270. if (!t)
  66271. return;
  66272. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  66273. return;
  66274. }
  66275. for (var j = 0; j < 3; ++j) {
  66276. if (t.error[j] < threshold) {
  66277. var deleted0 = [];
  66278. var deleted1 = [];
  66279. var v0 = t.vertices[j];
  66280. var v1 = t.vertices[(j + 1) % 3];
  66281. if (v0.isBorder || v1.isBorder)
  66282. continue;
  66283. var p = BABYLON.Vector3.Zero();
  66284. var n = BABYLON.Vector3.Zero();
  66285. var uv = BABYLON.Vector2.Zero();
  66286. var color = new BABYLON.Color4(0, 0, 0, 1);
  66287. _this.calculateError(v0, v1, p, n, uv, color);
  66288. var delTr = [];
  66289. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  66290. continue;
  66291. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  66292. continue;
  66293. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  66294. continue;
  66295. var uniqueArray = [];
  66296. delTr.forEach(function (deletedT) {
  66297. if (uniqueArray.indexOf(deletedT) === -1) {
  66298. deletedT.deletePending = true;
  66299. uniqueArray.push(deletedT);
  66300. }
  66301. });
  66302. if (uniqueArray.length % 2 !== 0) {
  66303. continue;
  66304. }
  66305. v0.q = v1.q.add(v0.q);
  66306. v0.updatePosition(p);
  66307. var tStart = _this.references.length;
  66308. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  66309. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  66310. var tCount = _this.references.length - tStart;
  66311. if (tCount <= v0.triangleCount) {
  66312. if (tCount) {
  66313. for (var c = 0; c < tCount; c++) {
  66314. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  66315. }
  66316. }
  66317. }
  66318. else {
  66319. v0.triangleStart = tStart;
  66320. }
  66321. v0.triangleCount = tCount;
  66322. break;
  66323. }
  66324. }
  66325. };
  66326. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  66327. }, 0);
  66328. };
  66329. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  66330. if (triangleCount - deletedTriangles <= targetCount)
  66331. loop.breakLoop();
  66332. else {
  66333. iterationFunction(loop.index, function () {
  66334. loop.executeNext();
  66335. });
  66336. }
  66337. }, function () {
  66338. setTimeout(function () {
  66339. //reconstruct this part of the mesh
  66340. _this.reconstructMesh(submeshIndex);
  66341. successCallback();
  66342. }, 0);
  66343. });
  66344. };
  66345. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  66346. var _this = this;
  66347. this.vertices = [];
  66348. this.triangles = [];
  66349. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  66350. var indices = this._mesh.getIndices();
  66351. var submesh = this._mesh.subMeshes[submeshIndex];
  66352. var findInVertices = function (positionToSearch) {
  66353. if (optimizeMesh) {
  66354. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  66355. if (_this.vertices[ii].position.equals(positionToSearch)) {
  66356. return _this.vertices[ii];
  66357. }
  66358. }
  66359. }
  66360. return null;
  66361. };
  66362. var vertexReferences = [];
  66363. var vertexInit = function (i) {
  66364. var offset = i + submesh.verticesStart;
  66365. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  66366. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  66367. vertex.originalOffsets.push(offset);
  66368. if (vertex.id === _this.vertices.length) {
  66369. _this.vertices.push(vertex);
  66370. }
  66371. vertexReferences.push(vertex.id);
  66372. };
  66373. //var totalVertices = mesh.getTotalVertices();
  66374. var totalVertices = submesh.verticesCount;
  66375. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  66376. var indicesInit = function (i) {
  66377. var offset = (submesh.indexStart / 3) + i;
  66378. var pos = (offset * 3);
  66379. var i0 = indices[pos + 0];
  66380. var i1 = indices[pos + 1];
  66381. var i2 = indices[pos + 2];
  66382. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  66383. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  66384. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  66385. var triangle = new DecimationTriangle([v0, v1, v2]);
  66386. triangle.originalOffset = pos;
  66387. _this.triangles.push(triangle);
  66388. };
  66389. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  66390. _this.init(callback);
  66391. });
  66392. });
  66393. };
  66394. QuadraticErrorSimplification.prototype.init = function (callback) {
  66395. var _this = this;
  66396. var triangleInit1 = function (i) {
  66397. var t = _this.triangles[i];
  66398. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  66399. for (var j = 0; j < 3; j++) {
  66400. 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))));
  66401. }
  66402. };
  66403. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  66404. var triangleInit2 = function (i) {
  66405. var t = _this.triangles[i];
  66406. for (var j = 0; j < 3; ++j) {
  66407. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  66408. }
  66409. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66410. };
  66411. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  66412. _this.initialized = true;
  66413. callback();
  66414. });
  66415. });
  66416. };
  66417. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  66418. var newTriangles = [];
  66419. var i;
  66420. for (i = 0; i < this.vertices.length; ++i) {
  66421. this.vertices[i].triangleCount = 0;
  66422. }
  66423. var t;
  66424. var j;
  66425. for (i = 0; i < this.triangles.length; ++i) {
  66426. if (!this.triangles[i].deleted) {
  66427. t = this.triangles[i];
  66428. for (j = 0; j < 3; ++j) {
  66429. t.vertices[j].triangleCount = 1;
  66430. }
  66431. newTriangles.push(t);
  66432. }
  66433. }
  66434. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  66435. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  66436. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  66437. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  66438. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  66439. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  66440. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  66441. var vertexCount = 0;
  66442. for (i = 0; i < this.vertices.length; ++i) {
  66443. var vertex = this.vertices[i];
  66444. vertex.id = vertexCount;
  66445. if (vertex.triangleCount) {
  66446. vertex.originalOffsets.forEach(function (originalOffset) {
  66447. newPositionData.push(vertex.position.x);
  66448. newPositionData.push(vertex.position.y);
  66449. newPositionData.push(vertex.position.z);
  66450. newNormalData.push(normalData[originalOffset * 3]);
  66451. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  66452. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  66453. if (uvs && uvs.length) {
  66454. newUVsData.push(uvs[(originalOffset * 2)]);
  66455. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  66456. }
  66457. else if (colorsData && colorsData.length) {
  66458. newColorsData.push(colorsData[(originalOffset * 4)]);
  66459. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  66460. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  66461. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  66462. }
  66463. ++vertexCount;
  66464. });
  66465. }
  66466. }
  66467. var startingIndex = this._reconstructedMesh.getTotalIndices();
  66468. var startingVertex = this._reconstructedMesh.getTotalVertices();
  66469. var submeshesArray = this._reconstructedMesh.subMeshes;
  66470. this._reconstructedMesh.subMeshes = [];
  66471. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  66472. var originalIndices = this._mesh.getIndices();
  66473. for (i = 0; i < newTriangles.length; ++i) {
  66474. t = newTriangles[i]; //now get the new referencing point for each vertex
  66475. [0, 1, 2].forEach(function (idx) {
  66476. var id = originalIndices[t.originalOffset + idx];
  66477. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  66478. if (offset < 0)
  66479. offset = 0;
  66480. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  66481. });
  66482. }
  66483. //overwriting the old vertex buffers and indices.
  66484. this._reconstructedMesh.setIndices(newIndicesArray);
  66485. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  66486. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  66487. if (newUVsData.length > 0)
  66488. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  66489. if (newColorsData.length > 0)
  66490. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  66491. //create submesh
  66492. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  66493. if (submeshIndex > 0) {
  66494. this._reconstructedMesh.subMeshes = [];
  66495. submeshesArray.forEach(function (submesh) {
  66496. new BABYLON.SubMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  66497. });
  66498. var newSubmesh = new BABYLON.SubMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  66499. }
  66500. };
  66501. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  66502. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  66503. this._reconstructedMesh.material = this._mesh.material;
  66504. this._reconstructedMesh.parent = this._mesh.parent;
  66505. this._reconstructedMesh.isVisible = false;
  66506. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  66507. };
  66508. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  66509. for (var i = 0; i < vertex1.triangleCount; ++i) {
  66510. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  66511. if (t.deleted)
  66512. continue;
  66513. var s = this.references[vertex1.triangleStart + i].vertexId;
  66514. var v1 = t.vertices[(s + 1) % 3];
  66515. var v2 = t.vertices[(s + 2) % 3];
  66516. if ((v1 === vertex2 || v2 === vertex2) /* && !this.isTriangleOnBoundingBox(t)*/) {
  66517. deletedArray[i] = true;
  66518. delTr.push(t);
  66519. continue;
  66520. }
  66521. var d1 = v1.position.subtract(point);
  66522. d1 = d1.normalize();
  66523. var d2 = v2.position.subtract(point);
  66524. d2 = d2.normalize();
  66525. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  66526. return true;
  66527. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  66528. deletedArray[i] = false;
  66529. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  66530. return true;
  66531. }
  66532. return false;
  66533. };
  66534. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  66535. var newDeleted = deletedTriangles;
  66536. for (var i = 0; i < vertex.triangleCount; ++i) {
  66537. var ref = this.references[vertex.triangleStart + i];
  66538. var t = this.triangles[ref.triangleId];
  66539. if (t.deleted)
  66540. continue;
  66541. if (deletedArray[i] && t.deletePending) {
  66542. t.deleted = true;
  66543. newDeleted++;
  66544. continue;
  66545. }
  66546. t.vertices[ref.vertexId] = origVertex;
  66547. t.isDirty = true;
  66548. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  66549. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  66550. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  66551. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  66552. this.references.push(ref);
  66553. }
  66554. return newDeleted;
  66555. };
  66556. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  66557. for (var i = 0; i < this.vertices.length; ++i) {
  66558. var vCount = [];
  66559. var vId = [];
  66560. var v = this.vertices[i];
  66561. var j;
  66562. for (j = 0; j < v.triangleCount; ++j) {
  66563. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  66564. for (var ii = 0; ii < 3; ii++) {
  66565. var ofs = 0;
  66566. var vv = triangle.vertices[ii];
  66567. while (ofs < vCount.length) {
  66568. if (vId[ofs] === vv.id)
  66569. break;
  66570. ++ofs;
  66571. }
  66572. if (ofs === vCount.length) {
  66573. vCount.push(1);
  66574. vId.push(vv.id);
  66575. }
  66576. else {
  66577. vCount[ofs]++;
  66578. }
  66579. }
  66580. }
  66581. for (j = 0; j < vCount.length; ++j) {
  66582. if (vCount[j] === 1) {
  66583. this.vertices[vId[j]].isBorder = true;
  66584. }
  66585. else {
  66586. this.vertices[vId[j]].isBorder = false;
  66587. }
  66588. }
  66589. }
  66590. };
  66591. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  66592. if (identifyBorders === void 0) { identifyBorders = false; }
  66593. var i;
  66594. if (!identifyBorders) {
  66595. var newTrianglesVector = [];
  66596. for (i = 0; i < this.triangles.length; ++i) {
  66597. if (!this.triangles[i].deleted) {
  66598. newTrianglesVector.push(this.triangles[i]);
  66599. }
  66600. }
  66601. this.triangles = newTrianglesVector;
  66602. }
  66603. for (i = 0; i < this.vertices.length; ++i) {
  66604. this.vertices[i].triangleCount = 0;
  66605. this.vertices[i].triangleStart = 0;
  66606. }
  66607. var t;
  66608. var j;
  66609. var v;
  66610. for (i = 0; i < this.triangles.length; ++i) {
  66611. t = this.triangles[i];
  66612. for (j = 0; j < 3; ++j) {
  66613. v = t.vertices[j];
  66614. v.triangleCount++;
  66615. }
  66616. }
  66617. var tStart = 0;
  66618. for (i = 0; i < this.vertices.length; ++i) {
  66619. this.vertices[i].triangleStart = tStart;
  66620. tStart += this.vertices[i].triangleCount;
  66621. this.vertices[i].triangleCount = 0;
  66622. }
  66623. var newReferences = new Array(this.triangles.length * 3);
  66624. for (i = 0; i < this.triangles.length; ++i) {
  66625. t = this.triangles[i];
  66626. for (j = 0; j < 3; ++j) {
  66627. v = t.vertices[j];
  66628. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  66629. v.triangleCount++;
  66630. }
  66631. }
  66632. this.references = newReferences;
  66633. if (identifyBorders) {
  66634. this.identifyBorder();
  66635. }
  66636. };
  66637. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  66638. var x = point.x;
  66639. var y = point.y;
  66640. var z = point.z;
  66641. 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
  66642. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  66643. };
  66644. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  66645. var q = vertex1.q.add(vertex2.q);
  66646. var border = vertex1.isBorder && vertex2.isBorder;
  66647. var error = 0;
  66648. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  66649. if (qDet !== 0 && !border) {
  66650. if (!pointResult) {
  66651. pointResult = BABYLON.Vector3.Zero();
  66652. }
  66653. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  66654. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  66655. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  66656. error = this.vertexError(q, pointResult);
  66657. }
  66658. else {
  66659. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  66660. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  66661. var error1 = this.vertexError(q, vertex1.position);
  66662. var error2 = this.vertexError(q, vertex2.position);
  66663. var error3 = this.vertexError(q, p3);
  66664. error = Math.min(error1, error2, error3);
  66665. if (error === error1) {
  66666. if (pointResult) {
  66667. pointResult.copyFrom(vertex1.position);
  66668. }
  66669. }
  66670. else if (error === error2) {
  66671. if (pointResult) {
  66672. pointResult.copyFrom(vertex2.position);
  66673. }
  66674. }
  66675. else {
  66676. if (pointResult) {
  66677. pointResult.copyFrom(p3);
  66678. }
  66679. }
  66680. }
  66681. return error;
  66682. };
  66683. return QuadraticErrorSimplification;
  66684. }());
  66685. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  66686. })(BABYLON || (BABYLON = {}));
  66687. //# sourceMappingURL=babylon.meshSimplification.js.map
  66688. var BABYLON;
  66689. (function (BABYLON) {
  66690. var Internals;
  66691. (function (Internals) {
  66692. var MeshLODLevel = (function () {
  66693. function MeshLODLevel(distance, mesh) {
  66694. this.distance = distance;
  66695. this.mesh = mesh;
  66696. }
  66697. return MeshLODLevel;
  66698. }());
  66699. Internals.MeshLODLevel = MeshLODLevel;
  66700. })(Internals = BABYLON.Internals || (BABYLON.Internals = {}));
  66701. })(BABYLON || (BABYLON = {}));
  66702. //# sourceMappingURL=babylon.meshLODLevel.js.map
  66703. var BABYLON;
  66704. (function (BABYLON) {
  66705. // Standard optimizations
  66706. var SceneOptimization = (function () {
  66707. function SceneOptimization(priority) {
  66708. if (priority === void 0) { priority = 0; }
  66709. this.priority = priority;
  66710. this.apply = function (scene) {
  66711. return true; // Return true if everything that can be done was applied
  66712. };
  66713. }
  66714. return SceneOptimization;
  66715. }());
  66716. BABYLON.SceneOptimization = SceneOptimization;
  66717. var TextureOptimization = (function (_super) {
  66718. __extends(TextureOptimization, _super);
  66719. function TextureOptimization(priority, maximumSize) {
  66720. if (priority === void 0) { priority = 0; }
  66721. if (maximumSize === void 0) { maximumSize = 1024; }
  66722. var _this = _super.call(this, priority) || this;
  66723. _this.priority = priority;
  66724. _this.maximumSize = maximumSize;
  66725. _this.apply = function (scene) {
  66726. var allDone = true;
  66727. for (var index = 0; index < scene.textures.length; index++) {
  66728. var texture = scene.textures[index];
  66729. if (!texture.canRescale || texture.getContext) {
  66730. continue;
  66731. }
  66732. var currentSize = texture.getSize();
  66733. var maxDimension = Math.max(currentSize.width, currentSize.height);
  66734. if (maxDimension > _this.maximumSize) {
  66735. texture.scale(0.5);
  66736. allDone = false;
  66737. }
  66738. }
  66739. return allDone;
  66740. };
  66741. return _this;
  66742. }
  66743. return TextureOptimization;
  66744. }(SceneOptimization));
  66745. BABYLON.TextureOptimization = TextureOptimization;
  66746. var HardwareScalingOptimization = (function (_super) {
  66747. __extends(HardwareScalingOptimization, _super);
  66748. function HardwareScalingOptimization(priority, maximumScale) {
  66749. if (priority === void 0) { priority = 0; }
  66750. if (maximumScale === void 0) { maximumScale = 2; }
  66751. var _this = _super.call(this, priority) || this;
  66752. _this.priority = priority;
  66753. _this.maximumScale = maximumScale;
  66754. _this._currentScale = 1;
  66755. _this.apply = function (scene) {
  66756. _this._currentScale++;
  66757. scene.getEngine().setHardwareScalingLevel(_this._currentScale);
  66758. return _this._currentScale >= _this.maximumScale;
  66759. };
  66760. return _this;
  66761. }
  66762. return HardwareScalingOptimization;
  66763. }(SceneOptimization));
  66764. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  66765. var ShadowsOptimization = (function (_super) {
  66766. __extends(ShadowsOptimization, _super);
  66767. function ShadowsOptimization() {
  66768. var _this = _super !== null && _super.apply(this, arguments) || this;
  66769. _this.apply = function (scene) {
  66770. scene.shadowsEnabled = false;
  66771. return true;
  66772. };
  66773. return _this;
  66774. }
  66775. return ShadowsOptimization;
  66776. }(SceneOptimization));
  66777. BABYLON.ShadowsOptimization = ShadowsOptimization;
  66778. var PostProcessesOptimization = (function (_super) {
  66779. __extends(PostProcessesOptimization, _super);
  66780. function PostProcessesOptimization() {
  66781. var _this = _super !== null && _super.apply(this, arguments) || this;
  66782. _this.apply = function (scene) {
  66783. scene.postProcessesEnabled = false;
  66784. return true;
  66785. };
  66786. return _this;
  66787. }
  66788. return PostProcessesOptimization;
  66789. }(SceneOptimization));
  66790. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  66791. var LensFlaresOptimization = (function (_super) {
  66792. __extends(LensFlaresOptimization, _super);
  66793. function LensFlaresOptimization() {
  66794. var _this = _super !== null && _super.apply(this, arguments) || this;
  66795. _this.apply = function (scene) {
  66796. scene.lensFlaresEnabled = false;
  66797. return true;
  66798. };
  66799. return _this;
  66800. }
  66801. return LensFlaresOptimization;
  66802. }(SceneOptimization));
  66803. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  66804. var ParticlesOptimization = (function (_super) {
  66805. __extends(ParticlesOptimization, _super);
  66806. function ParticlesOptimization() {
  66807. var _this = _super !== null && _super.apply(this, arguments) || this;
  66808. _this.apply = function (scene) {
  66809. scene.particlesEnabled = false;
  66810. return true;
  66811. };
  66812. return _this;
  66813. }
  66814. return ParticlesOptimization;
  66815. }(SceneOptimization));
  66816. BABYLON.ParticlesOptimization = ParticlesOptimization;
  66817. var RenderTargetsOptimization = (function (_super) {
  66818. __extends(RenderTargetsOptimization, _super);
  66819. function RenderTargetsOptimization() {
  66820. var _this = _super !== null && _super.apply(this, arguments) || this;
  66821. _this.apply = function (scene) {
  66822. scene.renderTargetsEnabled = false;
  66823. return true;
  66824. };
  66825. return _this;
  66826. }
  66827. return RenderTargetsOptimization;
  66828. }(SceneOptimization));
  66829. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  66830. var MergeMeshesOptimization = (function (_super) {
  66831. __extends(MergeMeshesOptimization, _super);
  66832. function MergeMeshesOptimization() {
  66833. var _this = _super !== null && _super.apply(this, arguments) || this;
  66834. _this._canBeMerged = function (abstractMesh) {
  66835. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  66836. return false;
  66837. }
  66838. var mesh = abstractMesh;
  66839. if (!mesh.isVisible || !mesh.isEnabled()) {
  66840. return false;
  66841. }
  66842. if (mesh.instances.length > 0) {
  66843. return false;
  66844. }
  66845. if (mesh.skeleton || mesh.hasLODLevels) {
  66846. return false;
  66847. }
  66848. if (mesh.parent) {
  66849. return false;
  66850. }
  66851. return true;
  66852. };
  66853. _this.apply = function (scene, updateSelectionTree) {
  66854. var globalPool = scene.meshes.slice(0);
  66855. var globalLength = globalPool.length;
  66856. for (var index = 0; index < globalLength; index++) {
  66857. var currentPool = new Array();
  66858. var current = globalPool[index];
  66859. // Checks
  66860. if (!_this._canBeMerged(current)) {
  66861. continue;
  66862. }
  66863. currentPool.push(current);
  66864. // Find compatible meshes
  66865. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  66866. var otherMesh = globalPool[subIndex];
  66867. if (!_this._canBeMerged(otherMesh)) {
  66868. continue;
  66869. }
  66870. if (otherMesh.material !== current.material) {
  66871. continue;
  66872. }
  66873. if (otherMesh.checkCollisions !== current.checkCollisions) {
  66874. continue;
  66875. }
  66876. currentPool.push(otherMesh);
  66877. globalLength--;
  66878. globalPool.splice(subIndex, 1);
  66879. subIndex--;
  66880. }
  66881. if (currentPool.length < 2) {
  66882. continue;
  66883. }
  66884. // Merge meshes
  66885. BABYLON.Mesh.MergeMeshes(currentPool);
  66886. }
  66887. if (updateSelectionTree != undefined) {
  66888. if (updateSelectionTree) {
  66889. scene.createOrUpdateSelectionOctree();
  66890. }
  66891. }
  66892. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  66893. scene.createOrUpdateSelectionOctree();
  66894. }
  66895. return true;
  66896. };
  66897. return _this;
  66898. }
  66899. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  66900. get: function () {
  66901. return MergeMeshesOptimization._UpdateSelectionTree;
  66902. },
  66903. set: function (value) {
  66904. MergeMeshesOptimization._UpdateSelectionTree = value;
  66905. },
  66906. enumerable: true,
  66907. configurable: true
  66908. });
  66909. MergeMeshesOptimization._UpdateSelectionTree = false;
  66910. return MergeMeshesOptimization;
  66911. }(SceneOptimization));
  66912. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  66913. // Options
  66914. var SceneOptimizerOptions = (function () {
  66915. function SceneOptimizerOptions(targetFrameRate, trackerDuration) {
  66916. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  66917. if (trackerDuration === void 0) { trackerDuration = 2000; }
  66918. this.targetFrameRate = targetFrameRate;
  66919. this.trackerDuration = trackerDuration;
  66920. this.optimizations = new Array();
  66921. }
  66922. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  66923. var result = new SceneOptimizerOptions(targetFrameRate);
  66924. var priority = 0;
  66925. result.optimizations.push(new MergeMeshesOptimization(priority));
  66926. result.optimizations.push(new ShadowsOptimization(priority));
  66927. result.optimizations.push(new LensFlaresOptimization(priority));
  66928. // Next priority
  66929. priority++;
  66930. result.optimizations.push(new PostProcessesOptimization(priority));
  66931. result.optimizations.push(new ParticlesOptimization(priority));
  66932. // Next priority
  66933. priority++;
  66934. result.optimizations.push(new TextureOptimization(priority, 1024));
  66935. return result;
  66936. };
  66937. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  66938. var result = new SceneOptimizerOptions(targetFrameRate);
  66939. var priority = 0;
  66940. result.optimizations.push(new MergeMeshesOptimization(priority));
  66941. result.optimizations.push(new ShadowsOptimization(priority));
  66942. result.optimizations.push(new LensFlaresOptimization(priority));
  66943. // Next priority
  66944. priority++;
  66945. result.optimizations.push(new PostProcessesOptimization(priority));
  66946. result.optimizations.push(new ParticlesOptimization(priority));
  66947. // Next priority
  66948. priority++;
  66949. result.optimizations.push(new TextureOptimization(priority, 512));
  66950. // Next priority
  66951. priority++;
  66952. result.optimizations.push(new RenderTargetsOptimization(priority));
  66953. // Next priority
  66954. priority++;
  66955. result.optimizations.push(new HardwareScalingOptimization(priority, 2));
  66956. return result;
  66957. };
  66958. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  66959. var result = new SceneOptimizerOptions(targetFrameRate);
  66960. var priority = 0;
  66961. result.optimizations.push(new MergeMeshesOptimization(priority));
  66962. result.optimizations.push(new ShadowsOptimization(priority));
  66963. result.optimizations.push(new LensFlaresOptimization(priority));
  66964. // Next priority
  66965. priority++;
  66966. result.optimizations.push(new PostProcessesOptimization(priority));
  66967. result.optimizations.push(new ParticlesOptimization(priority));
  66968. // Next priority
  66969. priority++;
  66970. result.optimizations.push(new TextureOptimization(priority, 256));
  66971. // Next priority
  66972. priority++;
  66973. result.optimizations.push(new RenderTargetsOptimization(priority));
  66974. // Next priority
  66975. priority++;
  66976. result.optimizations.push(new HardwareScalingOptimization(priority, 4));
  66977. return result;
  66978. };
  66979. return SceneOptimizerOptions;
  66980. }());
  66981. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  66982. // Scene optimizer tool
  66983. var SceneOptimizer = (function () {
  66984. function SceneOptimizer() {
  66985. }
  66986. SceneOptimizer._CheckCurrentState = function (scene, options, currentPriorityLevel, onSuccess, onFailure) {
  66987. // TODO: add an epsilon
  66988. if (scene.getEngine().getFps() >= options.targetFrameRate) {
  66989. if (onSuccess) {
  66990. onSuccess();
  66991. }
  66992. return;
  66993. }
  66994. // Apply current level of optimizations
  66995. var allDone = true;
  66996. var noOptimizationApplied = true;
  66997. for (var index = 0; index < options.optimizations.length; index++) {
  66998. var optimization = options.optimizations[index];
  66999. if (optimization.priority === currentPriorityLevel) {
  67000. noOptimizationApplied = false;
  67001. allDone = allDone && optimization.apply(scene);
  67002. }
  67003. }
  67004. // If no optimization was applied, this is a failure :(
  67005. if (noOptimizationApplied) {
  67006. if (onFailure) {
  67007. onFailure();
  67008. }
  67009. return;
  67010. }
  67011. // If all optimizations were done, move to next level
  67012. if (allDone) {
  67013. currentPriorityLevel++;
  67014. }
  67015. // Let's the system running for a specific amount of time before checking FPS
  67016. scene.executeWhenReady(function () {
  67017. setTimeout(function () {
  67018. SceneOptimizer._CheckCurrentState(scene, options, currentPriorityLevel, onSuccess, onFailure);
  67019. }, options.trackerDuration);
  67020. });
  67021. };
  67022. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  67023. if (!options) {
  67024. options = SceneOptimizerOptions.ModerateDegradationAllowed();
  67025. }
  67026. // Let's the system running for a specific amount of time before checking FPS
  67027. scene.executeWhenReady(function () {
  67028. setTimeout(function () {
  67029. SceneOptimizer._CheckCurrentState(scene, options, 0, onSuccess, onFailure);
  67030. }, options.trackerDuration);
  67031. });
  67032. };
  67033. return SceneOptimizer;
  67034. }());
  67035. BABYLON.SceneOptimizer = SceneOptimizer;
  67036. })(BABYLON || (BABYLON = {}));
  67037. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  67038. var BABYLON;
  67039. (function (BABYLON) {
  67040. var OutlineRenderer = (function () {
  67041. function OutlineRenderer(scene) {
  67042. this.zOffset = 1;
  67043. this._scene = scene;
  67044. }
  67045. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  67046. var _this = this;
  67047. if (useOverlay === void 0) { useOverlay = false; }
  67048. var scene = this._scene;
  67049. var engine = this._scene.getEngine();
  67050. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67051. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  67052. return;
  67053. }
  67054. var mesh = subMesh.getRenderingMesh();
  67055. var material = subMesh.getMaterial();
  67056. engine.enableEffect(this._effect);
  67057. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  67058. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  67059. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  67060. // Bones
  67061. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67062. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67063. }
  67064. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  67065. // Alpha test
  67066. if (material && material.needAlphaTesting()) {
  67067. var alphaTexture = material.getAlphaTestTexture();
  67068. if (alphaTexture) {
  67069. this._effect.setTexture("diffuseSampler", alphaTexture);
  67070. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67071. }
  67072. }
  67073. engine.setZOffset(-this.zOffset);
  67074. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  67075. engine.setZOffset(0);
  67076. };
  67077. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  67078. var defines = [];
  67079. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  67080. var mesh = subMesh.getMesh();
  67081. var material = subMesh.getMaterial();
  67082. // Alpha test
  67083. if (material && material.needAlphaTesting()) {
  67084. defines.push("#define ALPHATEST");
  67085. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67086. attribs.push(BABYLON.VertexBuffer.UVKind);
  67087. defines.push("#define UV1");
  67088. }
  67089. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  67090. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67091. defines.push("#define UV2");
  67092. }
  67093. }
  67094. // Bones
  67095. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67096. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67097. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67098. if (mesh.numBoneInfluencers > 4) {
  67099. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67100. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67101. }
  67102. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67103. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67104. }
  67105. else {
  67106. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67107. }
  67108. // Instances
  67109. if (useInstances) {
  67110. defines.push("#define INSTANCES");
  67111. attribs.push("world0");
  67112. attribs.push("world1");
  67113. attribs.push("world2");
  67114. attribs.push("world3");
  67115. }
  67116. // Get correct effect
  67117. var join = defines.join("\n");
  67118. if (this._cachedDefines !== join) {
  67119. this._cachedDefines = join;
  67120. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color"], ["diffuseSampler"], join);
  67121. }
  67122. return this._effect.isReady();
  67123. };
  67124. return OutlineRenderer;
  67125. }());
  67126. BABYLON.OutlineRenderer = OutlineRenderer;
  67127. })(BABYLON || (BABYLON = {}));
  67128. //# sourceMappingURL=babylon.outlineRenderer.js.map
  67129. var BABYLON;
  67130. (function (BABYLON) {
  67131. var FaceAdjacencies = (function () {
  67132. function FaceAdjacencies() {
  67133. this.edges = new Array();
  67134. this.edgesConnectedCount = 0;
  67135. }
  67136. return FaceAdjacencies;
  67137. }());
  67138. var EdgesRenderer = (function () {
  67139. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  67140. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  67141. if (epsilon === void 0) { epsilon = 0.95; }
  67142. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  67143. this.edgesWidthScalerForOrthographic = 1000.0;
  67144. this.edgesWidthScalerForPerspective = 50.0;
  67145. this._linesPositions = new Array();
  67146. this._linesNormals = new Array();
  67147. this._linesIndices = new Array();
  67148. this._buffers = {};
  67149. this._checkVerticesInsteadOfIndices = false;
  67150. this._source = source;
  67151. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  67152. this._epsilon = epsilon;
  67153. this._prepareRessources();
  67154. this._generateEdgesLines();
  67155. }
  67156. EdgesRenderer.prototype._prepareRessources = function () {
  67157. if (this._lineShader) {
  67158. return;
  67159. }
  67160. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  67161. attributes: ["position", "normal"],
  67162. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  67163. });
  67164. this._lineShader.disableDepthWrite = true;
  67165. this._lineShader.backFaceCulling = false;
  67166. };
  67167. EdgesRenderer.prototype.dispose = function () {
  67168. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  67169. if (buffer) {
  67170. buffer.dispose();
  67171. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  67172. }
  67173. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  67174. if (buffer) {
  67175. buffer.dispose();
  67176. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  67177. }
  67178. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  67179. this._lineShader.dispose();
  67180. };
  67181. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  67182. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  67183. return 0;
  67184. }
  67185. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  67186. return 1;
  67187. }
  67188. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  67189. return 2;
  67190. }
  67191. return -1;
  67192. };
  67193. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  67194. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  67195. return 0;
  67196. }
  67197. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  67198. return 1;
  67199. }
  67200. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  67201. return 2;
  67202. }
  67203. return -1;
  67204. };
  67205. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  67206. var needToCreateLine;
  67207. if (edge === undefined) {
  67208. needToCreateLine = true;
  67209. }
  67210. else {
  67211. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  67212. needToCreateLine = dotProduct < this._epsilon;
  67213. }
  67214. if (needToCreateLine) {
  67215. var offset = this._linesPositions.length / 3;
  67216. var normal = p0.subtract(p1);
  67217. normal.normalize();
  67218. // Positions
  67219. this._linesPositions.push(p0.x);
  67220. this._linesPositions.push(p0.y);
  67221. this._linesPositions.push(p0.z);
  67222. this._linesPositions.push(p0.x);
  67223. this._linesPositions.push(p0.y);
  67224. this._linesPositions.push(p0.z);
  67225. this._linesPositions.push(p1.x);
  67226. this._linesPositions.push(p1.y);
  67227. this._linesPositions.push(p1.z);
  67228. this._linesPositions.push(p1.x);
  67229. this._linesPositions.push(p1.y);
  67230. this._linesPositions.push(p1.z);
  67231. // Normals
  67232. this._linesNormals.push(p1.x);
  67233. this._linesNormals.push(p1.y);
  67234. this._linesNormals.push(p1.z);
  67235. this._linesNormals.push(-1);
  67236. this._linesNormals.push(p1.x);
  67237. this._linesNormals.push(p1.y);
  67238. this._linesNormals.push(p1.z);
  67239. this._linesNormals.push(1);
  67240. this._linesNormals.push(p0.x);
  67241. this._linesNormals.push(p0.y);
  67242. this._linesNormals.push(p0.z);
  67243. this._linesNormals.push(-1);
  67244. this._linesNormals.push(p0.x);
  67245. this._linesNormals.push(p0.y);
  67246. this._linesNormals.push(p0.z);
  67247. this._linesNormals.push(1);
  67248. // Indices
  67249. this._linesIndices.push(offset);
  67250. this._linesIndices.push(offset + 1);
  67251. this._linesIndices.push(offset + 2);
  67252. this._linesIndices.push(offset);
  67253. this._linesIndices.push(offset + 2);
  67254. this._linesIndices.push(offset + 3);
  67255. }
  67256. };
  67257. EdgesRenderer.prototype._generateEdgesLines = function () {
  67258. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  67259. var indices = this._source.getIndices();
  67260. // First let's find adjacencies
  67261. var adjacencies = new Array();
  67262. var faceNormals = new Array();
  67263. var index;
  67264. var faceAdjacencies;
  67265. // Prepare faces
  67266. for (index = 0; index < indices.length; index += 3) {
  67267. faceAdjacencies = new FaceAdjacencies();
  67268. var p0Index = indices[index];
  67269. var p1Index = indices[index + 1];
  67270. var p2Index = indices[index + 2];
  67271. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  67272. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  67273. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  67274. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  67275. faceNormal.normalize();
  67276. faceNormals.push(faceNormal);
  67277. adjacencies.push(faceAdjacencies);
  67278. }
  67279. // Scan
  67280. for (index = 0; index < adjacencies.length; index++) {
  67281. faceAdjacencies = adjacencies[index];
  67282. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  67283. var otherFaceAdjacencies = adjacencies[otherIndex];
  67284. if (faceAdjacencies.edgesConnectedCount === 3) {
  67285. break;
  67286. }
  67287. if (otherFaceAdjacencies.edgesConnectedCount === 3) {
  67288. continue;
  67289. }
  67290. var otherP0 = indices[otherIndex * 3];
  67291. var otherP1 = indices[otherIndex * 3 + 1];
  67292. var otherP2 = indices[otherIndex * 3 + 2];
  67293. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  67294. var otherEdgeIndex;
  67295. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  67296. continue;
  67297. }
  67298. switch (edgeIndex) {
  67299. case 0:
  67300. if (this._checkVerticesInsteadOfIndices) {
  67301. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67302. }
  67303. else {
  67304. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  67305. }
  67306. break;
  67307. case 1:
  67308. if (this._checkVerticesInsteadOfIndices) {
  67309. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67310. }
  67311. else {
  67312. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  67313. }
  67314. break;
  67315. case 2:
  67316. if (this._checkVerticesInsteadOfIndices) {
  67317. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  67318. }
  67319. else {
  67320. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  67321. }
  67322. break;
  67323. }
  67324. if (otherEdgeIndex === -1) {
  67325. continue;
  67326. }
  67327. faceAdjacencies.edges[edgeIndex] = otherIndex;
  67328. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  67329. faceAdjacencies.edgesConnectedCount++;
  67330. otherFaceAdjacencies.edgesConnectedCount++;
  67331. if (faceAdjacencies.edgesConnectedCount === 3) {
  67332. break;
  67333. }
  67334. }
  67335. }
  67336. }
  67337. // Create lines
  67338. for (index = 0; index < adjacencies.length; index++) {
  67339. // 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
  67340. var current = adjacencies[index];
  67341. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  67342. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  67343. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  67344. }
  67345. // Merge into a single mesh
  67346. var engine = this._source.getScene().getEngine();
  67347. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  67348. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  67349. this._ib = engine.createIndexBuffer(this._linesIndices);
  67350. this._indicesCount = this._linesIndices.length;
  67351. };
  67352. EdgesRenderer.prototype.render = function () {
  67353. if (!this._lineShader.isReady()) {
  67354. return;
  67355. }
  67356. var scene = this._source.getScene();
  67357. var engine = scene.getEngine();
  67358. this._lineShader._preBind();
  67359. // VBOs
  67360. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  67361. scene.resetCachedMaterial();
  67362. this._lineShader.setColor4("color", this._source.edgesColor);
  67363. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  67364. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  67365. }
  67366. else {
  67367. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  67368. }
  67369. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  67370. this._lineShader.bind(this._source.getWorldMatrix());
  67371. // Draw order
  67372. engine.draw(true, 0, this._indicesCount);
  67373. this._lineShader.unbind();
  67374. engine.setDepthWrite(true);
  67375. };
  67376. return EdgesRenderer;
  67377. }());
  67378. BABYLON.EdgesRenderer = EdgesRenderer;
  67379. })(BABYLON || (BABYLON = {}));
  67380. //# sourceMappingURL=babylon.edgesRenderer.js.map
  67381. /// <reference path="..\PostProcess\babylon.postProcess.ts" />
  67382. /// <reference path="..\Math\babylon.math.ts" />
  67383. var BABYLON;
  67384. (function (BABYLON) {
  67385. /**
  67386. * Special Glow Blur post process only blurring the alpha channel
  67387. * It enforces keeping the most luminous color in the color channel.
  67388. */
  67389. var GlowBlurPostProcess = (function (_super) {
  67390. __extends(GlowBlurPostProcess, _super);
  67391. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  67392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  67393. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  67394. _this.direction = direction;
  67395. _this.kernel = kernel;
  67396. _this.onApplyObservable.add(function (effect) {
  67397. effect.setFloat2("screenSize", _this.width, _this.height);
  67398. effect.setVector2("direction", _this.direction);
  67399. effect.setFloat("blurWidth", _this.kernel);
  67400. });
  67401. return _this;
  67402. }
  67403. return GlowBlurPostProcess;
  67404. }(BABYLON.PostProcess));
  67405. /**
  67406. * The highlight layer Helps adding a glow effect around a mesh.
  67407. *
  67408. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  67409. * glowy meshes to your scene.
  67410. *
  67411. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  67412. */
  67413. var HighlightLayer = (function () {
  67414. /**
  67415. * Instantiates a new highlight Layer and references it to the scene..
  67416. * @param name The name of the layer
  67417. * @param scene The scene to use the layer in
  67418. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  67419. */
  67420. function HighlightLayer(name, scene, options) {
  67421. this.name = name;
  67422. this._vertexBuffers = {};
  67423. this._mainTextureDesiredSize = { width: 0, height: 0 };
  67424. this._meshes = {};
  67425. this._maxSize = 0;
  67426. this._shouldRender = false;
  67427. this._instanceGlowingMeshStencilReference = HighlightLayer.glowingMeshStencilReference++;
  67428. this._excludedMeshes = {};
  67429. /**
  67430. * Specifies whether or not the inner glow is ACTIVE in the layer.
  67431. */
  67432. this.innerGlow = true;
  67433. /**
  67434. * Specifies whether or not the outer glow is ACTIVE in the layer.
  67435. */
  67436. this.outerGlow = true;
  67437. /**
  67438. * Specifies wether the highlight layer is enabled or not.
  67439. */
  67440. this.isEnabled = true;
  67441. /**
  67442. * An event triggered when the highlight layer has been disposed.
  67443. * @type {BABYLON.Observable}
  67444. */
  67445. this.onDisposeObservable = new BABYLON.Observable();
  67446. /**
  67447. * An event triggered when the highlight layer is about rendering the main texture with the glowy parts.
  67448. * @type {BABYLON.Observable}
  67449. */
  67450. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  67451. /**
  67452. * An event triggered when the highlight layer is being blurred.
  67453. * @type {BABYLON.Observable}
  67454. */
  67455. this.onBeforeBlurObservable = new BABYLON.Observable();
  67456. /**
  67457. * An event triggered when the highlight layer has been blurred.
  67458. * @type {BABYLON.Observable}
  67459. */
  67460. this.onAfterBlurObservable = new BABYLON.Observable();
  67461. /**
  67462. * An event triggered when the glowing blurred texture is being merged in the scene.
  67463. * @type {BABYLON.Observable}
  67464. */
  67465. this.onBeforeComposeObservable = new BABYLON.Observable();
  67466. /**
  67467. * An event triggered when the glowing blurred texture has been merged in the scene.
  67468. * @type {BABYLON.Observable}
  67469. */
  67470. this.onAfterComposeObservable = new BABYLON.Observable();
  67471. /**
  67472. * An event triggered when the highlight layer changes its size.
  67473. * @type {BABYLON.Observable}
  67474. */
  67475. this.onSizeChangedObservable = new BABYLON.Observable();
  67476. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  67477. var engine = scene.getEngine();
  67478. this._engine = engine;
  67479. this._maxSize = this._engine.getCaps().maxTextureSize;
  67480. this._scene.highlightLayers.push(this);
  67481. // Warn on stencil.
  67482. if (!this._engine.isStencilEnable) {
  67483. 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 }");
  67484. }
  67485. // Adapt options
  67486. this._options = options || {
  67487. mainTextureRatio: 0.5,
  67488. blurTextureSizeRatio: 0.5,
  67489. blurHorizontalSize: 1.0,
  67490. blurVerticalSize: 1.0,
  67491. alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE
  67492. };
  67493. this._options.mainTextureRatio = this._options.mainTextureRatio || 0.5;
  67494. this._options.blurTextureSizeRatio = this._options.blurTextureSizeRatio || 1.0;
  67495. this._options.blurHorizontalSize = this._options.blurHorizontalSize || 1;
  67496. this._options.blurVerticalSize = this._options.blurVerticalSize || 1;
  67497. this._options.alphaBlendingMode = this._options.alphaBlendingMode || BABYLON.Engine.ALPHA_COMBINE;
  67498. // VBO
  67499. var vertices = [];
  67500. vertices.push(1, 1);
  67501. vertices.push(-1, 1);
  67502. vertices.push(-1, -1);
  67503. vertices.push(1, -1);
  67504. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  67505. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  67506. // Indices
  67507. var indices = [];
  67508. indices.push(0);
  67509. indices.push(1);
  67510. indices.push(2);
  67511. indices.push(0);
  67512. indices.push(2);
  67513. indices.push(3);
  67514. this._indexBuffer = engine.createIndexBuffer(indices);
  67515. // Effect
  67516. this._glowMapMergeEffect = engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], "");
  67517. // Render target
  67518. this.setMainTextureSize();
  67519. // Create Textures and post processes
  67520. this.createTextureAndPostProcesses();
  67521. }
  67522. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  67523. /**
  67524. * Gets the horizontal size of the blur.
  67525. */
  67526. get: function () {
  67527. return this._horizontalBlurPostprocess.kernel;
  67528. },
  67529. /**
  67530. * Specifies the horizontal size of the blur.
  67531. */
  67532. set: function (value) {
  67533. this._horizontalBlurPostprocess.kernel = value;
  67534. },
  67535. enumerable: true,
  67536. configurable: true
  67537. });
  67538. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  67539. /**
  67540. * Gets the vertical size of the blur.
  67541. */
  67542. get: function () {
  67543. return this._verticalBlurPostprocess.kernel;
  67544. },
  67545. /**
  67546. * Specifies the vertical size of the blur.
  67547. */
  67548. set: function (value) {
  67549. this._verticalBlurPostprocess.kernel = value;
  67550. },
  67551. enumerable: true,
  67552. configurable: true
  67553. });
  67554. Object.defineProperty(HighlightLayer.prototype, "camera", {
  67555. /**
  67556. * Gets the camera attached to the layer.
  67557. */
  67558. get: function () {
  67559. return this._options.camera;
  67560. },
  67561. enumerable: true,
  67562. configurable: true
  67563. });
  67564. /**
  67565. * Creates the render target textures and post processes used in the highlight layer.
  67566. */
  67567. HighlightLayer.prototype.createTextureAndPostProcesses = function () {
  67568. var _this = this;
  67569. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  67570. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  67571. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  67572. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  67573. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  67574. width: this._mainTextureDesiredSize.width,
  67575. height: this._mainTextureDesiredSize.height
  67576. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67577. this._mainTexture.activeCamera = this._options.camera;
  67578. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67579. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67580. this._mainTexture.anisotropicFilteringLevel = 1;
  67581. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  67582. this._mainTexture.renderParticles = false;
  67583. this._mainTexture.renderList = null;
  67584. this._mainTexture.ignoreCameraViewport = true;
  67585. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  67586. width: blurTextureWidth,
  67587. height: blurTextureHeight
  67588. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  67589. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67590. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  67591. this._blurTexture.anisotropicFilteringLevel = 16;
  67592. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  67593. this._blurTexture.renderParticles = false;
  67594. this._blurTexture.ignoreCameraViewport = true;
  67595. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67596. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  67597. effect.setTexture("textureSampler", _this._mainTexture);
  67598. });
  67599. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  67600. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67601. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67602. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67603. });
  67604. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67605. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67606. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67607. });
  67608. }
  67609. else {
  67610. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67611. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  67612. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67613. });
  67614. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  67615. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  67616. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  67617. });
  67618. }
  67619. this._mainTexture.onAfterUnbindObservable.add(function () {
  67620. _this.onBeforeBlurObservable.notifyObservers(_this);
  67621. _this._scene.postProcessManager.directRender([_this._downSamplePostprocess, _this._horizontalBlurPostprocess, _this._verticalBlurPostprocess], _this._blurTexture.getInternalTexture(), true);
  67622. _this.onAfterBlurObservable.notifyObservers(_this);
  67623. });
  67624. // Custom render function
  67625. var renderSubMesh = function (subMesh) {
  67626. var mesh = subMesh.getRenderingMesh();
  67627. var scene = _this._scene;
  67628. var engine = scene.getEngine();
  67629. // Culling
  67630. engine.setState(subMesh.getMaterial().backFaceCulling);
  67631. // Managing instances
  67632. var batch = mesh._getInstancesRenderList(subMesh._id);
  67633. if (batch.mustReturn) {
  67634. return;
  67635. }
  67636. // Excluded Mesh
  67637. if (_this._excludedMeshes[mesh.uniqueId]) {
  67638. return;
  67639. }
  67640. ;
  67641. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  67642. var highlightLayerMesh = _this._meshes[mesh.uniqueId];
  67643. var material = subMesh.getMaterial();
  67644. var emissiveTexture = null;
  67645. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  67646. emissiveTexture = material.emissiveTexture;
  67647. }
  67648. if (_this.isReady(subMesh, hardwareInstancedRendering, emissiveTexture)) {
  67649. engine.enableEffect(_this._glowMapGenerationEffect);
  67650. mesh._bind(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  67651. _this._glowMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  67652. if (highlightLayerMesh) {
  67653. _this._glowMapGenerationEffect.setFloat4("color", highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  67654. }
  67655. else {
  67656. _this._glowMapGenerationEffect.setFloat4("color", HighlightLayer.neutralColor.r, HighlightLayer.neutralColor.g, HighlightLayer.neutralColor.b, HighlightLayer.neutralColor.a);
  67657. }
  67658. // Alpha test
  67659. if (material && material.needAlphaTesting()) {
  67660. var alphaTexture = material.getAlphaTestTexture();
  67661. if (alphaTexture) {
  67662. _this._glowMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  67663. _this._glowMapGenerationEffect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  67664. }
  67665. }
  67666. // Glow emissive only
  67667. if (emissiveTexture) {
  67668. _this._glowMapGenerationEffect.setTexture("emissiveSampler", emissiveTexture);
  67669. _this._glowMapGenerationEffect.setMatrix("emissiveMatrix", emissiveTexture.getTextureMatrix());
  67670. }
  67671. // Bones
  67672. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67673. _this._glowMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  67674. }
  67675. // Draw
  67676. mesh._processRendering(subMesh, _this._glowMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._glowMapGenerationEffect.setMatrix("world", world); });
  67677. }
  67678. else {
  67679. // Need to reset refresh rate of the shadowMap
  67680. _this._mainTexture.resetRefreshCounter();
  67681. }
  67682. };
  67683. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes) {
  67684. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  67685. var index;
  67686. for (index = 0; index < opaqueSubMeshes.length; index++) {
  67687. renderSubMesh(opaqueSubMeshes.data[index]);
  67688. }
  67689. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  67690. renderSubMesh(alphaTestSubMeshes.data[index]);
  67691. }
  67692. for (index = 0; index < transparentSubMeshes.length; index++) {
  67693. renderSubMesh(transparentSubMeshes.data[index]);
  67694. }
  67695. };
  67696. this._mainTexture.onClearObservable.add(function (engine) {
  67697. engine.clear(HighlightLayer.neutralColor, true, true, true);
  67698. });
  67699. };
  67700. /**
  67701. * Checks for the readiness of the element composing the layer.
  67702. * @param subMesh the mesh to check for
  67703. * @param useInstances specify wether or not to use instances to render the mesh
  67704. * @param emissiveTexture the associated emissive texture used to generate the glow
  67705. * @return true if ready otherwise, false
  67706. */
  67707. HighlightLayer.prototype.isReady = function (subMesh, useInstances, emissiveTexture) {
  67708. if (!subMesh.getMaterial().isReady(subMesh.getMesh(), useInstances)) {
  67709. return false;
  67710. }
  67711. var defines = [];
  67712. var attribs = [BABYLON.VertexBuffer.PositionKind];
  67713. var mesh = subMesh.getMesh();
  67714. var material = subMesh.getMaterial();
  67715. var uv1 = false;
  67716. var uv2 = false;
  67717. // Alpha test
  67718. if (material && material.needAlphaTesting()) {
  67719. var alphaTexture = material.getAlphaTestTexture();
  67720. if (alphaTexture) {
  67721. defines.push("#define ALPHATEST");
  67722. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67723. alphaTexture.coordinatesIndex === 1) {
  67724. defines.push("#define DIFFUSEUV2");
  67725. uv2 = true;
  67726. }
  67727. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67728. defines.push("#define DIFFUSEUV1");
  67729. uv1 = true;
  67730. }
  67731. }
  67732. }
  67733. // Emissive
  67734. if (emissiveTexture) {
  67735. defines.push("#define EMISSIVE");
  67736. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  67737. emissiveTexture.coordinatesIndex === 1) {
  67738. defines.push("#define EMISSIVEUV2");
  67739. uv2 = true;
  67740. }
  67741. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  67742. defines.push("#define EMISSIVEUV1");
  67743. uv1 = true;
  67744. }
  67745. }
  67746. if (uv1) {
  67747. attribs.push(BABYLON.VertexBuffer.UVKind);
  67748. defines.push("#define UV1");
  67749. }
  67750. if (uv2) {
  67751. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  67752. defines.push("#define UV2");
  67753. }
  67754. // Bones
  67755. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  67756. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  67757. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  67758. if (mesh.numBoneInfluencers > 4) {
  67759. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  67760. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  67761. }
  67762. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  67763. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  67764. }
  67765. else {
  67766. defines.push("#define NUM_BONE_INFLUENCERS 0");
  67767. }
  67768. // Instances
  67769. if (useInstances) {
  67770. defines.push("#define INSTANCES");
  67771. attribs.push("world0");
  67772. attribs.push("world1");
  67773. attribs.push("world2");
  67774. attribs.push("world3");
  67775. }
  67776. // Get correct effect
  67777. var join = defines.join("\n");
  67778. if (this._cachedDefines !== join) {
  67779. this._cachedDefines = join;
  67780. this._glowMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix"], ["diffuseSampler", "emissiveSampler"], join);
  67781. }
  67782. return this._glowMapGenerationEffect.isReady();
  67783. };
  67784. /**
  67785. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  67786. */
  67787. HighlightLayer.prototype.render = function () {
  67788. var currentEffect = this._glowMapMergeEffect;
  67789. // Check
  67790. if (!currentEffect.isReady() || !this._blurTexture.isReady())
  67791. return;
  67792. var engine = this._scene.getEngine();
  67793. this.onBeforeComposeObservable.notifyObservers(this);
  67794. // Render
  67795. engine.enableEffect(currentEffect);
  67796. engine.setState(false);
  67797. // Cache
  67798. var previousStencilBuffer = engine.getStencilBuffer();
  67799. var previousStencilFunction = engine.getStencilFunction();
  67800. var previousStencilMask = engine.getStencilMask();
  67801. var previousStencilOperationPass = engine.getStencilOperationPass();
  67802. var previousStencilOperationFail = engine.getStencilOperationFail();
  67803. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  67804. var previousAlphaMode = engine.getAlphaMode();
  67805. // Texture
  67806. currentEffect.setTexture("textureSampler", this._blurTexture);
  67807. // VBOs
  67808. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  67809. // Stencil operations
  67810. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  67811. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  67812. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  67813. // Draw order
  67814. engine.setAlphaMode(this._options.alphaBlendingMode);
  67815. engine.setStencilMask(0x00);
  67816. engine.setStencilBuffer(true);
  67817. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  67818. if (this.outerGlow) {
  67819. currentEffect.setFloat("offset", 0);
  67820. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  67821. engine.draw(true, 0, 6);
  67822. }
  67823. if (this.innerGlow) {
  67824. currentEffect.setFloat("offset", 1);
  67825. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  67826. engine.draw(true, 0, 6);
  67827. }
  67828. // Restore Cache
  67829. engine.setStencilFunction(previousStencilFunction);
  67830. engine.setStencilMask(previousStencilMask);
  67831. engine.setAlphaMode(previousAlphaMode);
  67832. engine.setStencilBuffer(previousStencilBuffer);
  67833. engine.setStencilOperationPass(previousStencilOperationPass);
  67834. engine.setStencilOperationFail(previousStencilOperationFail);
  67835. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  67836. engine._stencilState.reset();
  67837. this.onAfterComposeObservable.notifyObservers(this);
  67838. // Handle size changes.
  67839. var size = this._mainTexture.getSize();
  67840. this.setMainTextureSize();
  67841. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  67842. // Recreate RTT and post processes on size change.
  67843. this.onSizeChangedObservable.notifyObservers(this);
  67844. this.disposeTextureAndPostProcesses();
  67845. this.createTextureAndPostProcesses();
  67846. }
  67847. };
  67848. /**
  67849. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  67850. * @param mesh The mesh to exclude from the highlight layer
  67851. */
  67852. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  67853. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67854. if (!meshExcluded) {
  67855. this._excludedMeshes[mesh.uniqueId] = {
  67856. mesh: mesh,
  67857. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  67858. mesh.getEngine().setStencilBuffer(false);
  67859. }),
  67860. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  67861. mesh.getEngine().setStencilBuffer(true);
  67862. }),
  67863. };
  67864. }
  67865. };
  67866. /**
  67867. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  67868. * @param mesh The mesh to highlight
  67869. */
  67870. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  67871. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  67872. if (meshExcluded) {
  67873. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  67874. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  67875. }
  67876. this._excludedMeshes[mesh.uniqueId] = undefined;
  67877. };
  67878. /**
  67879. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  67880. * @param mesh The mesh to highlight
  67881. * @param color The color of the highlight
  67882. * @param glowEmissiveOnly Extract the glow from the emissive texture
  67883. */
  67884. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  67885. var _this = this;
  67886. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  67887. var meshHighlight = this._meshes[mesh.uniqueId];
  67888. if (meshHighlight) {
  67889. meshHighlight.color = color;
  67890. }
  67891. else {
  67892. this._meshes[mesh.uniqueId] = {
  67893. mesh: mesh,
  67894. color: color,
  67895. // Lambda required for capture due to Observable this context
  67896. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  67897. if (_this._excludedMeshes[mesh.uniqueId]) {
  67898. _this.defaultStencilReference(mesh);
  67899. }
  67900. else {
  67901. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  67902. }
  67903. }),
  67904. observerDefault: mesh.onAfterRenderObservable.add(this.defaultStencilReference),
  67905. glowEmissiveOnly: glowEmissiveOnly
  67906. };
  67907. }
  67908. this._shouldRender = true;
  67909. };
  67910. /**
  67911. * Remove a mesh from the highlight layer in order to make it stop glowing.
  67912. * @param mesh The mesh to highlight
  67913. */
  67914. HighlightLayer.prototype.removeMesh = function (mesh) {
  67915. var meshHighlight = this._meshes[mesh.uniqueId];
  67916. if (meshHighlight) {
  67917. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67918. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67919. }
  67920. this._meshes[mesh.uniqueId] = undefined;
  67921. this._shouldRender = false;
  67922. for (var meshHighlightToCheck in this._meshes) {
  67923. if (meshHighlightToCheck) {
  67924. this._shouldRender = true;
  67925. break;
  67926. }
  67927. }
  67928. };
  67929. /**
  67930. * Returns true if the layer contains information to display, otherwise false.
  67931. */
  67932. HighlightLayer.prototype.shouldRender = function () {
  67933. return this.isEnabled && this._shouldRender;
  67934. };
  67935. /**
  67936. * Sets the main texture desired size which is the closest power of two
  67937. * of the engine canvas size.
  67938. */
  67939. HighlightLayer.prototype.setMainTextureSize = function () {
  67940. if (this._options.mainTextureFixedSize) {
  67941. this._mainTextureDesiredSize.width = this._options.mainTextureFixedSize;
  67942. this._mainTextureDesiredSize.height = this._options.mainTextureFixedSize;
  67943. }
  67944. else {
  67945. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._options.mainTextureRatio;
  67946. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._options.mainTextureRatio;
  67947. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  67948. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  67949. }
  67950. };
  67951. /**
  67952. * Force the stencil to the normal expected value for none glowing parts
  67953. */
  67954. HighlightLayer.prototype.defaultStencilReference = function (mesh) {
  67955. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.normalMeshStencilReference);
  67956. };
  67957. /**
  67958. * Dispose only the render target textures and post process.
  67959. */
  67960. HighlightLayer.prototype.disposeTextureAndPostProcesses = function () {
  67961. this._blurTexture.dispose();
  67962. this._mainTexture.dispose();
  67963. this._downSamplePostprocess.dispose();
  67964. this._horizontalBlurPostprocess.dispose();
  67965. this._verticalBlurPostprocess.dispose();
  67966. };
  67967. /**
  67968. * Dispose the highlight layer and free resources.
  67969. */
  67970. HighlightLayer.prototype.dispose = function () {
  67971. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  67972. if (vertexBuffer) {
  67973. vertexBuffer.dispose();
  67974. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  67975. }
  67976. if (this._indexBuffer) {
  67977. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  67978. this._indexBuffer = null;
  67979. }
  67980. // Clean textures and post processes
  67981. this.disposeTextureAndPostProcesses();
  67982. // Clean mesh references
  67983. for (var id in this._meshes) {
  67984. var meshHighlight = this._meshes[id];
  67985. if (meshHighlight && meshHighlight.mesh) {
  67986. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  67987. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  67988. }
  67989. }
  67990. this._meshes = null;
  67991. for (var id in this._excludedMeshes) {
  67992. var meshHighlight = this._excludedMeshes[id];
  67993. if (meshHighlight) {
  67994. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  67995. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  67996. }
  67997. }
  67998. this._excludedMeshes = null;
  67999. // Remove from scene
  68000. var index = this._scene.highlightLayers.indexOf(this, 0);
  68001. if (index > -1) {
  68002. this._scene.highlightLayers.splice(index, 1);
  68003. }
  68004. // Callback
  68005. this.onDisposeObservable.notifyObservers(this);
  68006. this.onDisposeObservable.clear();
  68007. this.onBeforeRenderMainTextureObservable.clear();
  68008. this.onBeforeBlurObservable.clear();
  68009. this.onBeforeComposeObservable.clear();
  68010. this.onAfterComposeObservable.clear();
  68011. this.onSizeChangedObservable.clear();
  68012. };
  68013. /**
  68014. * The neutral color used during the preparation of the glow effect.
  68015. * This is black by default as the blend operation is a blend operation.
  68016. */
  68017. HighlightLayer.neutralColor = new BABYLON.Color4(0, 0, 0, 0);
  68018. /**
  68019. * Stencil value used for glowing meshes.
  68020. */
  68021. HighlightLayer.glowingMeshStencilReference = 0x02;
  68022. /**
  68023. * Stencil value used for the other meshes in the scene.
  68024. */
  68025. HighlightLayer.normalMeshStencilReference = 0x01;
  68026. return HighlightLayer;
  68027. }());
  68028. BABYLON.HighlightLayer = HighlightLayer;
  68029. })(BABYLON || (BABYLON = {}));
  68030. //# sourceMappingURL=babylon.highlightlayer.js.map
  68031. var BABYLON;
  68032. (function (BABYLON) {
  68033. var MeshAssetTask = (function () {
  68034. function MeshAssetTask(name, meshesNames, rootUrl, sceneFilename) {
  68035. this.name = name;
  68036. this.meshesNames = meshesNames;
  68037. this.rootUrl = rootUrl;
  68038. this.sceneFilename = sceneFilename;
  68039. this.isCompleted = false;
  68040. }
  68041. MeshAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68042. var _this = this;
  68043. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  68044. _this.loadedMeshes = meshes;
  68045. _this.loadedParticleSystems = particleSystems;
  68046. _this.loadedSkeletons = skeletons;
  68047. _this.isCompleted = true;
  68048. if (_this.onSuccess) {
  68049. _this.onSuccess(_this);
  68050. }
  68051. onSuccess();
  68052. }, null, function () {
  68053. if (_this.onError) {
  68054. _this.onError(_this);
  68055. }
  68056. onError();
  68057. });
  68058. };
  68059. return MeshAssetTask;
  68060. }());
  68061. BABYLON.MeshAssetTask = MeshAssetTask;
  68062. var TextFileAssetTask = (function () {
  68063. function TextFileAssetTask(name, url) {
  68064. this.name = name;
  68065. this.url = url;
  68066. this.isCompleted = false;
  68067. }
  68068. TextFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68069. var _this = this;
  68070. BABYLON.Tools.LoadFile(this.url, function (data) {
  68071. _this.text = data;
  68072. _this.isCompleted = true;
  68073. if (_this.onSuccess) {
  68074. _this.onSuccess(_this);
  68075. }
  68076. onSuccess();
  68077. }, null, scene.database, false, function () {
  68078. if (_this.onError) {
  68079. _this.onError(_this);
  68080. }
  68081. onError();
  68082. });
  68083. };
  68084. return TextFileAssetTask;
  68085. }());
  68086. BABYLON.TextFileAssetTask = TextFileAssetTask;
  68087. var BinaryFileAssetTask = (function () {
  68088. function BinaryFileAssetTask(name, url) {
  68089. this.name = name;
  68090. this.url = url;
  68091. this.isCompleted = false;
  68092. }
  68093. BinaryFileAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68094. var _this = this;
  68095. BABYLON.Tools.LoadFile(this.url, function (data) {
  68096. _this.data = data;
  68097. _this.isCompleted = true;
  68098. if (_this.onSuccess) {
  68099. _this.onSuccess(_this);
  68100. }
  68101. onSuccess();
  68102. }, null, scene.database, true, function () {
  68103. if (_this.onError) {
  68104. _this.onError(_this);
  68105. }
  68106. onError();
  68107. });
  68108. };
  68109. return BinaryFileAssetTask;
  68110. }());
  68111. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  68112. var ImageAssetTask = (function () {
  68113. function ImageAssetTask(name, url) {
  68114. this.name = name;
  68115. this.url = url;
  68116. this.isCompleted = false;
  68117. }
  68118. ImageAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68119. var _this = this;
  68120. var img = new Image();
  68121. BABYLON.Tools.SetCorsBehavior(this.url, img);
  68122. img.onload = function () {
  68123. _this.image = img;
  68124. _this.isCompleted = true;
  68125. if (_this.onSuccess) {
  68126. _this.onSuccess(_this);
  68127. }
  68128. onSuccess();
  68129. };
  68130. img.onerror = function () {
  68131. if (_this.onError) {
  68132. _this.onError(_this);
  68133. }
  68134. onError();
  68135. };
  68136. img.src = this.url;
  68137. };
  68138. return ImageAssetTask;
  68139. }());
  68140. BABYLON.ImageAssetTask = ImageAssetTask;
  68141. var TextureAssetTask = (function () {
  68142. function TextureAssetTask(name, url, noMipmap, invertY, samplingMode) {
  68143. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68144. this.name = name;
  68145. this.url = url;
  68146. this.noMipmap = noMipmap;
  68147. this.invertY = invertY;
  68148. this.samplingMode = samplingMode;
  68149. this.isCompleted = false;
  68150. }
  68151. TextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68152. var _this = this;
  68153. var onload = function () {
  68154. _this.isCompleted = true;
  68155. if (_this.onSuccess) {
  68156. _this.onSuccess(_this);
  68157. }
  68158. onSuccess();
  68159. };
  68160. var onerror = function () {
  68161. if (_this.onError) {
  68162. _this.onError(_this);
  68163. }
  68164. onError();
  68165. };
  68166. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  68167. };
  68168. return TextureAssetTask;
  68169. }());
  68170. BABYLON.TextureAssetTask = TextureAssetTask;
  68171. var CubeTextureAssetTask = (function () {
  68172. function CubeTextureAssetTask(name, url, extensions, noMipmap, files) {
  68173. this.name = name;
  68174. this.url = url;
  68175. this.extensions = extensions;
  68176. this.noMipmap = noMipmap;
  68177. this.files = files;
  68178. this.isCompleted = false;
  68179. }
  68180. CubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68181. var _this = this;
  68182. var onload = function () {
  68183. _this.isCompleted = true;
  68184. if (_this.onSuccess) {
  68185. _this.onSuccess(_this);
  68186. }
  68187. onSuccess();
  68188. };
  68189. var onerror = function () {
  68190. if (_this.onError) {
  68191. _this.onError(_this);
  68192. }
  68193. onError();
  68194. };
  68195. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  68196. };
  68197. return CubeTextureAssetTask;
  68198. }());
  68199. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  68200. var HDRCubeTextureAssetTask = (function () {
  68201. function HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68202. if (noMipmap === void 0) { noMipmap = false; }
  68203. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68204. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68205. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68206. this.name = name;
  68207. this.url = url;
  68208. this.size = size;
  68209. this.noMipmap = noMipmap;
  68210. this.generateHarmonics = generateHarmonics;
  68211. this.useInGammaSpace = useInGammaSpace;
  68212. this.usePMREMGenerator = usePMREMGenerator;
  68213. this.isCompleted = false;
  68214. }
  68215. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  68216. var _this = this;
  68217. var onload = function () {
  68218. _this.isCompleted = true;
  68219. if (_this.onSuccess) {
  68220. _this.onSuccess(_this);
  68221. }
  68222. onSuccess();
  68223. };
  68224. var onerror = function () {
  68225. if (_this.onError) {
  68226. _this.onError(_this);
  68227. }
  68228. onError();
  68229. };
  68230. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.useInGammaSpace, this.usePMREMGenerator, onload, onerror);
  68231. };
  68232. return HDRCubeTextureAssetTask;
  68233. }());
  68234. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  68235. var AssetsManager = (function () {
  68236. function AssetsManager(scene) {
  68237. this.tasks = new Array();
  68238. this.waitingTasksCount = 0;
  68239. this.useDefaultLoadingScreen = true;
  68240. this._scene = scene;
  68241. }
  68242. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  68243. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  68244. this.tasks.push(task);
  68245. return task;
  68246. };
  68247. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  68248. var task = new TextFileAssetTask(taskName, url);
  68249. this.tasks.push(task);
  68250. return task;
  68251. };
  68252. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  68253. var task = new BinaryFileAssetTask(taskName, url);
  68254. this.tasks.push(task);
  68255. return task;
  68256. };
  68257. AssetsManager.prototype.addImageTask = function (taskName, url) {
  68258. var task = new ImageAssetTask(taskName, url);
  68259. this.tasks.push(task);
  68260. return task;
  68261. };
  68262. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  68263. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68264. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  68265. this.tasks.push(task);
  68266. return task;
  68267. };
  68268. AssetsManager.prototype.addCubeTextureTask = function (name, url, extensions, noMipmap, files) {
  68269. var task = new CubeTextureAssetTask(name, url, extensions, noMipmap, files);
  68270. this.tasks.push(task);
  68271. return task;
  68272. };
  68273. AssetsManager.prototype.addHDRCubeTextureTask = function (name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator) {
  68274. if (noMipmap === void 0) { noMipmap = false; }
  68275. if (generateHarmonics === void 0) { generateHarmonics = true; }
  68276. if (useInGammaSpace === void 0) { useInGammaSpace = false; }
  68277. if (usePMREMGenerator === void 0) { usePMREMGenerator = false; }
  68278. var task = new HDRCubeTextureAssetTask(name, url, size, noMipmap, generateHarmonics, useInGammaSpace, usePMREMGenerator);
  68279. this.tasks.push(task);
  68280. return task;
  68281. };
  68282. AssetsManager.prototype._decreaseWaitingTasksCount = function () {
  68283. this.waitingTasksCount--;
  68284. if (this.waitingTasksCount === 0) {
  68285. if (this.onFinish) {
  68286. this.onFinish(this.tasks);
  68287. }
  68288. this._scene.getEngine().hideLoadingUI();
  68289. }
  68290. };
  68291. AssetsManager.prototype._runTask = function (task) {
  68292. var _this = this;
  68293. task.run(this._scene, function () {
  68294. if (_this.onTaskSuccess) {
  68295. _this.onTaskSuccess(task);
  68296. }
  68297. _this._decreaseWaitingTasksCount();
  68298. }, function () {
  68299. if (_this.onTaskError) {
  68300. _this.onTaskError(task);
  68301. }
  68302. _this._decreaseWaitingTasksCount();
  68303. });
  68304. };
  68305. AssetsManager.prototype.reset = function () {
  68306. this.tasks = new Array();
  68307. return this;
  68308. };
  68309. AssetsManager.prototype.load = function () {
  68310. this.waitingTasksCount = this.tasks.length;
  68311. if (this.waitingTasksCount === 0) {
  68312. if (this.onFinish) {
  68313. this.onFinish(this.tasks);
  68314. }
  68315. return this;
  68316. }
  68317. if (this.useDefaultLoadingScreen) {
  68318. this._scene.getEngine().displayLoadingUI();
  68319. }
  68320. for (var index = 0; index < this.tasks.length; index++) {
  68321. var task = this.tasks[index];
  68322. this._runTask(task);
  68323. }
  68324. return this;
  68325. };
  68326. return AssetsManager;
  68327. }());
  68328. BABYLON.AssetsManager = AssetsManager;
  68329. })(BABYLON || (BABYLON = {}));
  68330. //# sourceMappingURL=babylon.assetsManager.js.map
  68331. var BABYLON;
  68332. (function (BABYLON) {
  68333. var MapTexture = (function (_super) {
  68334. __extends(MapTexture, _super);
  68335. function MapTexture(name, scene, size, samplingMode, useMipMap, margin) {
  68336. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  68337. if (useMipMap === void 0) { useMipMap = false; }
  68338. if (margin === void 0) { margin = 0; }
  68339. var _this = _super.call(this, null, scene, !useMipMap, false, samplingMode) || this;
  68340. _this.name = name;
  68341. _this._size = size;
  68342. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68343. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  68344. // Create the rectPackMap that will allocate portion of the texture
  68345. _this._rectPackingMap = new BABYLON.RectPackingMap(new BABYLON.Size(size.width, size.height), margin);
  68346. // Create the texture that will store the content
  68347. _this._texture = scene.getEngine().createRenderTargetTexture(size, { generateMipMaps: !_this.noMipmap, type: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT });
  68348. return _this;
  68349. }
  68350. /**
  68351. * Allocate a rectangle of a given size in the texture map
  68352. * @param size the size of the rectangle to allocation
  68353. * @return the PackedRect instance corresponding to the allocated rect or null is there was not enough space to allocate it.
  68354. */
  68355. MapTexture.prototype.allocateRect = function (size) {
  68356. return this._rectPackingMap.addRect(size);
  68357. };
  68358. /**
  68359. * Free a given rectangle from the texture map
  68360. * @param rectInfo the instance corresponding to the rect to free.
  68361. */
  68362. MapTexture.prototype.freeRect = function (rectInfo) {
  68363. if (rectInfo) {
  68364. rectInfo.freeContent();
  68365. }
  68366. };
  68367. Object.defineProperty(MapTexture.prototype, "freeSpace", {
  68368. /**
  68369. * Return the available space in the range of [O;1]. 0 being not space left at all, 1 being an empty texture map.
  68370. * This is the cumulated space, not the biggest available surface. Due to fragmentation you may not allocate a rect corresponding to this surface.
  68371. * @returns {}
  68372. */
  68373. get: function () {
  68374. return this._rectPackingMap.freeSpace;
  68375. },
  68376. enumerable: true,
  68377. configurable: true
  68378. });
  68379. /**
  68380. * Bind the texture to the rendering engine to render in the zone of a given rectangle.
  68381. * 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.
  68382. * Don't forget to call unbindTexture when you're done rendering
  68383. * @param rect the zone to render to
  68384. * @param clear true to clear the portion's color/depth data
  68385. */
  68386. MapTexture.prototype.bindTextureForRect = function (rect, clear) {
  68387. return this.bindTextureForPosSize(rect.pos, rect.contentSize, clear);
  68388. };
  68389. /**
  68390. * Bind the texture to the rendering engine to render in the zone of the given size at the given position.
  68391. * 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.
  68392. * Don't forget to call unbindTexture when you're done rendering
  68393. * @param pos the position into the texture
  68394. * @param size the portion to fit the clip space to
  68395. * @param clear true to clear the portion's color/depth data
  68396. */
  68397. MapTexture.prototype.bindTextureForPosSize = function (pos, size, clear) {
  68398. var engine = this.getScene().getEngine();
  68399. engine.bindFramebuffer(this._texture);
  68400. this._replacedViewport = engine.setDirectViewport(pos.x, pos.y, size.width, size.height);
  68401. if (clear) {
  68402. // We only want to clear the part of the texture we're binding to, only the scissor can help us to achieve that
  68403. engine.scissorClear(pos.x, pos.y, size.width, size.height, new BABYLON.Color4(0, 0, 0, 0));
  68404. }
  68405. };
  68406. /**
  68407. * Unbind the texture map from the rendering engine.
  68408. * Call this method when you're done rendering. A previous call to bindTextureForRect has to be made.
  68409. * @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.
  68410. */
  68411. MapTexture.prototype.unbindTexture = function (dumpForDebug) {
  68412. // Dump ?
  68413. if (dumpForDebug) {
  68414. BABYLON.Tools.DumpFramebuffer(this._size.width, this._size.height, this.getScene().getEngine());
  68415. }
  68416. var engine = this.getScene().getEngine();
  68417. if (this._replacedViewport) {
  68418. engine.setViewport(this._replacedViewport);
  68419. this._replacedViewport = null;
  68420. }
  68421. engine.unBindFramebuffer(this._texture);
  68422. };
  68423. Object.defineProperty(MapTexture.prototype, "canRescale", {
  68424. get: function () {
  68425. return false;
  68426. },
  68427. enumerable: true,
  68428. configurable: true
  68429. });
  68430. // Note, I don't know what behavior this method should have: clone the underlying texture/rectPackingMap or just reference them?
  68431. // Anyway, there's not much point to use this method for this kind of texture I guess
  68432. MapTexture.prototype.clone = function () {
  68433. return null;
  68434. };
  68435. return MapTexture;
  68436. }(BABYLON.Texture));
  68437. BABYLON.MapTexture = MapTexture;
  68438. })(BABYLON || (BABYLON = {}));
  68439. //# sourceMappingURL=babylon.mapTexture.js.map
  68440. var BABYLON;
  68441. (function (BABYLON) {
  68442. /**
  68443. * This class describe a rectangle that were added to the map.
  68444. * You have access to its coordinates either in pixel or normalized (UV)
  68445. */
  68446. var PackedRect = (function () {
  68447. function PackedRect(root, parent, pos, size) {
  68448. this._pos = pos;
  68449. this._size = size;
  68450. this._root = root;
  68451. this._parent = parent;
  68452. this._contentSize = null;
  68453. this._bottomNode = null;
  68454. this._leftNode = null;
  68455. this._initialSize = null;
  68456. this._rightNode = null;
  68457. }
  68458. Object.defineProperty(PackedRect.prototype, "pos", {
  68459. /**
  68460. * @returns the position of this node into the map
  68461. */
  68462. get: function () {
  68463. return this._pos;
  68464. },
  68465. enumerable: true,
  68466. configurable: true
  68467. });
  68468. Object.defineProperty(PackedRect.prototype, "contentSize", {
  68469. /**
  68470. * @returns the size of the rectangle this node handles
  68471. */
  68472. get: function () {
  68473. return this._contentSize;
  68474. },
  68475. enumerable: true,
  68476. configurable: true
  68477. });
  68478. /**
  68479. * Retrieve the inner position (considering the margin) and stores it into the res object
  68480. * @param res must be a valid Vector2 that will contain the inner position after this call
  68481. */
  68482. PackedRect.prototype.getInnerPosToRef = function (res) {
  68483. var m = this._root._margin;
  68484. res.x = this._pos.x + m;
  68485. res.y = this._pos.y + m;
  68486. };
  68487. /**
  68488. * Retrieve the inner size (considering the margin) and stores it into the res object
  68489. * @param res must be a valid Size that will contain the inner size after this call
  68490. */
  68491. PackedRect.prototype.getInnerSizeToRef = function (res) {
  68492. var m = this._root._margin;
  68493. res.width = this._contentSize.width - (m * 2);
  68494. res.height = this._contentSize.height - (m * 2);
  68495. };
  68496. Object.defineProperty(PackedRect.prototype, "UVs", {
  68497. /**
  68498. * Compute the UV of the top/left, top/right, bottom/right, bottom/left points of the rectangle this node handles into the map
  68499. * @returns And array of 4 Vector2, containing UV coordinates for the four corners of the Rectangle into the map
  68500. */
  68501. get: function () {
  68502. if (!this._contentSize) {
  68503. throw new Error("Can't compute UVs for this object because it's nor allocated");
  68504. }
  68505. return this.getUVsForCustomSize(this._contentSize);
  68506. },
  68507. enumerable: true,
  68508. configurable: true
  68509. });
  68510. /**
  68511. * You may have allocated the PackedRect using over-provisioning (you allocated more than you need in order to prevent frequent deallocations/reallocations)
  68512. * and then using only a part of the PackRect.
  68513. * This method will return the UVs for this part by given the custom size of what you really use
  68514. * @param customSize must be less/equal to the allocated size, UV will be compute from this
  68515. */
  68516. PackedRect.prototype.getUVsForCustomSize = function (customSize) {
  68517. var mainWidth = this._root._size.width;
  68518. var mainHeight = this._root._size.height;
  68519. var margin = this._root._margin;
  68520. var topLeft = new BABYLON.Vector2((this._pos.x + margin) / mainWidth, (this._pos.y + margin) / mainHeight);
  68521. var rightBottom = new BABYLON.Vector2((this._pos.x + customSize.width + margin - 1) / mainWidth, (this._pos.y + customSize.height + margin - 1) / mainHeight);
  68522. var uvs = new Array();
  68523. uvs.push(topLeft);
  68524. uvs.push(new BABYLON.Vector2(rightBottom.x, topLeft.y));
  68525. uvs.push(rightBottom);
  68526. uvs.push(new BABYLON.Vector2(topLeft.x, rightBottom.y));
  68527. return uvs;
  68528. };
  68529. /**
  68530. * Free this rectangle from the map.
  68531. * Call this method when you no longer need the rectangle to be in the map.
  68532. */
  68533. PackedRect.prototype.freeContent = function () {
  68534. if (!this.contentSize) {
  68535. return;
  68536. }
  68537. this._contentSize = null;
  68538. // If everything below is also free, reset the whole node, and attempt to reset parents if they also become free
  68539. this.attemptDefrag();
  68540. };
  68541. Object.defineProperty(PackedRect.prototype, "isUsed", {
  68542. get: function () {
  68543. return this._contentSize != null || this._leftNode != null;
  68544. },
  68545. enumerable: true,
  68546. configurable: true
  68547. });
  68548. PackedRect.prototype.findAndSplitNode = function (contentSize) {
  68549. var node = this.findNode(contentSize);
  68550. // Not enough space...
  68551. if (!node) {
  68552. return null;
  68553. }
  68554. node.splitNode(contentSize);
  68555. return node;
  68556. };
  68557. PackedRect.prototype.findNode = function (size) {
  68558. var resNode = null;
  68559. var margin = this._root._margin * 2;
  68560. // If this node is used, recurse to each of his subNodes to find an available one in its branch
  68561. if (this.isUsed) {
  68562. if (this._leftNode) {
  68563. resNode = this._leftNode.findNode(size);
  68564. }
  68565. if (!resNode && this._rightNode) {
  68566. resNode = this._rightNode.findNode(size);
  68567. }
  68568. if (!resNode && this._bottomNode) {
  68569. resNode = this._bottomNode.findNode(size);
  68570. }
  68571. }
  68572. else if (this._initialSize) {
  68573. if (((size.width + margin) <= this._initialSize.width) && ((size.height + margin) <= this._initialSize.height)) {
  68574. resNode = this;
  68575. }
  68576. else {
  68577. return null;
  68578. }
  68579. }
  68580. else if (((size.width + margin) <= this._size.width) && ((size.height + margin) <= this._size.height)) {
  68581. resNode = this;
  68582. }
  68583. return resNode;
  68584. };
  68585. PackedRect.prototype.splitNode = function (contentSize) {
  68586. var cs = PackedRect.TpsSize;
  68587. var margin = this._root._margin * 2;
  68588. cs.copyFrom(contentSize);
  68589. cs.width += margin;
  68590. cs.height += margin;
  68591. // 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)
  68592. if (!this._contentSize && this._initialSize) {
  68593. this._contentSize = cs.clone();
  68594. 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));
  68595. return this._leftNode.splitNode(contentSize);
  68596. }
  68597. else {
  68598. this._contentSize = cs.clone();
  68599. this._initialSize = cs.clone();
  68600. if (cs.width !== this._size.width) {
  68601. this._rightNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x + cs.width, this._pos.y), new BABYLON.Size(this._size.width - cs.width, cs.height));
  68602. }
  68603. if (cs.height !== this._size.height) {
  68604. this._bottomNode = new PackedRect(this._root, this, new BABYLON.Vector2(this._pos.x, this._pos.y + cs.height), new BABYLON.Size(this._size.width, this._size.height - cs.height));
  68605. }
  68606. return this;
  68607. }
  68608. };
  68609. PackedRect.prototype.attemptDefrag = function () {
  68610. if (!this.isUsed && this.isRecursiveFree) {
  68611. this.clearNode();
  68612. if (this._parent) {
  68613. this._parent.attemptDefrag();
  68614. }
  68615. }
  68616. };
  68617. PackedRect.prototype.clearNode = function () {
  68618. this._initialSize = null;
  68619. this._rightNode = null;
  68620. this._bottomNode = null;
  68621. };
  68622. Object.defineProperty(PackedRect.prototype, "isRecursiveFree", {
  68623. get: function () {
  68624. return !this.contentSize && (!this._leftNode || this._leftNode.isRecursiveFree) && (!this._rightNode || this._rightNode.isRecursiveFree) && (!this._bottomNode || this._bottomNode.isRecursiveFree);
  68625. },
  68626. enumerable: true,
  68627. configurable: true
  68628. });
  68629. PackedRect.prototype.evalFreeSize = function (size) {
  68630. var levelSize = 0;
  68631. if (!this.isUsed) {
  68632. var margin = this._root._margin;
  68633. var is = this._initialSize;
  68634. if (is) {
  68635. levelSize = is.surface - (is.width * margin) - (is.height * margin);
  68636. }
  68637. else {
  68638. var size_1 = this._size;
  68639. levelSize = size_1.surface - (size_1.width * margin) - (size_1.height * margin);
  68640. }
  68641. }
  68642. if (this._rightNode) {
  68643. levelSize += this._rightNode.evalFreeSize(0);
  68644. }
  68645. if (this._bottomNode) {
  68646. levelSize += this._bottomNode.evalFreeSize(0);
  68647. }
  68648. return levelSize + size;
  68649. };
  68650. PackedRect.TpsSize = BABYLON.Size.Zero();
  68651. return PackedRect;
  68652. }());
  68653. BABYLON.PackedRect = PackedRect;
  68654. /**
  68655. * The purpose of this class is to pack several Rectangles into a big map, while trying to fit everything as optimally as possible.
  68656. * This class is typically used to build lightmaps, sprite map or to pack several little textures into a big one.
  68657. * 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.
  68658. * In case you need a margin around the allocated rect, specify the amount in the margin argument during construction.
  68659. * In such case you will have to rely on innerPositionToRef and innerSizeToRef calls to get the proper size
  68660. */
  68661. var RectPackingMap = (function (_super) {
  68662. __extends(RectPackingMap, _super);
  68663. /**
  68664. * Create an instance of the object with a dimension using the given size
  68665. * @param size The dimension of the rectangle that will contain all the sub ones.
  68666. * @param margin The margin (empty space) created (in pixels) around the allocated Rectangles
  68667. */
  68668. function RectPackingMap(size, margin) {
  68669. if (margin === void 0) { margin = 0; }
  68670. var _this = _super.call(this, null, null, BABYLON.Vector2.Zero(), size) || this;
  68671. _this._margin = margin;
  68672. _this._root = _this;
  68673. return _this;
  68674. }
  68675. /**
  68676. * Add a rectangle, finding the best location to store it into the map
  68677. * @param size the dimension of the rectangle to store
  68678. * @return the Node containing the rectangle information, or null if we couldn't find a free spot
  68679. */
  68680. RectPackingMap.prototype.addRect = function (size) {
  68681. var node = this.findAndSplitNode(size);
  68682. return node;
  68683. };
  68684. Object.defineProperty(RectPackingMap.prototype, "freeSpace", {
  68685. /**
  68686. * Return the current space free normalized between [0;1]
  68687. * @returns {}
  68688. */
  68689. get: function () {
  68690. var freeSize = 0;
  68691. freeSize = this.evalFreeSize(freeSize);
  68692. return freeSize / (this._size.width * this._size.height);
  68693. },
  68694. enumerable: true,
  68695. configurable: true
  68696. });
  68697. return RectPackingMap;
  68698. }(PackedRect));
  68699. BABYLON.RectPackingMap = RectPackingMap;
  68700. })(BABYLON || (BABYLON = {}));
  68701. //# sourceMappingURL=babylon.rectPackingMap.js.map
  68702. var BABYLON;
  68703. (function (BABYLON) {
  68704. /**
  68705. * This groups together the common properties used for image processing either in direct forward pass
  68706. * or through post processing effect depending on the use of the image processing pipeline in your scene
  68707. * or not.
  68708. */
  68709. var ImageProcessingConfiguration = (function () {
  68710. function ImageProcessingConfiguration() {
  68711. /**
  68712. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  68713. */
  68714. this.colorCurves = new BABYLON.ColorCurves();
  68715. this._colorCurvesEnabled = false;
  68716. this._colorGradingEnabled = false;
  68717. this._colorGradingWithGreenDepth = false;
  68718. this._colorGradingBGR = false;
  68719. this._exposure = 1.0;
  68720. this._toneMappingEnabled = false;
  68721. this._contrast = 1.0;
  68722. /**
  68723. * Vignette stretch size.
  68724. */
  68725. this.vignetteStretch = 0;
  68726. /**
  68727. * Vignette centre X Offset.
  68728. */
  68729. this.vignetteCentreX = 0;
  68730. /**
  68731. * Vignette centre Y Offset.
  68732. */
  68733. this.vignetteCentreY = 0;
  68734. /**
  68735. * Vignette weight or intensity of the vignette effect.
  68736. */
  68737. this.vignetteWeight = 1.5;
  68738. /**
  68739. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  68740. * if vignetteEnabled is set to true.
  68741. */
  68742. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  68743. /**
  68744. * Camera field of view used by the Vignette effect.
  68745. */
  68746. this.vignetteCameraFov = 0.5;
  68747. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  68748. this._vignetteEnabled = false;
  68749. this._applyByPostProcess = false;
  68750. /**
  68751. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  68752. * @type {BABYLON.Observable}
  68753. */
  68754. this.onUpdateParameters = new BABYLON.Observable();
  68755. }
  68756. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  68757. /**
  68758. * Gets wether the color curves effect is enabled.
  68759. */
  68760. get: function () {
  68761. return this._colorCurvesEnabled;
  68762. },
  68763. /**
  68764. * Sets wether the color curves effect is enabled.
  68765. */
  68766. set: function (value) {
  68767. if (this._colorCurvesEnabled === value) {
  68768. return;
  68769. }
  68770. this._colorCurvesEnabled = value;
  68771. this._updateParameters();
  68772. },
  68773. enumerable: true,
  68774. configurable: true
  68775. });
  68776. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  68777. /**
  68778. * Gets wether the color grading effect is enabled.
  68779. */
  68780. get: function () {
  68781. return this._colorGradingEnabled;
  68782. },
  68783. /**
  68784. * Sets wether the color grading effect is enabled.
  68785. */
  68786. set: function (value) {
  68787. if (this._colorGradingEnabled === value) {
  68788. return;
  68789. }
  68790. this._colorGradingEnabled = value;
  68791. this._updateParameters();
  68792. },
  68793. enumerable: true,
  68794. configurable: true
  68795. });
  68796. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  68797. /**
  68798. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  68799. */
  68800. get: function () {
  68801. return this._colorGradingWithGreenDepth;
  68802. },
  68803. /**
  68804. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  68805. */
  68806. set: function (value) {
  68807. if (this._colorGradingWithGreenDepth === value) {
  68808. return;
  68809. }
  68810. this._colorGradingWithGreenDepth = value;
  68811. this._updateParameters();
  68812. },
  68813. enumerable: true,
  68814. configurable: true
  68815. });
  68816. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  68817. /**
  68818. * Gets wether the color grading texture contains BGR values.
  68819. */
  68820. get: function () {
  68821. return this._colorGradingBGR;
  68822. },
  68823. /**
  68824. * Sets wether the color grading texture contains BGR values.
  68825. */
  68826. set: function (value) {
  68827. if (this._colorGradingBGR === value) {
  68828. return;
  68829. }
  68830. this._colorGradingBGR = value;
  68831. this._updateParameters();
  68832. },
  68833. enumerable: true,
  68834. configurable: true
  68835. });
  68836. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  68837. /**
  68838. * Gets the Exposure used in the effect.
  68839. */
  68840. get: function () {
  68841. return this._exposure;
  68842. },
  68843. /**
  68844. * Sets the Exposure used in the effect.
  68845. */
  68846. set: function (value) {
  68847. if (this._exposure === value) {
  68848. return;
  68849. }
  68850. this._exposure = value;
  68851. this._updateParameters();
  68852. },
  68853. enumerable: true,
  68854. configurable: true
  68855. });
  68856. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  68857. /**
  68858. * Gets wether the tone mapping effect is enabled.
  68859. */
  68860. get: function () {
  68861. return this._toneMappingEnabled;
  68862. },
  68863. /**
  68864. * Sets wether the tone mapping effect is enabled.
  68865. */
  68866. set: function (value) {
  68867. if (this._toneMappingEnabled === value) {
  68868. return;
  68869. }
  68870. this._toneMappingEnabled = value;
  68871. this._updateParameters();
  68872. },
  68873. enumerable: true,
  68874. configurable: true
  68875. });
  68876. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  68877. /**
  68878. * Gets the contrast used in the effect.
  68879. */
  68880. get: function () {
  68881. return this._contrast;
  68882. },
  68883. /**
  68884. * Sets the contrast used in the effect.
  68885. */
  68886. set: function (value) {
  68887. if (this._contrast === value) {
  68888. return;
  68889. }
  68890. this._contrast = value;
  68891. this._updateParameters();
  68892. },
  68893. enumerable: true,
  68894. configurable: true
  68895. });
  68896. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  68897. /**
  68898. * Gets the vignette blend mode allowing different kind of effect.
  68899. */
  68900. get: function () {
  68901. return this._vignetteBlendMode;
  68902. },
  68903. /**
  68904. * Sets the vignette blend mode allowing different kind of effect.
  68905. */
  68906. set: function (value) {
  68907. if (this._vignetteBlendMode === value) {
  68908. return;
  68909. }
  68910. this._vignetteBlendMode = value;
  68911. this._updateParameters();
  68912. },
  68913. enumerable: true,
  68914. configurable: true
  68915. });
  68916. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  68917. /**
  68918. * Gets wether the vignette effect is enabled.
  68919. */
  68920. get: function () {
  68921. return this._vignetteEnabled;
  68922. },
  68923. /**
  68924. * Sets wether the vignette effect is enabled.
  68925. */
  68926. set: function (value) {
  68927. if (this._vignetteEnabled === value) {
  68928. return;
  68929. }
  68930. this._vignetteEnabled = value;
  68931. this._updateParameters();
  68932. },
  68933. enumerable: true,
  68934. configurable: true
  68935. });
  68936. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  68937. /**
  68938. * Gets wether the image processing is applied through a post process or not.
  68939. */
  68940. get: function () {
  68941. return this._applyByPostProcess;
  68942. },
  68943. /**
  68944. * Sets wether the image processing is applied through a post process or not.
  68945. */
  68946. set: function (value) {
  68947. if (this._applyByPostProcess === value) {
  68948. return;
  68949. }
  68950. this._applyByPostProcess = value;
  68951. this._updateParameters();
  68952. },
  68953. enumerable: true,
  68954. configurable: true
  68955. });
  68956. /**
  68957. * Method called each time the image processing information changes requires to recompile the effect.
  68958. */
  68959. ImageProcessingConfiguration.prototype._updateParameters = function () {
  68960. this.onUpdateParameters.notifyObservers(this);
  68961. };
  68962. ImageProcessingConfiguration.prototype.getClassName = function () {
  68963. return "ImageProcessingConfiguration";
  68964. };
  68965. /**
  68966. * Prepare the list of uniforms associated with the Image Processing effects.
  68967. * @param uniformsList The list of uniforms used in the effect
  68968. * @param defines the list of defines currently in use
  68969. */
  68970. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  68971. if (defines.EXPOSURE) {
  68972. uniforms.push("exposureLinear");
  68973. }
  68974. if (defines.CONTRAST) {
  68975. uniforms.push("contrast");
  68976. }
  68977. if (defines.COLORGRADING) {
  68978. uniforms.push("colorTransformSettings");
  68979. }
  68980. if (defines.VIGNETTE) {
  68981. uniforms.push("vInverseScreenSize");
  68982. uniforms.push("vignetteSettings1");
  68983. uniforms.push("vignetteSettings2");
  68984. }
  68985. if (defines.COLORCURVES) {
  68986. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  68987. }
  68988. };
  68989. /**
  68990. * Prepare the list of samplers associated with the Image Processing effects.
  68991. * @param uniformsList The list of uniforms used in the effect
  68992. * @param defines the list of defines currently in use
  68993. */
  68994. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  68995. if (defines.COLORGRADING) {
  68996. samplersList.push("txColorTransform");
  68997. }
  68998. };
  68999. /**
  69000. * Prepare the list of defines associated to the shader.
  69001. * @param defines the list of defines to complete
  69002. */
  69003. ImageProcessingConfiguration.prototype.prepareDefines = function (defines) {
  69004. defines.VIGNETTE = this.vignetteEnabled;
  69005. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  69006. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  69007. defines.TONEMAPPING = this.toneMappingEnabled;
  69008. defines.CONTRAST = (this.contrast !== 1.0);
  69009. defines.EXPOSURE = (this.exposure !== 1.0);
  69010. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  69011. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  69012. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  69013. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  69014. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  69015. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  69016. };
  69017. /**
  69018. * Returns true if all the image processing information are ready.
  69019. */
  69020. ImageProcessingConfiguration.prototype.isReady = function () {
  69021. // Color Grading texure can not be none blocking.
  69022. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  69023. };
  69024. /**
  69025. * Binds the image processing to the shader.
  69026. * @param effect The effect to bind to
  69027. */
  69028. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  69029. if (aspectRatio === void 0) { aspectRatio = 1; }
  69030. // Color Curves
  69031. if (this._colorCurvesEnabled) {
  69032. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  69033. }
  69034. // Vignette
  69035. if (this._vignetteEnabled) {
  69036. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  69037. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  69038. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  69039. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  69040. var vignetteScaleX = vignetteScaleY * aspectRatio;
  69041. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  69042. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  69043. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  69044. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  69045. var vignettePower = -2.0 * this.vignetteWeight;
  69046. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  69047. }
  69048. // Exposure
  69049. effect.setFloat("exposureLinear", this.exposure);
  69050. // Contrast
  69051. effect.setFloat("contrast", this.contrast);
  69052. // Color transform settings
  69053. if (this.colorGradingTexture) {
  69054. effect.setTexture("txColorTransform", this.colorGradingTexture);
  69055. var textureSize = this.colorGradingTexture.getSize().height;
  69056. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  69057. 0.5 / textureSize, // textureOffset
  69058. textureSize, // textureSize
  69059. this.colorGradingTexture.level // weight
  69060. );
  69061. }
  69062. };
  69063. /**
  69064. * Clones the current image processing instance.
  69065. * @return The cloned image processing
  69066. */
  69067. ImageProcessingConfiguration.prototype.clone = function () {
  69068. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  69069. };
  69070. /**
  69071. * Serializes the current image processing instance to a json representation.
  69072. * @return a JSON representation
  69073. */
  69074. ImageProcessingConfiguration.prototype.serialize = function () {
  69075. return BABYLON.SerializationHelper.Serialize(this);
  69076. };
  69077. /**
  69078. * Parses the image processing from a json representation.
  69079. * @param source the JSON source to parse
  69080. * @return The parsed image processing
  69081. */
  69082. ImageProcessingConfiguration.Parse = function (source) {
  69083. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  69084. };
  69085. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  69086. /**
  69087. * Used to apply the vignette as a mix with the pixel color.
  69088. */
  69089. get: function () {
  69090. return this._VIGNETTEMODE_MULTIPLY;
  69091. },
  69092. enumerable: true,
  69093. configurable: true
  69094. });
  69095. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  69096. /**
  69097. * Used to apply the vignette as a replacement of the pixel color.
  69098. */
  69099. get: function () {
  69100. return this._VIGNETTEMODE_OPAQUE;
  69101. },
  69102. enumerable: true,
  69103. configurable: true
  69104. });
  69105. // Static constants associated to the image processing.
  69106. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  69107. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  69108. __decorate([
  69109. BABYLON.serializeAsColorCurves()
  69110. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  69111. __decorate([
  69112. BABYLON.serialize()
  69113. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  69114. __decorate([
  69115. BABYLON.serializeAsTexture()
  69116. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  69117. __decorate([
  69118. BABYLON.serialize()
  69119. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  69120. __decorate([
  69121. BABYLON.serialize()
  69122. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  69123. __decorate([
  69124. BABYLON.serialize()
  69125. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  69126. __decorate([
  69127. BABYLON.serialize()
  69128. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  69129. __decorate([
  69130. BABYLON.serialize()
  69131. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  69132. __decorate([
  69133. BABYLON.serialize()
  69134. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  69135. __decorate([
  69136. BABYLON.serialize()
  69137. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  69138. __decorate([
  69139. BABYLON.serialize()
  69140. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  69141. __decorate([
  69142. BABYLON.serialize()
  69143. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  69144. __decorate([
  69145. BABYLON.serialize()
  69146. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  69147. __decorate([
  69148. BABYLON.serializeAsColor4()
  69149. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  69150. __decorate([
  69151. BABYLON.serialize()
  69152. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  69153. __decorate([
  69154. BABYLON.serialize()
  69155. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  69156. __decorate([
  69157. BABYLON.serialize()
  69158. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  69159. __decorate([
  69160. BABYLON.serialize()
  69161. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  69162. return ImageProcessingConfiguration;
  69163. }());
  69164. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  69165. })(BABYLON || (BABYLON = {}));
  69166. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  69167. var BABYLON;
  69168. (function (BABYLON) {
  69169. var serializedGeometries = [];
  69170. var serializeGeometry = function (geometry, serializationGeometries) {
  69171. if (serializedGeometries[geometry.id]) {
  69172. return;
  69173. }
  69174. if (geometry.doNotSerialize) {
  69175. return;
  69176. }
  69177. if (geometry instanceof BABYLON.Geometry.Primitives.Box) {
  69178. serializationGeometries.boxes.push(geometry.serialize());
  69179. }
  69180. else if (geometry instanceof BABYLON.Geometry.Primitives.Sphere) {
  69181. serializationGeometries.spheres.push(geometry.serialize());
  69182. }
  69183. else if (geometry instanceof BABYLON.Geometry.Primitives.Cylinder) {
  69184. serializationGeometries.cylinders.push(geometry.serialize());
  69185. }
  69186. else if (geometry instanceof BABYLON.Geometry.Primitives.Torus) {
  69187. serializationGeometries.toruses.push(geometry.serialize());
  69188. }
  69189. else if (geometry instanceof BABYLON.Geometry.Primitives.Ground) {
  69190. serializationGeometries.grounds.push(geometry.serialize());
  69191. }
  69192. else if (geometry instanceof BABYLON.Geometry.Primitives.Plane) {
  69193. serializationGeometries.planes.push(geometry.serialize());
  69194. }
  69195. else if (geometry instanceof BABYLON.Geometry.Primitives.TorusKnot) {
  69196. serializationGeometries.torusKnots.push(geometry.serialize());
  69197. }
  69198. else if (geometry instanceof BABYLON.Geometry.Primitives._Primitive) {
  69199. throw new Error("Unknown primitive type");
  69200. }
  69201. else {
  69202. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  69203. }
  69204. serializedGeometries[geometry.id] = true;
  69205. };
  69206. var serializeMesh = function (mesh, serializationScene) {
  69207. var serializationObject = {};
  69208. // Geometry
  69209. var geometry = mesh._geometry;
  69210. if (geometry) {
  69211. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  69212. // 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
  69213. serializeGeometry(geometry, serializationScene.geometries);
  69214. }
  69215. }
  69216. // Custom
  69217. if (mesh.serialize) {
  69218. mesh.serialize(serializationObject);
  69219. }
  69220. return serializationObject;
  69221. };
  69222. var finalizeSingleMesh = function (mesh, serializationObject) {
  69223. //only works if the mesh is already loaded
  69224. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69225. //serialize material
  69226. if (mesh.material) {
  69227. if (mesh.material instanceof BABYLON.StandardMaterial) {
  69228. serializationObject.materials = serializationObject.materials || [];
  69229. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69230. serializationObject.materials.push(mesh.material.serialize());
  69231. }
  69232. }
  69233. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  69234. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  69235. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  69236. serializationObject.multiMaterials.push(mesh.material.serialize());
  69237. }
  69238. }
  69239. }
  69240. //serialize geometry
  69241. var geometry = mesh._geometry;
  69242. if (geometry) {
  69243. if (!serializationObject.geometries) {
  69244. serializationObject.geometries = {};
  69245. serializationObject.geometries.boxes = [];
  69246. serializationObject.geometries.spheres = [];
  69247. serializationObject.geometries.cylinders = [];
  69248. serializationObject.geometries.toruses = [];
  69249. serializationObject.geometries.grounds = [];
  69250. serializationObject.geometries.planes = [];
  69251. serializationObject.geometries.torusKnots = [];
  69252. serializationObject.geometries.vertexData = [];
  69253. }
  69254. serializeGeometry(geometry, serializationObject.geometries);
  69255. }
  69256. // Skeletons
  69257. if (mesh.skeleton) {
  69258. serializationObject.skeletons = serializationObject.skeletons || [];
  69259. serializationObject.skeletons.push(mesh.skeleton.serialize());
  69260. }
  69261. //serialize the actual mesh
  69262. serializationObject.meshes = serializationObject.meshes || [];
  69263. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69264. }
  69265. };
  69266. var SceneSerializer = (function () {
  69267. function SceneSerializer() {
  69268. }
  69269. SceneSerializer.ClearCache = function () {
  69270. serializedGeometries = [];
  69271. };
  69272. SceneSerializer.Serialize = function (scene) {
  69273. var serializationObject = {};
  69274. SceneSerializer.ClearCache();
  69275. // Scene
  69276. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  69277. serializationObject.autoClear = scene.autoClear;
  69278. serializationObject.clearColor = scene.clearColor.asArray();
  69279. serializationObject.ambientColor = scene.ambientColor.asArray();
  69280. serializationObject.gravity = scene.gravity.asArray();
  69281. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  69282. serializationObject.workerCollisions = scene.workerCollisions;
  69283. // Fog
  69284. if (scene.fogMode && scene.fogMode !== 0) {
  69285. serializationObject.fogMode = scene.fogMode;
  69286. serializationObject.fogColor = scene.fogColor.asArray();
  69287. serializationObject.fogStart = scene.fogStart;
  69288. serializationObject.fogEnd = scene.fogEnd;
  69289. serializationObject.fogDensity = scene.fogDensity;
  69290. }
  69291. //Physics
  69292. if (scene.isPhysicsEnabled()) {
  69293. serializationObject.physicsEnabled = true;
  69294. serializationObject.physicsGravity = scene.getPhysicsEngine().gravity.asArray();
  69295. serializationObject.physicsEngine = scene.getPhysicsEngine().getPhysicsPluginName();
  69296. }
  69297. // Metadata
  69298. if (scene.metadata) {
  69299. serializationObject.metadata = scene.metadata;
  69300. }
  69301. // Morph targets
  69302. serializationObject.morphTargetManagers = [];
  69303. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  69304. var abstractMesh = _a[_i];
  69305. var manager = abstractMesh.morphTargetManager;
  69306. if (manager) {
  69307. serializationObject.morphTargetManagers.push(manager.serialize());
  69308. }
  69309. }
  69310. // Lights
  69311. serializationObject.lights = [];
  69312. var index;
  69313. var light;
  69314. for (index = 0; index < scene.lights.length; index++) {
  69315. light = scene.lights[index];
  69316. if (!light.doNotSerialize) {
  69317. serializationObject.lights.push(light.serialize());
  69318. }
  69319. }
  69320. // Cameras
  69321. serializationObject.cameras = [];
  69322. for (index = 0; index < scene.cameras.length; index++) {
  69323. var camera = scene.cameras[index];
  69324. if (!camera.doNotSerialize) {
  69325. serializationObject.cameras.push(camera.serialize());
  69326. }
  69327. }
  69328. if (scene.activeCamera) {
  69329. serializationObject.activeCameraID = scene.activeCamera.id;
  69330. }
  69331. // Animations
  69332. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  69333. // Materials
  69334. serializationObject.materials = [];
  69335. serializationObject.multiMaterials = [];
  69336. var material;
  69337. for (index = 0; index < scene.materials.length; index++) {
  69338. material = scene.materials[index];
  69339. if (!material.doNotSerialize) {
  69340. serializationObject.materials.push(material.serialize());
  69341. }
  69342. }
  69343. // MultiMaterials
  69344. serializationObject.multiMaterials = [];
  69345. for (index = 0; index < scene.multiMaterials.length; index++) {
  69346. var multiMaterial = scene.multiMaterials[index];
  69347. serializationObject.multiMaterials.push(multiMaterial.serialize());
  69348. }
  69349. // Skeletons
  69350. serializationObject.skeletons = [];
  69351. for (index = 0; index < scene.skeletons.length; index++) {
  69352. serializationObject.skeletons.push(scene.skeletons[index].serialize());
  69353. }
  69354. // Geometries
  69355. serializationObject.geometries = {};
  69356. serializationObject.geometries.boxes = [];
  69357. serializationObject.geometries.spheres = [];
  69358. serializationObject.geometries.cylinders = [];
  69359. serializationObject.geometries.toruses = [];
  69360. serializationObject.geometries.grounds = [];
  69361. serializationObject.geometries.planes = [];
  69362. serializationObject.geometries.torusKnots = [];
  69363. serializationObject.geometries.vertexData = [];
  69364. serializedGeometries = [];
  69365. var geometries = scene.getGeometries();
  69366. for (index = 0; index < geometries.length; index++) {
  69367. var geometry = geometries[index];
  69368. if (geometry.isReady()) {
  69369. serializeGeometry(geometry, serializationObject.geometries);
  69370. }
  69371. }
  69372. // Meshes
  69373. serializationObject.meshes = [];
  69374. for (index = 0; index < scene.meshes.length; index++) {
  69375. var abstractMesh = scene.meshes[index];
  69376. if (abstractMesh instanceof BABYLON.Mesh) {
  69377. var mesh = abstractMesh;
  69378. if (!mesh.doNotSerialize) {
  69379. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  69380. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  69381. }
  69382. }
  69383. }
  69384. }
  69385. // Particles Systems
  69386. serializationObject.particleSystems = [];
  69387. for (index = 0; index < scene.particleSystems.length; index++) {
  69388. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  69389. }
  69390. // Lens flares
  69391. serializationObject.lensFlareSystems = [];
  69392. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  69393. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  69394. }
  69395. // Shadows
  69396. serializationObject.shadowGenerators = [];
  69397. for (index = 0; index < scene.lights.length; index++) {
  69398. light = scene.lights[index];
  69399. var shadowGenerator = light.getShadowGenerator();
  69400. if (shadowGenerator) {
  69401. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  69402. }
  69403. }
  69404. // Action Manager
  69405. if (scene.actionManager) {
  69406. serializationObject.actions = scene.actionManager.serialize("scene");
  69407. }
  69408. // Audio
  69409. serializationObject.sounds = [];
  69410. for (index = 0; index < scene.soundTracks.length; index++) {
  69411. var soundtrack = scene.soundTracks[index];
  69412. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  69413. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  69414. }
  69415. }
  69416. return serializationObject;
  69417. };
  69418. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  69419. if (withParents === void 0) { withParents = false; }
  69420. if (withChildren === void 0) { withChildren = false; }
  69421. var serializationObject = {};
  69422. SceneSerializer.ClearCache();
  69423. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  69424. if (withParents || withChildren) {
  69425. //deliberate for loop! not for each, appended should be processed as well.
  69426. for (var i = 0; i < toSerialize.length; ++i) {
  69427. if (withChildren) {
  69428. toSerialize[i].getDescendants().forEach(function (node) {
  69429. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  69430. toSerialize.push(node);
  69431. }
  69432. });
  69433. }
  69434. //make sure the array doesn't contain the object already
  69435. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  69436. toSerialize.push(toSerialize[i].parent);
  69437. }
  69438. }
  69439. }
  69440. toSerialize.forEach(function (mesh) {
  69441. finalizeSingleMesh(mesh, serializationObject);
  69442. });
  69443. return serializationObject;
  69444. };
  69445. return SceneSerializer;
  69446. }());
  69447. BABYLON.SceneSerializer = SceneSerializer;
  69448. })(BABYLON || (BABYLON = {}));
  69449. //# sourceMappingURL=babylon.sceneSerializer.js.map
  69450. var BABYLON;
  69451. (function (BABYLON) {
  69452. var ReflectionProbe = (function () {
  69453. function ReflectionProbe(name, size, scene, generateMipMaps) {
  69454. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69455. var _this = this;
  69456. this.name = name;
  69457. this._viewMatrix = BABYLON.Matrix.Identity();
  69458. this._target = BABYLON.Vector3.Zero();
  69459. this._add = BABYLON.Vector3.Zero();
  69460. this.invertYAxis = false;
  69461. this.position = BABYLON.Vector3.Zero();
  69462. this._scene = scene;
  69463. this._scene.reflectionProbes.push(this);
  69464. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  69465. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  69466. switch (faceIndex) {
  69467. case 0:
  69468. _this._add.copyFromFloats(1, 0, 0);
  69469. break;
  69470. case 1:
  69471. _this._add.copyFromFloats(-1, 0, 0);
  69472. break;
  69473. case 2:
  69474. _this._add.copyFromFloats(0, _this.invertYAxis ? 1 : -1, 0);
  69475. break;
  69476. case 3:
  69477. _this._add.copyFromFloats(0, _this.invertYAxis ? -1 : 1, 0);
  69478. break;
  69479. case 4:
  69480. _this._add.copyFromFloats(0, 0, 1);
  69481. break;
  69482. case 5:
  69483. _this._add.copyFromFloats(0, 0, -1);
  69484. break;
  69485. }
  69486. if (_this._attachedMesh) {
  69487. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  69488. }
  69489. _this.position.addToRef(_this._add, _this._target);
  69490. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  69491. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  69492. });
  69493. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  69494. scene.updateTransformMatrix(true);
  69495. });
  69496. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  69497. }
  69498. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  69499. get: function () {
  69500. return this._renderTargetTexture.samples;
  69501. },
  69502. set: function (value) {
  69503. this._renderTargetTexture.samples = value;
  69504. },
  69505. enumerable: true,
  69506. configurable: true
  69507. });
  69508. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  69509. get: function () {
  69510. return this._renderTargetTexture.refreshRate;
  69511. },
  69512. set: function (value) {
  69513. this._renderTargetTexture.refreshRate = value;
  69514. },
  69515. enumerable: true,
  69516. configurable: true
  69517. });
  69518. ReflectionProbe.prototype.getScene = function () {
  69519. return this._scene;
  69520. };
  69521. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  69522. get: function () {
  69523. return this._renderTargetTexture;
  69524. },
  69525. enumerable: true,
  69526. configurable: true
  69527. });
  69528. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  69529. get: function () {
  69530. return this._renderTargetTexture.renderList;
  69531. },
  69532. enumerable: true,
  69533. configurable: true
  69534. });
  69535. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  69536. this._attachedMesh = mesh;
  69537. };
  69538. /**
  69539. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  69540. *
  69541. * @param renderingGroupId The rendering group id corresponding to its index
  69542. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  69543. */
  69544. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  69545. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  69546. };
  69547. ReflectionProbe.prototype.dispose = function () {
  69548. var index = this._scene.reflectionProbes.indexOf(this);
  69549. if (index !== -1) {
  69550. // Remove from the scene if found
  69551. this._scene.reflectionProbes.splice(index, 1);
  69552. }
  69553. if (this._renderTargetTexture) {
  69554. this._renderTargetTexture.dispose();
  69555. this._renderTargetTexture = null;
  69556. }
  69557. };
  69558. return ReflectionProbe;
  69559. }());
  69560. BABYLON.ReflectionProbe = ReflectionProbe;
  69561. })(BABYLON || (BABYLON = {}));
  69562. //# sourceMappingURL=babylon.reflectionProbe.js.map
  69563. var BABYLON;
  69564. (function (BABYLON) {
  69565. var Layer = (function () {
  69566. function Layer(name, imgUrl, scene, isBackground, color) {
  69567. this.name = name;
  69568. this.scale = new BABYLON.Vector2(1, 1);
  69569. this.offset = new BABYLON.Vector2(0, 0);
  69570. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  69571. this.layerMask = 0x0FFFFFFF;
  69572. this._vertexBuffers = {};
  69573. // Events
  69574. /**
  69575. * An event triggered when the layer is disposed.
  69576. * @type {BABYLON.Observable}
  69577. */
  69578. this.onDisposeObservable = new BABYLON.Observable();
  69579. /**
  69580. * An event triggered before rendering the scene
  69581. * @type {BABYLON.Observable}
  69582. */
  69583. this.onBeforeRenderObservable = new BABYLON.Observable();
  69584. /**
  69585. * An event triggered after rendering the scene
  69586. * @type {BABYLON.Observable}
  69587. */
  69588. this.onAfterRenderObservable = new BABYLON.Observable();
  69589. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  69590. this.isBackground = isBackground === undefined ? true : isBackground;
  69591. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  69592. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  69593. this._scene.layers.push(this);
  69594. var engine = this._scene.getEngine();
  69595. this._rebuild();
  69596. // Effects
  69597. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  69598. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  69599. }
  69600. Object.defineProperty(Layer.prototype, "onDispose", {
  69601. set: function (callback) {
  69602. if (this._onDisposeObserver) {
  69603. this.onDisposeObservable.remove(this._onDisposeObserver);
  69604. }
  69605. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  69606. },
  69607. enumerable: true,
  69608. configurable: true
  69609. });
  69610. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  69611. set: function (callback) {
  69612. if (this._onBeforeRenderObserver) {
  69613. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  69614. }
  69615. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  69616. },
  69617. enumerable: true,
  69618. configurable: true
  69619. });
  69620. Object.defineProperty(Layer.prototype, "onAfterRender", {
  69621. set: function (callback) {
  69622. if (this._onAfterRenderObserver) {
  69623. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  69624. }
  69625. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  69626. },
  69627. enumerable: true,
  69628. configurable: true
  69629. });
  69630. Layer.prototype._rebuild = function () {
  69631. var engine = this._scene.getEngine();
  69632. // VBO
  69633. var vertices = [];
  69634. vertices.push(1, 1);
  69635. vertices.push(-1, 1);
  69636. vertices.push(-1, -1);
  69637. vertices.push(1, -1);
  69638. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69639. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  69640. // Indices
  69641. var indices = [];
  69642. indices.push(0);
  69643. indices.push(1);
  69644. indices.push(2);
  69645. indices.push(0);
  69646. indices.push(2);
  69647. indices.push(3);
  69648. this._indexBuffer = engine.createIndexBuffer(indices);
  69649. };
  69650. Layer.prototype.render = function () {
  69651. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  69652. // Check
  69653. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  69654. return;
  69655. var engine = this._scene.getEngine();
  69656. this.onBeforeRenderObservable.notifyObservers(this);
  69657. // Render
  69658. engine.enableEffect(currentEffect);
  69659. engine.setState(false);
  69660. // Texture
  69661. currentEffect.setTexture("textureSampler", this.texture);
  69662. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  69663. // Color
  69664. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  69665. // Scale / offset
  69666. currentEffect.setVector2("offset", this.offset);
  69667. currentEffect.setVector2("scale", this.scale);
  69668. // VBOs
  69669. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  69670. // Draw order
  69671. if (!this.alphaTest) {
  69672. engine.setAlphaMode(this.alphaBlendingMode);
  69673. engine.draw(true, 0, 6);
  69674. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  69675. }
  69676. else {
  69677. engine.draw(true, 0, 6);
  69678. }
  69679. this.onAfterRenderObservable.notifyObservers(this);
  69680. };
  69681. Layer.prototype.dispose = function () {
  69682. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69683. if (vertexBuffer) {
  69684. vertexBuffer.dispose();
  69685. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  69686. }
  69687. if (this._indexBuffer) {
  69688. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  69689. this._indexBuffer = null;
  69690. }
  69691. if (this.texture) {
  69692. this.texture.dispose();
  69693. this.texture = null;
  69694. }
  69695. // Remove from scene
  69696. var index = this._scene.layers.indexOf(this);
  69697. this._scene.layers.splice(index, 1);
  69698. // Callback
  69699. this.onDisposeObservable.notifyObservers(this);
  69700. this.onDisposeObservable.clear();
  69701. this.onAfterRenderObservable.clear();
  69702. this.onBeforeRenderObservable.clear();
  69703. };
  69704. return Layer;
  69705. }());
  69706. BABYLON.Layer = Layer;
  69707. })(BABYLON || (BABYLON = {}));
  69708. //# sourceMappingURL=babylon.layer.js.map
  69709. var BABYLON;
  69710. (function (BABYLON) {
  69711. var TextureTools = (function () {
  69712. function TextureTools() {
  69713. }
  69714. /**
  69715. * Uses the GPU to create a copy texture rescaled at a given size
  69716. * @param texture Texture to copy from
  69717. * @param width Desired width
  69718. * @param height Desired height
  69719. * @return Generated texture
  69720. */
  69721. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  69722. if (useBilinearMode === void 0) { useBilinearMode = true; }
  69723. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  69724. var scene = texture.getScene();
  69725. var engine = scene.getEngine();
  69726. rtt.wrapU = texture.wrapU;
  69727. rtt.wrapV = texture.wrapV;
  69728. rtt.uOffset = texture.uOffset;
  69729. rtt.vOffset = texture.vOffset;
  69730. rtt.uScale = texture.uScale;
  69731. rtt.vScale = texture.vScale;
  69732. rtt.uAng = texture.uAng;
  69733. rtt.vAng = texture.vAng;
  69734. rtt.wAng = texture.wAng;
  69735. rtt.coordinatesIndex = texture.coordinatesIndex;
  69736. rtt.level = texture.level;
  69737. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  69738. rtt._texture.isReady = false;
  69739. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69740. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69741. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  69742. passPostProcess.getEffect().executeWhenCompiled(function () {
  69743. passPostProcess.onApply = function (effect) {
  69744. effect.setTexture("textureSampler", texture);
  69745. };
  69746. scene.postProcessManager.directRender([passPostProcess], rtt.getInternalTexture());
  69747. engine.unBindFramebuffer(rtt.getInternalTexture());
  69748. rtt.disposeFramebufferObjects();
  69749. passPostProcess.dispose();
  69750. rtt._texture.isReady = true;
  69751. });
  69752. return rtt;
  69753. };
  69754. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  69755. if (!scene._environmentBRDFTexture) {
  69756. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  69757. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69758. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  69759. scene._environmentBRDFTexture = texture;
  69760. }
  69761. return scene._environmentBRDFTexture;
  69762. };
  69763. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/eud9fvn27rf9evPPwFz+v22S7fGZ/n7/70G79J5/Xv/qzbLP+Pnvvoc/6Tz7jX/15/c62LfeH7fofbpfP3l/ct36Wf+u4+D37+XYb++G26LPsr/zFttnPuh37bm1bt0f7MvtlnOx4uv0H4fty8UUsz77rfn/57u32cgXvDv72eQf0tl0+G38b0Nf9K4Dl704MEfA16KsE8Gw9JgD+DQE8EA0DT2b7GwK4GHnF4a8iguXZt9/vL5/dbisJbEq/uwD5vIK/fbbAv4N9U/8nJIDNCazKvBLBGwdwu62OhajxmQSAx6gqNp5HCg9wPan2nwSNjhLD8ux/3u8vP3y7vbwDAYjtR8AzFyDqLu1Q+YEINnew23rPCYiKb+q/K7o4AVT4tg0t/h4ydJZfkQASQ/d5b9fZ/Z1ENmuPn/cwYCYEELBguKC3nRkCnE0AFOwOKCOAR/sH/L4hgFMpbSWP5dn/uN9ffs7t9mJ5cAHoBLTyszBAFJ/F/xIKdASw5wgaEWDMLySxAk4svf6L+4QAGPiJCziNAPb4f3UZ2dh/m+z7BK4SAPYrxf5FB6ABPgCUAfANAZwKyscc7IEA/vv9/uLzbreXzx9cQCMACAl00m8jAlF7ov6SCMQ8gJsMFFBnCECSg5H6TxJAU3vPAbwhgFfz9AABeOEDBcIbB3AqPzwQwH+731/8sNvt5Ydut5e3B2C/fG9P+jESgGz/RgxG9r9VAwTUUh0goQDafUz+DYnAnSha5l99Z1l/yQVswAZSGIAugNd/9xBgCw9E8aECkHUB22QPHIAVDlQdQAMWAibhBgZAasAVHUAI8Cqg96Tm0bj3VBS9jwd7IIBvuN9ffMHt9vLTbreXy+32QlwAhgMIeuNzKwOqCoB2Aa00KHE+EsIeDuj4H2N+Hf/TfAC6A4nhgQCQDDwiaKDXiq9KgBEJNPArAtCk0AEd2mpAizW3/lYIoANpBPg3BPA+hjs/9eXZV+0E8Bm32wsJA9aEoBCAuAABPiEAC/yDC4gSgRgKRHkAlgsI6v7iEFqJEMgBwb4BGkEfEEDnDlReoAP/SQRgOYIB+IYDMEE/SQBbXoLNr0jhq4qOZc0PHBSf5oKW519xvz//kbfby8+83V68ABfwniIBgwgQ/HoRUMv8w5qAoQqgk4DWQiCw+63eD8k/XAPQgK5s/5a5xzAAqgR6wY9k+ZEMtCOoJABb230hEHMFWQdgAl0Ap/+uc6tKBrrP/n0AuwfiNwTwNKguHHV5/qX3+/M1B/Ddb7cXax7g2e324vaQB3hhkMAW92tHoFb96cVAbimwkgQ0Vv7R+D8iACfuxzKfLvnNlAAjAsBwwP2MwLQAD9sbYJME0AFcg5uBPSAA0x0AobhtcDKDA0j3KYDhk7Hp8uKj9/vzH3C7vfget9uLT9nDgDUZuOYCLBJA8MNKPyGGIftPrL+4gy3eh5p/lwRUYYAs9Fn7tM/E9lvJwCH2DxJ/mPTr4nyyLiDtBgTAGCrgNuPzNuETgN+suEEAFhng9lkCoICMLH7V0isCeEMCxylrefkl9/uzz90J4NNUGLDmAnYXINUBrf5dCCAuQCcCvYVAYPk3G++VAveVfkIAFRLolgbr2F9ifP33pAqAV/fHRF4HcAS7AKlAAEIYFNwITOszs/wMsB6II4BXFZ0QwBsSOEYCDwTw2TsBfPrt9uLlqzCgcwFABI0EVCiANl8Uvq0JWNsi2JPZ/0YKsOiHxftsW4v51ZqAaBWgZf91PsBL/jFHwEqBR1cCiuJ3gAfCmCEA3cf8rmz8AMZHIoA3JDBPAsuHVgL4jNvt+UoCH34ggK0asIYBGArsAB7AD+reQgCl+GwZ8LaNlP3MEEDaSg4ACMGr/+ulwV4JsAEfLH42/vdKgWElAJ4QpBl+LAlKErHwt+oGMgTA2ngE4IUIOH3dGr/hAKT/m/UBdSJYPuVL7vflU26352sScCWAD+0EsCcDVxewKjfmAzAsENVn4EfgdySgnYB81yEAgL4RA8T8mTUASAAYBgylQAkL8K/+zL6rsl8qF6ArAeS7WRGoAB8Sf7isN/VZqTs6jQ5wXlweWfyqpQ8I4I0TmCCAT/3I/b48u92ef9bt9nwNAdZE4FoOFALYXcAGegkDMByAzzQEgJh+cAIs/legH0IA5QTCPADE+7ISkD0TgA/8sBIgLQfOgF/F9kPcr+J8fIYguyCILQRKgV4DNviOzoKqeJS0u4AA3pBAjQSWT//I/b5OmC0MWB3ASgBrGLA+IryvDNxCgRXo+wKhjgwk8bcTwUACsJ09ANRVAALwCxmEoFcrAUsuAJ4M1E8BDuHABAHomJ8RgACrZfQLyT9dBWi2OOEG9NJd/TDQ8HAQuBE97ZhjGKy6o+imnU+4gDckkCeB5cMfud/v6zr9Dz84gOdCAM/3JwQhF9CAD25gBWWz/8wNgMpj3K9Lfy0foMMBVffXyT4r+cceC9bvCcDFP0311QrATPkvWgosYQFLAuoqQEcQuw3v2si25F+M1RkZXLUU+CgBmCBOEsCbvECOBJbP+Oj9fv+u2+3Zp91uz9cy4Kfebs/3ROD6iPD2b10YJCXB+0PyrgsHdtBuRACfBeTN+uM+suJPSEDbfh3/oxPoHgwiC3/06j8Eutj69sAQqj++I0CUfvIpwCEvYCT90O4Pn1XsT5Ve1/+dcp9FBh3woqXBSEJkvjHHEOUPqJPAjUUCeOMGfCJYPvOj9/t7//d2e7YmAlcS2B3A8xcPYcBm/7ULEDIQew+5gS0EIEA31R8Uf6gAoBsgKwBd9ddvBBJAs6XARgLQXQ2o7T8+IETe+9eRACg7rhCMVgCiE8D4O9wOCb2ubOht1/vYd2ubzLlgKbBHEDSnAMfL6durVm8qBPwXWz7rY/f7/X/fbsvL2+3Zqv4QAjzfw4COAMAJbEC3wC8koBJ9lAhgxZ+4hi3Oh/f8dU8EqtV/JhHgWn9cC4CJQZXZp6GAk/1nawMkrrcqAiwPIIA2FwOB2oaAF5UkcX+GADBs0I5gsNbBQqCorJcFJjqWKvhNMjky0Aek7/LZH7vf3/vO2215vruAD91uz/dSYCOAPQzYkoD7vw34sFIQw4LNymNSUKk8Wv0hCYhkoJ74Q6BboO9eDKoWAHXvBiCvAdPZf4nt3QqA924AbfXV8t8uN4Bt2We029WkoErWpSoCSm11TM8AOYA5uRS4RAITIQDDavaYHxCcm5exfM7H7vd3v2N9McDt9uxDD//WKsAG/ue32/M1DEACuO3g1jkBsf57fqCL/7UbIISAio85AAG0VQEYiIC9DJTYfy/+Dx8HlpeDRK8G90IBHQbgWgD2WT8LoOJ7NyeA5JEkAwwxmuqzur5X6y+sBEwDMggrqoBNH7c68Puk/fI9Vwfwvx4e6H724oEA1iSg5AAaAewlweeyLmAnAHQCTfU1CTAH4GyTMt+QDMRFQFEYQB71lXUAOjHYlvTqh4N2xe5yASoh2PpaJUGDBDrLr9cGIDlY1l+vDlQOAQHckYMiA68KMFsGtOy65RCGsMIDT+QqJoD3yUwCy/f+6P3+7koAt50AXrwigM0FrIuEoBrwHMMAUhmQUKAlAwHo7VmAPURo9h/r//ozLv1V7/5v6wGMV4B3rwYPXEBqIZAQwp4TYDE+LQlqtQfw6my/LgsyZaeLg7wVgmDnWQ5AA5ZWCDRx7ECzyn3udgFptFCIgTlyFRMEUCKgA+O/jl2Xz/3o/f7Otz88QvpszQOsLmAPARoBSDVgud02AthdwPZ5BSxUBVr8L3kAVHrvs076KSLQi3/M9QCJ7H/G/rf4n8X41XIgcwHecuBMDgAe+BHA6uQgqnvbF5DB5hwUQM3vQgIWkKOVftH+gAC6cz0RXZ9MjmD5fh/ZCWCd1CsB7CSwhgArAUgIIC5AQoDOCewJwab+CH79WR4C0mQAZT4hEQS9DgfEztNkoEECDfi6FAhZflb6Q1XXqwHDEECpvZX4a0qP1l7bfAS98cQfzQUo9a4mASMC0CsIm6JGK/2i/QkCuFK9PxmIYPm8nQDu795uy3K7LTvwVyJAB7ARwJoAVLkA7QIkJ9A5AQS95Ad2YmgvAJWwQFcBpB38pUuB9wVKbAWgCXwV86Mz2ICKTwUWFgOxMEBicr0eoBwCGBUADfxsDsAiA+zflNay31ZcfnAdAAXgDGkcdAcfZCJYfuCX3O9vf/vtthHAmgcQF7ATwOoAtn9IACsRSDkQ/wqIIUGoXYEQQ/sL5IDJP539776DwodVAGlr5QBgP8sDdApP3gSUXQa8/rZsRaBeHmy+HwDyCI1MUNlZzX9iJSBO9igJGJYCo4RdIqMfJQ4Ztq8C7FXjHuSnQ92XH/yvdwJ4Z68ErOXAlQRW0O9/JRG42v9GBHsuAImAqv+uzDo30C3yAfVHoHeg9xyAp/7wlp+WFCSWv1sOTBb+0EoAZP5DImBrApAUMFHolQG19c+EAkbpjyUEdQ6gm/QEsCzZFxKDlWNwprJVWfBm/1WAvWrcQ0ie7Lz80H91v7/9v263+9sPI2zrAZAEdvXvXMBKBJIIFDcgyUAEvHICg/o7wA/Bvyt35wCc2F9Cg03RvRyAA34N8hD0xsIfXP7bQgDMFSgyYO8GsF4N/hQ5ALak1yUGRQDZZJ5VWXgKEsie8yQuH63b8vn/8oEA3lsJYJ2EQgD73xX4z9bs/74gaHMBQgA7+DsXAJWBBniHCLTtNx2AUnkG/LYNiUCpvX7wp6sIOHF/lwgkNf8UGagwYMgLMBdgLQCyVgOyciCGCs5nz/Jr8EXOQOcQZEbrfjjTU8qaCBseMyx4vxPB8iP+RU8A24Kg9R8Qgaj/av8lDBgcwApQ+QdVgW0bKr3+jsk//AztzBKgtv4K+Kj08rl7JFgt9BnCAIsQcD2AsQAolQj0CAGAqhOFCK5u3cA+84dyIJLCPm6buAgoBa5qDoDF6wzUkZ13iSDKKwTamSKZSf29cuzJUwq7LV/wz18RwH2Nl9dKABLArv6bC5B/+9OBGxmsIIR1AQ3w2gk4RECTfwBulgC0rP96/FYJUOv9SzkAB/xuKTBY/qsTgZ0LILF/s/RW9v81ywEwhbeAwUIH6hRwGp+wEOhqoF49fojqQoPlR/+z+/3t77jd3n3rdru999CzEYAQAYJfXACEAqL8W5lQgA5uoJUK9zxBB3ii9ALiYT2AjvuN72wFILP+XdlP8gLKFeg6f5QM3AC+VlMMZ9ABGuN+VePHWL6tHVD23or3tQPo2iWfBRgShDp0ELcBjmIAbwTWqEzIJvLM6kEDEFcD9erxCzg3my4/9p/e7299x+323lu32+oAtjwAhgE7Cazqv7mAvRLQcgG7A9B5AAwHus87CWBYsIKFfe+eCSBgt2J+7QBQ+VsogOU/9fIPBvLhASEF8AHwlhPQ2wVYFhmo/Wby74QyYLcmQAEbbbue2FcnAb28QTmHQKBwNVCvHv8IESw//h/f7299pyIA7QIE/LsTeIbqL59hPUADvHIBG8jBIWgn0L4rsKMj2Noomz8QgZELsCoAAnh0Caj8lup7ib9tX+ZBoKgUmFkWTGJ8S/UHZa/kAHT+QGaeoeQmMUC/CoAzVYAjYDvSNwPCq8fPnINus/zEfwQE8O7tdt8dwGZjIQQQ9Y9cwAB+RQIC4I4MdvvdLL+O//E7LgLykn6q3Efjf6X8bOUfkoNYcQZ8z/KzBUBYCqT/YQgjBuOBHxPs7JHh7JoAy/IzWz+xEtBKBEYg8fIGw+SeQQQ+CzHZP+oWXWPU/8z9y0/+h/f729/5kAN4791X/6/cpl4SCsDfLRQwHEBLCmJFYH92vssNgBPo7D8qv4CekIHpAjKgx1iffGbKb5UAQwdguIAtz2KsEWj7vIQggNON91lYoIFN2mznYKj9UBmwQgXLLcDstRTdBchEFWAWcLP9MgC9cuzM8aXN8lP//v3+9v/uCUDyAM0FIBFADqAjAsgFiAvYwK3/MfAL8InSd/Yfy37Qpyv3OSTgxf8C5vZXPfF3aB2AA3hJGg5LghMOgCUBo8SgEAyC3Irvh5xAwhW0cT1iQBKYWds/QQLdeVUQcrEjeGoiWH7633sggHfWJOAaAkglYL/wLQyQf3tYsCp9CwmgFIgOgIJ/JwMdBuB3cQTDX4z9wR2whN+WE9idh67761p/F/8bpb8O/OotQCsJDhZfji0qT9p0LsCI83X9H8E9KH8iCSiTrQO29bwAAbvlCipPAw4T/oRKQAVElbaMJ472t7jnqnEjrlt+1t+539/6P4oAxLquawIkF7Bb/40M9hAAHcD2GVzABmBYKSgxfyMGAbROCipl1w6gs/8ZF0Cy/UIOOr7vHAIu9iHP/2v77yX9ROUt29+AHVUCnDJgtvSn8wXsnQGzIUAW3F27qFS4z2CrD07wCogqbR8LtGecUwR4vX/5OX/7FQFsOYC9FCiToBGAEAH83ZwA5AM06BspiPKrNQIt/kcg69iffBegNqVXb/wdQgIMC0DltUuQ+L+Bmz0OrNTdK/91+4JVf15SEPMCYRkwEfc3stBxurMS0AoTMKRocaV8cKw6jpcFsdUn2/8qRT8buGeP55HC8vP+5v3+1v99cADvvfNQBZB4dO24Kv5GAntSUOz/+n1wAis4wAnoMAC/N9svSUKsBABgmwPAbQTwWzsW/2vAI6j14h+1CEjnBYZFQWSxj+sEVFyPjgBBrhf+aOtPY39vRaBVJlQ2vyOGIATQsb6etBguDMSQyAF4IMhUAmZANNNnUNSqBDvtzzif6HSWL/wbuwN4eycA4gDEBQgRYPzfSGC3/BYBdOCHxKBHBAJoAbdWfIz1I9XXsf5g9y0yAJB7iUDPCaC6e2EA2ngMGyIHwAgBldncf4ID0EDXVp1NYmbnrclOtyfDhiPOoCO4CEXB/rOBfOZ4yy/8a7sDAALY1gKAfWMEgOovoNdk0IArKr+7gwH02gWQ2L4t/sEEoLL2IQnoFX96HYC4CIz/jcSgAJSVAtu2RPZ/SPRBHkC7AkYEqceC2fqBfdKaCcHAAeAkpKVBCANcElBVgBQRTC4HngHOTJ+rQo2jhEbP6xf/VU4AmBza7L+EAZgLgGSgxP8dGQDwmQOQbS2xp6oEWAnQn1seIEMCJO4fsv8Q2w/JQU0IJMvPiCCT/NPuQP/noJ0rAFBa23VSr1N/vQhIgxzzB9odMMIAkGvFZPF6JkyIlJeFFl6IcRYYX0ciOOOcll/6l+/3t/7fngPYy4BSCmyT0SGAlgvY4/+BAET10fZjUhAWCg2AV8nBEPQ6D6DJgSUAoQ/G+Dr+T9l/pfg0HxAs/e3WBUhbsihIgHKkHGiGCQHYO/UHomDgdd0BcRkZlYtyAFlgZNtlzqkSJcwc1xr/6FjLL/tLPQG8t+YA3tuXBKPiqISgAB//bjZdkoNE/Rs5EAIYXIAKCwYHYJADlvhalp8RgS4PogNwFN8jgo1A2LoALxRw1gA09TbCAjckQHBZlQEFwEoS0Iv1S3mAYFGPlwOIJn+0v+ocPohEsHzRX9gJYM0BvPvwTyoB2gGsP6iEAowANsBJWAAVgRYeAPCb/WdkAKEAttNJwRbzM+UPQI8K36k9Kf3RagBTe2vhj3o8uAFXLxUGxTdXBrK1AIltTZ2JzUe7Lp/Ralvxvrb5kcWP9nv2fwBzIRF4FRFkx/XcwRljHCGm5Vf++fv9re+63d4xCABVRhOAJoOtRCguQKoCmghwv7L/mBPQwB/KfMQhCEF0ym8RAUkIToUAxrP/gxOwSoDGmn9WCjTzASw3kHQA5poA7Q4g3n+MEMAChiadiopXwHZV26usvB43e/7Lr/pznADakmBdDcB8AFj+5ggcF4AhgAlwwyUM6m+pPgF8U3BS6jOdAAkJ3HUAO5C7ZKBT99/IVDsGhwyY3e8qNfhCERXDa5BrlW/ftaoqe265Ar0U+PIQQCUzqwqYBYfnSK4AcuW8sjmHaMzl1/zZnQDeud3eXRcCrfH/ngNYbyxzAKL8nQNAMiC5gI0gBNz42XIBAnAkBACwqDyWByPlp2BPWP7WD0Crs/5ewq+1JaBnWX8rEajbDiVAlbNpwHRyAJ4D6EqECQcQWfxo/0wI4E3wcPJnUbSLXqH5A26qHaD9kb7ssKaj+nV/ZiSALRG4rwhsJLBfUKt/k3yAJMGwEtCFBGD/PTIY4n6d8ANyaEk/Q/nPUv8h+WeRgXYCVgIwSwbK3osKi4PonEGUC2C2Pngc2LL73Xanlj9bBTg7BIgAFe2vuoxZS14B7wy/DCT8xX/qfn/rrYccwLtrElA7AJkgkrDSJUHJfO/Z/wZ4Kx8g4IXyYKfm0i9QfkoSJK5HghALr51Ce2Jwv0ad9BvAj1WCidKfZf1x3UDnvPQ90HYf7o1WfSQMGbOpU1D3H6oCynpjPE7VfSccpoalMEHNdAxFKkDLgDzTRo5ZaXukz1E34f1Gy2/8kzEB6MUlsjCoCwWMEAAdgOcGTECrnECn+JYTgPyABn0U82vwt7hfJft0rK9DAlHooTSolH94GxBUAnTSL/reAbz6UBADt344SDkIJBIT5E62HgnEAwgFmjq3ChFkAJUFd7Zd9fwsdZ89nnX85Tf/8Z0A1hwAOgDJAxBbuU1usboYCoiCKvWX+L/lAUDlNUG0bD8Bt7dviP9Vf0v9LbV3XQCz/3qbZf2d0h8D+JAPYDb/RAfArL1l92W7Z/OjEICpOZvkw7bES0EisET7M0RxRNkzx78qJGj37rf+MUUA+zoAnQjs1gTAhJNyFy4X7kBtkYHKB0ifDMgrLiADfJMESGa/Cwe0/a+CHsmA5QQ8N6ByAzJZh1IhEobOAegsvwaVDhEKDkCre0cielYbau4SQfIZggyIM0DMtMkc6ywnMHMsduzlt/+R+/2tt2+3d8QBiAtQSUBaEVDxPyYB22cEuiYDQgJtLUFk7539ke1vgAeAR05gC3ekbAclwuaEjEVA3XoAAnLpT6sBCuStrUrIpqsBHhkwcBOVTecFJAteCAFSyk/GzapwBOJofwV0mbEQkNX2p/X9HX9IEcB7eyLw3q8IlPgSbV/LBThEIMreQJkhAeYOIsDrsELV8VmIgHX9ITGo1L+BnxGB5wQY6IvKLzZZCKD7nsj8m+sADjoAVHk9ga19tF1CzSk5GO8T9MCUAdpZbSqEUW17lpNYfucfvN/fBgfwLlQBcEnwdkA9cdGiCjCgGrCpZhACDMSA6wL28dewgKl6GzuI963EXwtf1Nr/wQ0YMb+bCJwAPgKc5gPIPeiImeUC4B5J2zbZnGXBQjI4Mdk2HFNPYqv9MNlJCJByAzPPEezIiUAe7a8ANjPWGYpePc52Db/799/vb7/zKgQQAnhvDwH0cwFWLqBluwkRYJ7AqgoMTiHjApTqR9ZfbLxbCbCUX1wOKQGiO8ASn7XdKgMimL2SoG4nkxGVnqk+OoeBDHR4AN87EmCWnlULBGiBuiNJMFC5RJB8HsACRgYwZ7WpEEY2pNEuYOoYv/f37Q7g3dvtnT3+39YC6BBAv3IK1wVA9p8SAYC5gRDBqz53QDasvag/dQboGMCy0zBA7e/CgoTyszX/VeA35QeH1YGc2Hwr2YchGn5mJNGVd8FdoEOIHEBo9VkeQc3cqFJgEkPhxSBHwoIMCVTAlx1vlggq4y+/7/fe72+tDuDdV2XARgD7isDtd95BpZWjKRUov4Acwa6BT5OEsEjICg1aBUAl8DpwA2kgQeCYbHsjL0zygfKbll9XC5xk3zYGgM1yA0IKERGgI2PJQJ20M13CAQfgWv1kEjBj+Yc2zlqAGdWPgBPtrwI2O16FXMrn8Ad+z04AaxVgTwDiasAtBNgnrK4E6HBgSApichCBBHkBCnQNbmb1iTPoSEXlDXCfTv6x0EAA2OUDtCPA70bMT6sAXjVAlf4sIhieC8BYXy0CYk5gIPKCA8CJGzoAI5QYJqoRzx8NAZ6KCLLgzra7igSWP/i79hzA6gCAAMQFrBMNSUCrFypUm+x78k/cQRffY45AqatOGDJy0CDHkh5dDERielFhWvrTIYHO+icy/jK+qe6sCkCAH70erLsXylXMWv5GFowQrLyACISU6HZ0W+RALX0Qz2ug4NgYUWScRNQ+q6IZ8GbaVMCdHS99jX/4dwIBCAmsoNd5AHAB1sRDArByAV1YgLkBnfRDF6AtPbP4LNY32lkOgMX/tPynSKFzC466Y2JP+mT+mk8BOiVAVP2MA9COgH4nQGcgHxyCAe5uMicqARTcJ+QBIlB5+6O+V4E7c9wMCSx/9HfkCEDyAMPDJiQZ2AABqtZUVwG7s+ZWMlCDO/F9iPFZso9l/IkDaMRgxPqe4g8JQa30yg14pdaM7TddgWHxXcUPVgLqvnqyWw6AqrlT0jPV33AekYJb4IlAdfX+6LwR0BVi8Yhg+WO//X5/e68AyLMAawlwCAEwF2BkpTfgqwlu5QU6G45KrdYNsNi9qwAQMgjBnyEDI77XYGcxfjXut1wAhlfSptsGoNHJPab6XkLwTAeAk1MIidp+mJlRJYCqPxCABwizr0aUDl3I/ogEMsDMjJEZp0oYjECWP/HbSA4ACEDWAbA8gJ6MjADWbYP6i5LqvyRROBBABHgjXEAV14k963s7d0koOkm/s+J+FiaERADqbjkAHKNNrsRCoE7lmYsQ0HjlPm+dgMzKRLmQkkgyBJhR/SPWPwPyTJuriWD5U78FHMB7eyJQ5QDaYiBhXL0mgGWumRNQAO/KbieTASMOL8bvVgUSq2/lAvAaOvDiwiEjs6/BThdZ6bUBJNvfuQN0Z+pzVzI09nXqrT3UMRMAACAASURBVJcKg+J6xKAnLao7Tvruc6ZcyBS6EDpUXUIEvgyAz2oTnQuqe+aYzT386d98v69rALZ1AEIAazVgz/4zBzC8aorlAdS2rkIgC4e8v2TxkOsGMLeA45I6vgZ7ygFg4g8JQhOdl+FPZv+ZnRey0CQhE4PtH1TfCBmkXQd+S+1ZXkCTiQZq0gG4sb6qMHSAKFYQHpsIMoDMtKla/syYy5/9Tb0DWGP/7R8QgOUA2NtnzEw3LhRS6hjlA9CK6/gfS4XU5rOk427p9bg02cfATtS9CwGcSsB6/taTf9Zvx0ItvQ2JgH7WgEYyMMA+5AwmHMBMDsAjAhrPTz5M9H4mggy4M65g+XO/YSeAXf1lLYAsBca/24D7MwKdakBIYOUBxKYyJ0BDAeIOTOW2QI75AgVkXNVH7b+VBFTgDisAQda/gd5LrCrlZpa/WXJrEVBk+cGxNWAkqwDMQWiFNq2/zNKgDOi6A2NFICULRAV8rrSN7HgEzmh/NH4G2MZlDi8qXf78Fz8QgNj/thjIcADtvw9HNcgQwGxIwPIGLHTQVj8BfszWmzkAlZsQwFrlPbcCYOUCjBwKKwl6pUBRWyFhukxY7LmO7414X8f61BVY4YLY9iDBhy6BTX6LPJCoPHtcAXelbQRUD+gZEojGZyCvjrv8hV/fOwArBGBLgnFpcGdJYUJ0gNknxLDNCwm8xKEV6xtqPwt4DWpm92kIQICN7bSNF2Xv/pLfUgNd5wxoCEAA34GbqL0VAmhSuMIBuIqv8wGJRUQWmCzAfNIQwV/8tff7O+9BEhBKgEMiUIUAXjLQinMbAAAcCIruFWMVgBPFX28iLhW2Yvzu+JCo06A21wAQm69XRVJwk+RpaiEQCxeQKEDlaWhgtEWQWEqvt7vhwoQDKAFfjR+5hytdgjf20X1HLH/kIpa//GtUCLATgE4CogOQz628IwzslKx0gosuG1bWnuUGotJhyzUYYUIjBSsnoJKVXZnPCAeYo3EBH1UDDIA38CniiBR/CA1I1r5VEQBUg/1XVt8jjG7iWZUD5WEz5UIK8sRagIhYquQQgfqI/a/aeBYKZMOD5a/86r0MCGsApAqQcQDbgTQBMNuqJ70GE/nuOgMSGjDFj7ZZhNABnxBTIxon459Vfa9yYpUEEfRU5RXounEUkJEgGJlEYNb9O2IQ16hsO07y9nk2ETjzJKG4JIKUSlgQKqyDzgzQM22ic/AcxPLXflXSAew30no8eDsJvBGWyhmJsKojQOAOi3R0yRFtPcvuqxo/tf7qeryYv2T/mZqT0IARgfzmG9Eg6erP8Jvr+4Tk4Sk6IwnWfgA/IxsCPhmfKWuk3ugcqENIgLwC+hl1j4Ac7c+CPDNOd4/++q/ccwCRA1iFHkqAtBrA3ICh/J46Yp7AjM+DHIK27t1aA0YIbKGPIisrw59NAOqSH/0NEKyMCBS4qwnAtNpnk4JGnN8pfKYKoIgiA2R2DEYglW1XE8FZQI6AHu1vv8nf+BUPBNDKgFYOgDkAsHdmQhAnkhP74kNDg72OwgMP0CRuN90GW+CTdCwWoVluQKv3EAYQ1cZjuOpv9JXJNyT49KIgliMwlByVu7kJUFwvPBjcQuaxYSuUOBAGZMjGIxEP1BEQn3z/3/oi4gA0CQD4uxAACMBLCKLNjFSPJd3Q7rtJOWu1oZNcHMgmE+8H5T3P3Xj7OlCzCgEeN+sEVDs8Rpu4Ol9ggd1ScuYWkAQIsDv1lrYqB+BZ/2FfsBqQAe3sbZG6Xwn2aGzr3Ja//cuJA8CnAXfr314SajgBkwBwAs6EAwmwWWFChThY0s8iI297B3DDPYRtCLi3Psb2AdRAHrKvqb9BCEyNtaKXS4OkoqAnomXjKUEo9e/GSjqAs0HvAS8C5WzfaNwKES1/95cZDmAlAbIacPudIRcgi4H0oqBuUirgU6WDSVtJsHnJw8gtZNyGWeJLEJNn61vZzYjzo/3dQ0Ea1DgmUXMWAqTAbil9UOaLynttQj+iAzibCCLQRfstUM+ShJiqqP/y937p7gDuex5gBz5bByD23woDMA9ACeCAG8jkCLTis+8ZUhjCAisZOKvwySw/OoWONFWMrmv4ZsWAqX+wrXMGbLkwnMvgIowEIWuHTsV1CTKz978WeViA88IKDzRnA/Ts8TyCcUng7/+SngC2twFZJLBPljIB4IQ1wgA9waPM+rCfJApN9Tae1beOGZ1LO06CEKj7UbF9A7CVB7AShIa9R3Uf1gOwhF9V6S1iEEQFDqFN3my14IJEYNYRTANNERd+PZMMIsXXp7H8g198v68VgHf2uP9dBX5xAtvbgaUUqEqCg/1HKweAlx9vsLeGIlqxchWojCyqY1RCgXK5jxGHofIsD9B+V92nSAgIxCEkgLEGBU8mAaO4PgoVmEJbOQQG1CzIs+08Msg6kAwRzJBOlgiWf/SLRgewksCq8l0YAKBveQAgBGb/t4vDhJQmAwf4a9dQeZPWnJbiHMfgOYeNlAKlx3BFOxs3L6B+LySS8EUg6rzwuEgQ3luBGugDqx/lCzyCGPbtCBBi05M9Io2OFB4hEXgmGLMgzZDEjIvYruUf/0I7BGgkAJWAbY46SUArGThMyAIZVADH2ppEkiCBir2n5xmpu5ME1I5pUH+LYEnFICKEDpiFEADPSSu0JhQX/MphTBFBIYnI3MRjgLviLs48H9OR/JNf4IcAK9bxPwoV9TerAXgj4T0BOJk9MhAQDZOfACUCNgIy0zbTJpPZpyGAQwTiKug7AYkr0L+N991Vf00gpGyHINbK3yZVMQQwVT2xEMh1BEZ/Nvk1EKsKmgXyGeOeTQQdEf/TL3wggNX2b/H//jqwLRGo1gC0HMCeD9AlQPw+WDqZJEZIoCdaNY6OgOmFAVq5u7ae3Y9AHam7sd8kApUsZHaekclAvrv86eoBcwkZkFvrA1hf1wU4Cu4Btu1T/c8G/hWgrxDEmSFDc0D//OdDCEAqADoPIMnA7a8wrv6LpSEFfJlkoQtAdfKShEmAWlUDN7xgOYYE6DPuBY+Lv0W0HRXdK/cN2X6l0jqcsICubbx2AVeFAK7Sy+zV1YDiasAjgH6MvqZth+vXH6sksfyLn/eKAFaw6yoA5gEE9FYScDsZZfsR8CwhSJNb2Tq5UVLsQO0lE5Pk4bqRiBDU/oEcHFVn9X1T4dFZ6TKhYfWZcltqbm6HsZm6D07QKuGRcqQGgEUKSF5N2QySYPutbZkw4SmJwCIIJIXIYSz/8uf2BEDXAWAosN/w7gUhAHwhge7GY2wGBKFtf5oMGKgcl1Cx/wKwKKQY2hWB3oHbqver7ab6J8t/2L9VbaR6sM8auk4gArlRNbBchQnSaBw5RyV7lRCAgSYCerS/otRZwqiMmSECc7x/9XNUDkCvAyB5AAwDtrlBQgG8KegCOsvolQgrgPKcQKTQSReBhOCquBP3a8LTToXF/vpY8ls2J6AdBFH/rNJfov4YDoL6UzVP5gDc8MBJBFbBnwHrWW08EEcqrvhw+5oNBZZ//bMLBCDqb7kAcAJtUQeyOuQDcGIPnzFeJQClSbJqngBULW3xIzKpkBYe3wGxkISn/u5zASwccLbh5NHhht43ELsFcGeFXwfmA1UAdBsZ9YxU/ej+zDkwJ+RtO5Mkmhh9yc+637cKwJ79lxyAlP/kKcC1IqBzAJgL0K4AQwC0m7hgyAsBrAVEaL0HJU6SQKeiyT6dWictOwsTsqW+9ttosAax/pA3AKJBEqEhQLX+T+J2PG9GEIxEPPC6ag/SNzhOtm/fZo3JABYpfLT/KBFU+leUvxHNR37mSAAC/lYBUDkA76EgIYWOAHASKnXHm4/hwaB8pIxIV8oFFpxlziNws/0diSgF91bwuQQmE7QQ+2fUvwO+pf7KkXRA9db6W6QB1+KCHu1qMgTQE70DoTOG24/Y5qMuIEMOFYBXQ4FM++WjP2MnAFUClGTg5gCEAMhy4M4F7JNou/eZ0qBWELD7qO6D0uNkZXmEwKqb4HXI4wzAa8ejLTYSjb5mfXz8jgCvlP86YrhC/ZH4lfpSFU4SgAfMo88TZFxAlRgyY1aI4Iy2zQF87KfbBLCVAAP199YCaBJAV9AlnAxX0NqwnIBSrHSSziAPa/VeJt/ACMp0AY6l1+CNvofqb6h6NikoJMMUHN2apayZNt3YxRwAPa6Tb2iTXj4cVP2MwkdkUQFz5njsGt1tX/rTHghArwHY7P++DBhdwDanYCWgzgPIfh2TtfUB+6QcJhcBedfGUXoGwAaOyXhdKy4rC1rxPAtlymqfjP0x5h6ArVSdARJdiQa6BWC8t3h8RhQ616AnY+cEigRQdREWUZ1NDBnFz4I5Y+OroMf2y5f9VE4ACH50AS4B7OD28gDtxyEVgW6yOIQwWGlg/Uz8bQLXcBoa/AM56Dq8FcMbCTyx/o3ISF3fsvaMWPRv7JLEPht08nC4TyTDb5UNI1VnwO3coaHQFPBKxa0QwAO/G1LAucwA+2oHkDkny2Vs27/8pygCANUXF9D+h2CdC1CA334rcQf7Z7yxsp8qiFpBOKhPQAiW6jIlN9UdzllAKQBjdtxT9eF8HJLQ5xNae6Lska1nSu+pfyMjb3GOlxwEYrHANwA6sO/abdBxyRiPAf4ZoGf6WOA9y0Es/+YnAwHs4JfsP4v/JSEoTgD/is1veYFZEsB+xAp7gDEX0yRU2asQaHX2wD8QjEEsCDKt0pZqM2LpSqaiiNpteCW7mQSgukc4UTWxsH0Z8EaKT/erRGIW/E/pAo6AOdt35+Pxvwf/t0gA8BKQFfzZMiDmAYakoJ4oUB2gE4UtHDLiYQSa9bnsDEhJj4HfdBYHF/V4Vn8gvh3sh9Rfk60ot7c9Uf+Xc80AkDnCNGng+RrnzCa/RS6Z8zXBJDv0ORnf9bHY96Pbov7LV/ykMQfQrQMgVQABvP67//60BKgXA7UTU9Z/mDgk+TeAndjrBtpCBcEF9Wz23on7j1p9TW74mzaH4jgC/Vtri20uDdakzvIDbTL0y1I9Gx+V8CJHgNeTBfIMEXhjz5LDU5HB8pU/ccwByBOAXQ6AxP9sQVBL5EJGF8uByPYDCehJE1UGAuB7JKD3MadA22iFx9DCiPPpeZAFOZWyH46Jk2cDPiZFRX1IvI7XrMdg2fsOvCRsYGMM25QadgC8KAeQIg5BblAajOL26v5Z4DPrb6m95wKWf/cTxhwAPgJskQAu/aUhAIB5+22J9aelQa0uOuFFQoRBCY2Soc4PNBDBMQVAGJ50amqVI8kYOH4F3FTZsyU9EvuLMs4q/NBP3SNT1Y2FPQyQcs0RYYT7JxYTZQgiAmoE/Ki/8E80DgO+RQYe8Nvx/v2P3wng9updALgAyEoEYrY/ejS4katyBegG2OfOEqpSX7s4K0QohgVUpSft+5VgR7BFsb/nEkxScByD/s31pB2IIOMSIETRE9YLF0wiOGMtwcUu4EoyyIAe79uyEsDwIhAsBSrrT6sAuyJ0i4KU6p9CAkpl9boBNuHT7iCw9vThJBJfe8erKrt2IZZjoWSIcTkLCTwVt6oC6nojwLKYvuoWIsUf1DsZRljn7m3PAPcMBY/GqIK8YU/IHTYs/+HHKQLYAd+tBCQkMIQA7L0AQAxo8bbjI1MXPiOIqMJNOgIEly4HmvsUIaUA7oQ0tD/LuBsAzTqC7XosUnAy/MwBZADtKTl1fjhB2aT19j9RCHAGOWTGyII/Gyos//HHAgEo5c8kAbv4X6m+lRDEmy73EtViSEA5pcFOIVTSMHIEAgTLVuvVceXVeFWwO3F+ByIW5zuxv1ZRRqL6d2TK64E1Y/9dIiDWfVB3veqPEcEThAARcDNgPKtNdC6Dw/lPP+Z+fxcWAOHbgM2FQKDsQ/wP+7TSo+qzsiAqk1apLmGoVUor4kTpcCCDALzZen1EQpbNp+QEjgNdiZWxN8t4pCKQUXeLOChZOFacEoFxTmzsYRIjEZwQAnjjRwCL7Hu0PxofLnVc1IM7gzxGE96vWgkAHwUWF8AWAuGDQOyhIAQ/KwPu+9t5KmVvJwXtMHSgE9BQfU0g7oMy2g4byb9ZMFtkwUCMhNDtJ2VDDVoNLBoSEBLpQBYB18kPpElkv9HM1XRzwFB85gzw2BaArX4uoRRAFYG7up+RQYYgKm5i+aof/RACiPK39wAAEbB3ArSq3v4Bl//qpcAa8Nt3QhAM7N0FE7DTSWc4goEUAAwm8Ky1CNYCG69syWr/BJBWLkArvWflL1H/iDwE2I6dH0hKJkeyYtCRFYCThSdZYLuEwo6hCGwGlE9FBsNx//OP2gkAwwBJBBoVgK4SsE8KyQWwuJ8RAoIdCQJvpMXqVnlQA3z4TpRdjsHA1IEo6hss7JFzQQDQYwaE0AHAUmMrSWgAmJKomuRH7D8DmOVWGMAjgHb7T8oBeORR2XcFOcyMyfps2776C/ocwPr7df8rkEMC23xS/0uQLgVm3IBOAHYni1ldneHVcSMJKdbJEYYOQU7BDR+M8VMZeQZUY1tHVNYxlQJnQgJNKNbk9tzGAFovx0CWDXurDkPF1+MVcgBZhzDbbgaoVWdQsftNaIHcNwLQIYCQgCh9SwaC2jfgQ/lPg92qAnQnokIB6gCUcrlVAqNsZqqco+xMtTM2/FTwVxyBofAsvGGgNe25UxqskgxV+ETIkCaCAgFEzkLmqdXuqZ1ARBam6gMAl6/5kSoEUPYfwa/fBNSeBQBi2MZW7wRox8skBgnYTUfgKLeA11O4KDk3gJ0pWzI00BOYxuhOeU9fhwXWqdg/Io7MfuJKKNhBfRrAJisAFJgH1wF4oPYAF4HxyP6oLwN6xhls/f7Lj7jf5dHf9hdeBNoRgJH5L4UB+2TSpBDmBADsCG5U9izYq+Sg25uKqqsJhnJ64JdrcC13Mfan14tAdDL76MhM0qmOFdh2fRxGJBZQoycKI7BkQZ5tFx0v2h+BPw30BrhXH7bweCOA/eWf+kUgFvjxKcChGqAAbuYADCLQ4N5O14j9I/DjftcGe1UDpn7Ogh2LhCrHfyzw098Hwews/aVkkMzkD8qd7JciggNJQItUjoC0CuAjxMLOMzz3r/3h4ADgLcDM+ktOwKwC4HJg9ZmV/RoXWaGBUv1TiYABO8ofWLHwRDLPBd8JCn8quLMWPeMkiPozK5/dNpBCkAPIgnwWiLP9QqAqBc8of6rN1/3wh4VA8gRg9AxARwI7iFgJUCcAKwlBFg50lQIdDoCbMC1rpYKQrBygW+kUMcjkR+CsxvHus/sReCPQRvsR0A74rPCBnXtK6ZVTsdzgYwK+ovaVthE5zCi/8MnydZ+vQgC1AIiFARveINHnJQMbNlHlAbDbiTj7NBmUiYCoNqsiDBNUT+YjoHaSh3Lz3BDBcivedkaSjvqa8X2ypBe+QEQBVl9vBHrmCCi4H7EKcJban00GFcJYvv6H9UlA+i4AXAuAZT/1WWf/LdXv8G6VAQkxlMHPMsJFJ3CJylugstTaU2FPdT3wZpQ9UZ4LiYvU/TswJ1xDRsWZ88v0a0oIFjtDNt7YEQCPEEc0dnX/AwGQ2P9oDkDCAvld9XdP9dEV4I3tbpaenMZ3V2lIn0yCSlv0wyTh1Nkz9p6ppxVGoFU2VV/UOqn+6NKiMbtzdQgmcgRv1P/hJlXdw/C7/dcfajsAifeFDESU27MB+wa5jzoUaOB3LD4SA4v9NVF4LgAnd3ehgeozAHugHianEx6wCR+FG2YeA294whVQYtjvWQRUMw9BlDIkG7b6j4VmVrusOp9s/y0ncJX6R+POAD4kiI0A4L8BQ+Uf3gfg2H/2MBBTfdP+C7vAzdaPAFfIwLSERHVoIoqUBjNKm3EDGVIwx8kAOFLuaL86hkkkxcU/jDgrSh8CUhG9B6iMzc+0iUB7xO6H4EWszLqBb/ghJARgTwKytwI7OYAhBHBcQDYckOtlTmFYABIA3XILbCEJ3QaE1ampsRItHTbsF+mqqpUryCzZzYA/QzJJN+ICPLFqLwPCI/F/aXy5N4YjiRT6akB7BGmd2/INP/ghBGjJPwL+1QnIfGf2X8CuQ4GGEZXoO9UFEOdwhAxYDiCtXE79ngKh2t7LFWTAHwAbSTEKEby2kaqznEHUJ6XmCUJJjaPUdFbFK4CvtI2IprJ/+caVAHQSkD0ObL0MxCgJbnNNqb7+XlX+KATYLlwdky4NZVaRxY/ZcMGLZwNHkCaXCPwZ1bbOBZXNyS0wkJruSKmll1w9CsrHdACzZOBdYwWwYj7CcAhcijf+8o0/KHYAkgzs/u4Trqm+/g7gKYUDRNG7F4jKhTlAbz+SbgNjdz+g0S5yA0wFO5AQAnHVzwOoZ/vPAn8yMeclKSMlPwOspm1nhO2oeRZEM+0qgH8q9d/O8ZtWAig4AMGQuRDIWQ48JAUBkO3eRcDWuQSi+pETQOBSdpxQ/kjJI7IYljkrVXaBlajpZxbqeGrOQEDzGqA8OoywfvdqHP5+IICznEKFSDJOYhjvm35g0QEkFwIh2Bm4w3AgcAJ6MrV5R+y9BpcmCFQl+oOz8MByE0qNu/EK4UDkJBihWHF7Bvz4m5jAJct+I8Wn+6+I1a8YE0k4+OwBtaLwlbYZwIfjrQQwrP4jK/82+6+2y8q/IQmolR2SiNvvqFUc3x/A9jOwESfAgB6BnxGJFR6E9tWbhJ499ey9FUbIhDT6ejadAjwKMbSVtkgxY7kvAOuZjwFn1fvq0CACeAhucGPycejzzT9gdABYERheCLqDUQhh+0qeC2iYNcBvWf4wMWgQhE7+CdHoC04TAlFy0zkY6+41udAJkyANar8JKVIHEBFEspYfOZLIxofkmSEOr82B+H9WvWcIoALaStuILNj+bdtKAF4JUKu+uQpQx/5AFKj6NBwQeiLOYCCxKEegCELb++GHcCoCA2taYHXU0IrtXTJhjsd5kKcDpziDBEEgQZkkg+MBWVigiYjA/T3gZofjGI4kC+azwTszXgTaqwlgHX/5ls97tRRYVL2tADRCgUH1yYKgDofE4nc4VqDG/EGbE0ZiziMIF/yGYlCHYJEKKzviJLaOEWTbQ5CQpN9AAhcoP5JWGaBA8lmyKYHZI+FgldwMeLNhgncNlX0RWczufyAAWQqcjP2tCgACV+Z+t0RYAUmIpAOxEdtHTmDbTybBsHaAnIMmiuHmatcBk9m8iexcEgrqVgP2c6cxvFL+LMii2HkYJ5Er8H6TaeL4ANj/CKSPofiIowcH8P23COBGnwHQhOBVALxHg1l4kCED0mbIEVjqTIhk+4GT26dJIXAF0yGBQR4U6MR5ZNsNTkIRS0mVsa8ir+o4LnF4ZKvPYXKV3xWK/1o4gG/9/ioJKC8E9dyAAXaM75sDANDp+N8LA7p3CyjF1Y5B3xxKEsZ6AVo5SIDYZHMvGRUlqqLseLCSbzunpBVGMsy6hTA0icAWXf9sIjC45irZyPzKuJUjIH4KxR8cwLd+v50A1PMAmOzTnwXTYvkld7Bth5uM+9uBo3yAodKR8uP4HUEQ5dFtGYEM25QCDwQQqVAEzAgcQdx/JvipC4jICX50Cpxk/wzoorCkAsrM8WbHM0WCEGXU9qr9y0oAWwiglH8LCYz1/w3wqvznqr5BDhqsUwuEqg5BkUwHdgOI2yGsx02tHIHcaGd/pMQIbArMRF7hCGAwFMqAxWwTEdys+sO9zJzfjBuoKPVVba8lgGISsFsApElivyE45wdXADdNhwUdlkm8nnYCCeWXY+l439tecgvG5OxuZqSMjnPoJnwWYJETYUoenWOkaBP9M2C2yDML8my72fg/Am2FLKKxZvZvfb7t+77KAWxOwEj8NXUHp7DNb3QBCvwSAnSCq0MAQhiitugOcCzcbsX71qrAri9OXEY21nMGHUu9GnG4oQVncMg2Z8FPSDEFNMcVHemf6ssIidw3a6wsyM9oVwXhUQLwznkQMVIKbQRAV/45RKDJoAHcIQMhiwjUQwjQscer3hYh0BWBxhhCNCzej/ZZx9FuIsolHLbMFUWfAXIUviAY2ecKOUVjMTIoXH8EmAwhRSA/Cuoj/c255pHot33uQw6A5QFku5cLQGAjMSDmLCcw4BImixUaCDCZkntuwGtPCcABCx6nHBJkVDg7qSuvwEoAcQDIBPi9MTIAKyt59rcKyGWWHCr9IvJ4kv2NAII8gIC1Wwqs1wUAoi0yEABrx82UP+sGziCFDsgkHLDyBN1N80gjqCLg+CkQJOPqdn4BUOhEniENVJtE/2x8TduRa/IAmT1WBMSzxomO8yj7P/65r1YCotIPn0m8j28BFpVvwGdkoCRf2/gOd1k3MNgImIEEyBZZYEKJugVrHYEoi3EsTSzu5HEIZCCFyuQPnMIl4If7kgVMtt0hUkOCMj5XgVex7VM2XU3IlEAQxyPDdP0//n3GlYAh+FWs370OXBbbqWSfblNxAlbbsuUPyMLLBeA9YLafTZruB8+AO2vps+32650Flqem4b4T1d881oyreWICqJLL1e2XjQDkjUDkmX+d5WffEVeWE0CBNJU/qfq6f0eQBdVv/Qw1tdyCBWzGsDJGqBIZgiCAzjqK0kQ6A1hnjOGBNUEwIUmd5AAqxyndB0PFw7nkOAY9R5ePf+9XSUBGBAJudAVt234Ttn37xi4ESGyTE0rnAIBtBqwfAD/+Zl68r8nGdA3RykEsy2TtfJYkKsfWk+wM4GavJwnA2fj/CDCPgqzSPwoLov1HSOUVAeBKwGgtgJH80+AfbL8OC9A66Od0gFy0UiuCa+Sjt0cKboYQRGmHsR0w4vmGE0GRltk+AapuIlTbG9dcDh8mxpkCauL6wt/eUcojfY8AUiv0Wd+tc3ogAA/8xsKfDuykTVP2/YO1GlCLNnUCiii0Cpu7LUfgjUf2WTG/JgXLORwFtbkE2VLQRNKPTgiHjNKASBw7PZZ2J0Vnc+Q4ugsk6gAAG0BJREFUVVKKQH/muZxKCp/4Xv3DQGLn0fI3sEerAPVTghAaaFyllgcDi1Asq43t6yzwI2IIKgHiOFKWjZyjZ3XZBMuAOJqYbTJVwwuDfIb/l8FR2cy5VX6Ts0HmZdunz90i7eClJZnjZdoMv1EjAMcFbLiYAT+x8TpX0DCeAHPXxAA5XTug7YiW7on9NPYPwgLtEEKiSNjcTg2y4YSehCeBv+xUZid98ne5khCmwHaQDGeOGfVZVgKwqgAiiBH4U2XAfTCco1qxNcAZxiOAm+J/kSvwEoYU4Anl325ath0hr5BYNPDYq9Sr4LzY+reJfBZZVa/vhPYRGGf2Z/p4bZZPfM++CmCFAF4YIETR/upnApw3AqUJAQ4ShQPD/ovA3wjdANDwwxvKZbVjN45uSwI427eqnIywpsbIKOT7iAAy4Ix+p5kxMn2kzSsCCKoA+AiwJoOOAJTtF8vPSAK3NSFLhAJdPwLuTKiwHc8jhsx+1YaGBSRxJdeadQgWETBVTJNG0mVEE3TbXww9yg6lmPzL/gapawNSitpXgIdcF40783tlzmUd94EAEiVAuc8m+HWOoCH61fxAy19R/mplAElHicqrryeD3wM1fVkpm1gBkOgxHEV0gZA4VnpiFlQ5MzHNNoXjpM+9APBozKuI59BvpgAwJgE/B0KA6CWgrP7vZP4bWcBJZJYEI1FYQuzlAtw8gTFg2jXs12I+diz7gQA9tu/2GaRkOQvrfYapiZgNR6znyMn1zQCkpG7GOZfG0PenQAAZIM6cS2bcq9osnxAC0C6AgH14+Ie9EIQQwoY5FRo0HAbbKY5In3Yf2QtHEGVWiGEAVhHow1cHPHgeJnAZqAIll3GrSUdKBkdyBmQF41WTsxv3LMK6mAAe5bdwSKt6/AcCMEIAmevrbz88A7Dv1CofVQQ66w9ftAJrMdSuAHD46ucIiEGDeRDcKCwgB43KgZYa47l4biIav0QyybjfOufhWGcRiQHK7nivKQFUATcQ+Ylgnhl7+cT3sEOARgDO038dATjZ/w74AKTM9q05AScjBY8YEHRVy4/Kr4mEKZXbRnaSa/IAvR3HISk3CZkkr3AMOPeM3c2SiTtWAfyzgDyz3+xYZ/6e6XPoCMBZ9tuAboB8cALKIbT5x54H2CeVBrkGOHUFHjFQNlBJ6wnVZ+AWgogA3Fg6cVymuJ1zME/kYQdT0CwgXTUpEFdmUodtCgQQjrVf2NXtMuNn2lTu18x4rxyACgO8sp+n+ts+A+Rs+a+0Z1jFfXS/ASLLGQxjJEAYlgpn1FwdN0UazloDD6wR4aQVH4GTPP+ZCUkn/MmhxtWgsu7H7O9x5fkun/hsFQKw5B+AGsGfjfc9UrDIYjukmmjatlv4taoAFduvyccFWYJIvOSdFvIo7s8Avps0ScBaE606VoVUdFvL9byO4Inc2PvhnEcC2CfL+mf7p+P//ar1dgTsEA7AmJ1gFrZ36k36tXEjV8CshFwT3tEsqBPt2rDQNqX68GNl2kfEUQGmpcQR+VSOkQJIQf2vUMorxkxdd1R+hbl6aLzmAMhCnuEZAKPmrxW+EYAFcGtpsLM9dATgUrSiMvLQbSruYArQCaKIAJxyCjgxnGN6hGLuyy55npicFuEcJZSjAD7aPwvOK46TGfPBAej4nz3959T8B8VXYMR5aK4HIACOLD8DLZvzlp2nZiAB1G1+J9pVbD8jrdR6Awts5PymQL+Pf6j6EBCCNVHN/7iV/lgq6XkWCcn1k2NmwX2UxLLHyQBeLkPGXD7x3cccQGbdP1P9UPmt5CAAqiMLOVvD8re2XkjggHXASALUWfAzl4BzKLT0wblk+kdt0vuNc6lMbBPkhtU9tMpRgfUogGaApfmi8lsdPd9S/44ASLyPQEelZwlATQqIPU/56ctB1MtEGI61slP1NybvU4LfELBXmxMZfzZGxnGkQY8HgB9rxkVM9XkK0imqfYUYqgRYAnHBEelxXzkAJwcg4EOFz9p+5hSasBPlZuGCMgIPIkwmiN50RjWg+22zDsFxHRnwR21cEKtzjADvTUx0OzMgjsY2VbEI/iq4ps+L3JiKslfPszJ2pS2exwMBZHMA+8Re709HAGxxELTtnACgWZNIa5ew/APY9c0xngno+qlBXHxfDP7tBlaOwSZjsn+GFLZJciAMOUQYRQI4dKxHBvWVJDAz9vKJz4rXAYjidiHA/sPRtQDWE4LGOwIt1e+2KxvgEsD7DPyotNPqXwQNO84ApIkxI3IJwXryMcPjnUAAVeCd1f6MaxsJgNX9WXjgKbzlCIwyX7vn3jJhpZCUAGBjRBCKTzjukoraOlfbp04iooTk04mFic4I6QiwvQkvp+XlL44cewYkZwF0uDZ1D2Ztu76VR8ZZPv5ZDxpOwwDr+X9P4ZV9b66B2HodRmgXnHEGrc8Tgz98B4GF4wJp0Bud7B+BqDu9fcxMn6hNaT+5llL/IsnNkMNMn9eZUDYC0M/5I2jXzxqowzaw9l1bZzsCl1p9I1zQJCHkhffeVH+HJBgA9HwysZYE4TA/Z/sZziECi+clPAXOKg62y5xLFHJMjZFU2ciVnA30GRJ4jD7Lxz/zVQ5AwFVa/rt3osAv5gIQ3A+25OFuenbefV6AlBLZeBb4U/hMNSLQC8gonPyzx7Xq7gapyObwfKJx4SfIOJmzjveYQM78VlW7PktU2eseCSCI9wegW5Y/SQwakDpksPYLM1juofVTQHFxE71NKGkJQmyGDTyt9qsFGeCYo8N5ZcfJtnMnsvo9smNm2mWBUHU50bFnjvvYY67H6wiAvvLLyQPgk3xWqKCFRZSdAbdti5KBilws8YrcAd70cgxfJYtAYQPI97uPEog62DbxCmNGE7UKJjx2duwz2kVjXLl/hiAihzEz5isCCFYByhzRCj0A37H92xjE1neuwtmP/V1nQBYKWfMbQ40MCKvtD5EMO6ErgBqMGQGBnWa6z37sdPujoUYUipy4f9a+R0A/c9zl277bXgXYRQABjsDUIK0Anym7DiW0m2CCaS0ZHsggafuzYO6GSwCQNkn0CwnojDESYUwFjDjcTL9osVHZTTwigCMgvu77txCAEkCy7s9IAcHI3IIGNoJwIAV0ppmwYD+4xgn9HoCpAuIQl0aDsF9nH0J6KDWo2v5DKk86zxy/QjCZtq9Tm+hcrtq/EUCn9M4LQIYwYL+x5mpABUgK8H0jgmH47IC/U38Sl1fBnwV+GryzuYILwd+GTl5ENPmyzNONkzx2xg7PklP2ujLtHqtNdJxov3YljQBEibW1t7Y34CVW/Wngt3vv9MXxB4sPd5w5CBY+6PESTvihCUzU7JzF68uCwzrnSnKudCx1MZmJUxo/itWTP+bMeWX7PEW7s46ZGSdq00IA+uYfou4DkEG9vX2W7Weqz8gBccjcAQNPRfnNuUjcCQPB6a7BZIMqBI32SfBVjhZNtm6sxPFL48HglX5XtM2OeWa7zFhWm+VbP6NPAgrYXOX3VH8fwFT9qEqg+rvq76izRxQZfEVlQXcOJ4nDBdgZY6TZKoZ6ZpLFo4iq8JZHj1Htf1X7K8bNjDnTZiCAyPLPxvs4LnUEiaW/HaifCPyReEXEkSGfM22/nO82OaKTTyP4QMOLQo/M5NdnfXWf6viZ9pk263Vm2m0hwOoAUK3NxUCBsrvEkFH9YI1AN3+zFYHki0M6UBog8bCDYcth0SUHOgW3pwxyAPiJ9wvMjp6Z7Gzsx+pXPU62/RntGgFYyt/IQVnS9au3DwHL6vc6RIjWASDIBntvOMvsSkAPwBZuuu0HQBuNUwUFPd+LwZ+diFc4kPSxyQ/52H2rx6u0z7bV7ZZvkRyAEddr694BP3IFmXyAE/NHlt8iAv2fjXju1wJ/Cvhq4AzOzDZO58y4mXxClUxObX/4IvqzyU547xqOjnGkf7VvpX2p7bd8eCIJKIpLXAFTfq322jl0feCOee00qC2HYIHfUt408GFgb26n5v0JawVmiOVUgHuDpX6E+GwqEzseLRcnXz3OzDVV+3jtl5UAEKAIOhO40WO+mZifOA5KBEG7DuCJhUADIcDkZPPUJIQDil21/dP4KXYsNs9g46HNgYGrkz1/UucRwHrMo+c527/abwwBdgLoSIAou1bjSNU98jD/81Ct/t7/IyAuRPocAH9F9be2pEM0x+l+tTEag03u11H55Zy2yTZzURUUH2xbBVDmcEfGfOy+yzfrEMBaCrzfTAbsiBwyYcGg/oSEAOu9sKi2oe2fUP3WJQnacN4XbH84lp6VB9xJZoKn25RPPD3yaQ2PAC5zEkfHP9I/03cjAAbgAegHFv9YBMEsPyqsPgcNbNaWgb+bh4QsNLHgjWV9Q4IxZoZFIubxghmWcRWZSVrgj/xwb8Df/VYZMEY/7hVjPBAAgIIqvKHGkfJ3Y0UEsl99+L4AaQcoxLmm593Z4Gfz2pvrw76kg5giBXIiV+EwHDdsEE336/efAaiZszzzuEfHWr7508k7ARXIEMjMGZhKnnkpKGnDxhu2ESWfAX8K0Jn/ZwBmgjn3E7Y/i5uIWDITM3uszFgdYV01cPVEgvZHwXP0dK46fmXc5Zs+nZcBN8BFqn10v7H8V5NMZ7kTVYHBoicBTMkgqaqhC3AaRHiJ9m8TccJZeBM4dUw2wIHrjABVmdjkJ2nDV8eJzuus/VeelzX2RgCDwnuLghxV74CbedQ3Uy5MvBQkUn53P7odreIJUFnzvdueGKdq+b3xLwF2NqE/zRxnweiDNc6VpLD+Uo0AGnjBWg92f6dVur2yNFhA59h4nEfb5+T6fw2MCPxU9ZV8mG3UXKNzn1yjnqIRZtz9RXIpinaIplkiCgd+08D9Bc4ihuUbMQRQkzXrDBAv4UNBcllR+IDK/Ejgb5MZZnVEIJ7V9J4M9EAdEUI7ZqZhVrkzZJawFslTegPvR/gFMiSxEYBW2PX7oPIROWTe+JsIHzoygS/6fDTwjiq/Bv8s8BmJAOfR2x6BxnMW1dDBIyxrTkbnt/VzGqX6PwIgjhxCX0MGXEeO9xh912t4IIAo5nfAj2o0kAaqeDLb341hHNcDf/QEoAvsI8lCA4nW5D/iAE5558ABxR/O/SDCD3a/DCuZ83q/E8HyDZ/mVAF2pCEoKcizdj5DJEIaVfAnlgJXwT/lApxS3wzoM2DLTNSK8mfHE+UvtS/A9apxM6fwlMeW81vJ5WrnsREAA/W2LQHsVMyfGKez/gr8Q1ignEXm8V8PzFXXYIHJUmY2mWbIwPq/EvWEzkzeTJuQNMgg2XEzIJwJb6rjHgp7zjrYI43D3MryX8EBWHZ+VvUtEmGAbseAGUSPWwT/2apvglntOAv0bRwDWRnAXdYmM/BkEvKpgZm8tEeC7nWH6QhgRvVdkColt9rKcT1ioC4gsP0V8LttjUnMwFkBvjXJhu2EFGcBEk3saL8cN5uHmD3PaMpnzzMax9v/GMc4cn5n9N0IANXXBWnmPQCi0Enwb8AO2mbAXwFw1fJXiKQBxLg7FYJAR8aGiyboZfvVwNFxMhN1ZoyZPplzie5hZYzXve3y9RICEBAOZJAEdQnQxpiuG3DWBWA//RnJhu5TdyskFTIDKwBPtU2qfwQGb3/Ut/utEo0TTUxczPSd6ZMF5pVjZ88hanfkHDcCiAC7HSAqFQJthi4icAlU8YMyImPtAcAOmLBtCHzCHikwR6GEvtMnVxQY6ZFD2vMt8TDTjFN5yj5Xgisa29t/BNSV4y5f/6nj04ADABNZfI8kqJor5XcVPwF+D7RybimSgF/PHDNQ5YhAPCC2vkl3EYF6VvlpP7VxZpJW+lTasntbAYLVduYcKse9evzoXJav+9RX6wBkMnUKfgH4U+VFDcTkcmANCAR/SBIF8M+CPOUUCDnijZwB9UyfDlSJmZpo0s3HTPtMm7McRMkNRcgK9s9e18HDDt03AugArx7qMfftQ0XKP+MmvD4U4HguhDi8PpV9mfUGTJFToJdrMGaGNWHO2u46iYCQjgAwC4RsuyxRZoA0c8xo3CvGjI7p3dvla4kD2Dqom06JIOsOEs8A4A9jOZCzwV9yBKpxBtSZNt01JY5h3cwzicA7p84VZGZech1AFhjZdjPneYTIop+iet7ReGed60YAFuBc9T8R/IPiF2N+Rh6RWtM+xEmIw/EmlEckacA6KnsGuL0JaO5LJv2ykztqF+2fBXV23LNApcc5cnyPCM4Yd/kv6ACyoM62q7wSTD+BaDiQlAuYLBNSIBeAGRGBSQbkTlZAf0bb4dySbqQ62TOTNtPGDVkIarJjnkkCR45Z/V1nHMPa5xUBwEQ/TfnhF3DHJC8TYa7gKPhLqg8Hi4Bd3W9ZbDZhzgB3ZYx2bs7szUzsqM3R/Y/pBqJzPZM0HgP4eD0bAaTi/WxeoBDvD6SQIAzG/K1bslJgEUF3o48+XUhi32EiFev8WYKYAjzOPBCDSFkicHj7o75Zlc+MQy4vurS2vzp+9ryvtveZ81i+5lPGMiBT3zRJ7J3Tig9UHvVxHYC6SxmQm22csVwC2q8lcgTbGGRWHQF4tq83KbYxjNkegWAW6NG4mUk84wYyx50Zt3K+FgFUzu2o+9gIIALeVeBHuxmdQxb8VeAP48IAEZCn9zvHsCZQFuDZdvQ4CeWPJudTE0F0fjNOoDLmEQKoHmfmWjRhLF8dOQA1KVygFpKDrwP4B7IwgDkNdOYIDJBlgXt2O7wPenJEE3IG7DN9qhM9Ou8rx5slgMo5zzoT5hY2AjBBfTL48cfZhs6+OhzOvANtArBpR5AA5mEiIHc5GjPrCLLEcIXyW5O3uj07sTNgybTJgjU7Vna8KtEebe/1X/6z5QAmwT+AnL1g9CD4hTzcsMAiDba9mPCLQEv3G2RlTfoMoDNtvEnZ+quBZlR6Buwzx7lCvTMAz7SZIYDsuFlyZCrvnddGAIMDCMDfgbxCFIkKgUcg2q6m1X3/VWj7yTUD7Ec1iSHhLrJEcAT0dLIVKxHRRKwSQQSAq/dH15PdX2030z76LRj4oz7LV2kHQJRqIAgB1GOD31DRChF0bR3lM8GcKO91fYvuwmJr73y8yeQSRlL5zwL1rOJHk/jo/oxyR8e4GtDZ41fPoyeAQhKvVBk4Q/kD8FdIYLvhCTLxQozIAWzDBwCLQB3tj87BnQwTyl8hgkrbzKSNAHD1/gxJZNtkrhfVPLo2rfyV9hsBlMH8RMpfBjn8MpbyZ8asEEEbT/1GFZWOgB/tD13EBcpfBfwVbiCa+FfvrwA7OpfKWLNksZ7D8p8+lFwI9AS2H1U0A1Rp47YlwLTaTwF/7xSB9Oj+I+pfeX15SCYGyWYm5etGAhlQPmabqxwFjrsRgAaO+f0k5ccTcI+dBGuaHJLjReByCSNQ16PAj/qHgIUBKqrN2h7tH6ncFQQRgSoCeLQ/Gj+65gxxasufPSZrt/zHrAN4jcCfBjyG4RPPCZQdgAOuCLgeqUSEFIIeZt0VQD46pjeBryCBCMRX788CNjqPCplYx9wIIHQAB8GfVvwT3gNAgTQBflflme0l7qJCIDMgzwCvtQmcSZpECi82rTiECBTVsWbHi/pl9kdtzgT20bGW/xA5gNcc/K4bOAh8D8DdD3/kPygplhVLoL9Q+TPnESlUFdTV9rPOIgLw0f1HQRv9rjpE8I63EYDpAF5D8LuAP2j5o7GpSkMn/UNXvlfaZtxCa3Oh8lcAWWk7C9yzjpEFmAes2X3ZY2dIKNNm+feWA3hC8FeASNuS9QxZNbeOTfur38i6edkxI2BnVFc7kyPWPnO8yvhntI0m9WOSwBGQRy7g6P4skWwEMDiASfDjzTFdxX5m3f4CYCNyyCzwicZIkQUBv6fiFYWvtDVB9cjKnyWLqrqfBehZsM4CcbZfFrjR+BFRynGWf6cdwCT4GahSJBCAPwJrtx++6GOnQK3icVO5T3p+oAL0qG13fYScvImVAW/p+CoIzYxfPb8qkUSAuIIgZseMzjWzP9NmPb+NABpYXgPwlwAPE02vZjwT8BHJsMn7ZG6AzLoMAM9qU7H5Z6j7GWNkVLd6nCwAFVe2r5HCn7V/+crVAVSeAUALbyjhrPJ7LsIC9NaHKN4lDsBQVtMpOI7CIyg2ebxjzKr/DOgzfSok8NhtI2CeCfQjID3SN7pG3L985cvEOgAE/ZFXfSceCio7AMO1uIShriflFhySqQL2DMKgx0yofwbAnnupALYCpsx5PUaY8H4ILSoAjxzG8hUvi88C7Ee3VB5PjrZJuA02BgVp4EBSwM7E/cn1BBVV90A2tQ86RQCOCCuz/ygRZAF/lETOBLSnypXz9Igssy8igIp7WP7tTgAhcCfVuyOBE8DfLq4A/shVuERhAGsKpBeFBNH/gmRNqogoov2PRQJHj/MYJDBDDkeAPHs8fcxGAJaiVwHMwLZtS4Df7Kst+8HKgQX44fj7hizYz24XKbH8rmjzItAe3R+dU9WmZ53AB5UEZoE8228ggH+TdQAFADMgpQhGAZ0SAlHkSOGj/VZ4MRNCZPvMtuv6JQgqA9gqKWTBmAV3tl32uGcpvgWy6vZZpT8L5CgQlAA85a2qtwZ6RflDB5AEfwT4aL+21Fb7LIhn+kfAzfzHIhVgR22j8zmq/BVQZc61SgKV41fH9n6bWXI4q9/y5SoJiAMfBb9Xm7ccwXB8cQVE7QayIW8groI0s5KwOmYEHm9Cm/suUP+MEp/V5oiaV8B6VdsZEphR9Jk+FXLYCMAE0oTtb2OpCZoBq+kAjLFMsgDP4x33TOsfugohMnJuEUEM56lmRaSIV+/PnP8RwGfHrxzjyrZnksPlBPBlRhlwxrpnwW8CnWXJC0RymBCS5b4zwV5Wf+hwBNhH+lqW9rHdwVF1P9r/dQZ6ljiWlQC0SjIbPLRRilYFv0cC7Yc9WOrLAFWf94y9n+ljnZurdie8YnzquMS9PAUJHAVshqCs63oMsFeuzzvPaB8eZ/lS7QCU4jJVNckgUGurH1XuiVJfilSYFTdUtUIgR0nA67/tU7OjouBll2GEKVnQZ4EWXUPFps8es3KM15EEskoPt3T7KP02AojUO0UCk+CnoCWAzII7Au2w3yG8o6COzoUBioKCnKPrFBjJqRlQcQLVY2WJIjNuBaCvIwlUVX0G0NVjdATwMXEAAYBdEnhC8Ecgc/efGPNH5xFNdhOQRdt/ptpHCh3tj675CFE8JTFUjv2UriFz7GUlgOp/DNKRwUHwdxPfUeMjDoCCq5BfOOoEZvpr2x+BLavolXEyAM6obnTMzHEqoMuc09HxKv2rbTPAVYZO/ydUbXfkKP4/BnecprBuissAAAAASUVORK5CYII=";
  69764. return TextureTools;
  69765. }());
  69766. BABYLON.TextureTools = TextureTools;
  69767. })(BABYLON || (BABYLON = {}));
  69768. //# sourceMappingURL=babylon.textureTools.js.map
  69769. var BABYLON;
  69770. (function (BABYLON) {
  69771. var FramingBehavior = (function () {
  69772. function FramingBehavior() {
  69773. this._mode = FramingBehavior.FitFrustumSidesMode;
  69774. this._radiusScale = 1.0;
  69775. this._positionScale = 0.5;
  69776. this._defaultElevation = 0.3;
  69777. this._elevationReturnTime = 1500;
  69778. this._elevationReturnWaitTime = 1000;
  69779. this._zoomStopsAnimation = false;
  69780. this._framingTime = 1500;
  69781. this._isPointerDown = false;
  69782. this._lastFrameTime = null;
  69783. this._lastInteractionTime = -Infinity;
  69784. // Framing control
  69785. this._animatables = new Array();
  69786. this._betaIsAnimating = false;
  69787. this._lastFrameRadius = 0;
  69788. }
  69789. Object.defineProperty(FramingBehavior.prototype, "name", {
  69790. get: function () {
  69791. return "Framing";
  69792. },
  69793. enumerable: true,
  69794. configurable: true
  69795. });
  69796. Object.defineProperty(FramingBehavior.prototype, "mode", {
  69797. /**
  69798. * Gets current mode used by the behavior.
  69799. */
  69800. get: function () {
  69801. return this._mode;
  69802. },
  69803. /**
  69804. * Sets the current mode used by the behavior
  69805. */
  69806. set: function (mode) {
  69807. this._mode = mode;
  69808. },
  69809. enumerable: true,
  69810. configurable: true
  69811. });
  69812. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  69813. /**
  69814. * Gets the scale applied to the radius
  69815. */
  69816. get: function () {
  69817. return this._radiusScale;
  69818. },
  69819. /**
  69820. * Sets the scale applied to the radius (1 by default)
  69821. */
  69822. set: function (radius) {
  69823. this._radiusScale = radius;
  69824. },
  69825. enumerable: true,
  69826. configurable: true
  69827. });
  69828. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  69829. /**
  69830. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69831. */
  69832. get: function () {
  69833. return this._positionScale;
  69834. },
  69835. /**
  69836. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  69837. */
  69838. set: function (scale) {
  69839. this._positionScale = scale;
  69840. },
  69841. enumerable: true,
  69842. configurable: true
  69843. });
  69844. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  69845. /**
  69846. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69847. * behaviour is triggered, in radians.
  69848. */
  69849. get: function () {
  69850. return this._defaultElevation;
  69851. },
  69852. /**
  69853. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  69854. * behaviour is triggered, in radians.
  69855. */
  69856. set: function (elevation) {
  69857. this._defaultElevation = elevation;
  69858. },
  69859. enumerable: true,
  69860. configurable: true
  69861. });
  69862. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  69863. /**
  69864. * Gets the time (in milliseconds) taken to return to the default beta position.
  69865. * Negative value indicates camera should not return to default.
  69866. */
  69867. get: function () {
  69868. return this._elevationReturnTime;
  69869. },
  69870. /**
  69871. * Sets the time (in milliseconds) taken to return to the default beta position.
  69872. * Negative value indicates camera should not return to default.
  69873. */
  69874. set: function (speed) {
  69875. this._elevationReturnTime = speed;
  69876. },
  69877. enumerable: true,
  69878. configurable: true
  69879. });
  69880. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  69881. /**
  69882. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69883. */
  69884. get: function () {
  69885. return this._elevationReturnWaitTime;
  69886. },
  69887. /**
  69888. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  69889. */
  69890. set: function (time) {
  69891. this._elevationReturnWaitTime = time;
  69892. },
  69893. enumerable: true,
  69894. configurable: true
  69895. });
  69896. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  69897. /**
  69898. * Gets the flag that indicates if user zooming should stop animation.
  69899. */
  69900. get: function () {
  69901. return this._zoomStopsAnimation;
  69902. },
  69903. /**
  69904. * Sets the flag that indicates if user zooming should stop animation.
  69905. */
  69906. set: function (flag) {
  69907. this._zoomStopsAnimation = flag;
  69908. },
  69909. enumerable: true,
  69910. configurable: true
  69911. });
  69912. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  69913. /**
  69914. * Gets the transition time when framing the mesh, in milliseconds
  69915. */
  69916. get: function () {
  69917. return this._framingTime;
  69918. },
  69919. /**
  69920. * Sets the transition time when framing the mesh, in milliseconds
  69921. */
  69922. set: function (time) {
  69923. this._framingTime = time;
  69924. },
  69925. enumerable: true,
  69926. configurable: true
  69927. });
  69928. FramingBehavior.prototype.attach = function (camera) {
  69929. var _this = this;
  69930. this._attachedCamera = camera;
  69931. var scene = this._attachedCamera.getScene();
  69932. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  69933. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  69934. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69935. _this._isPointerDown = true;
  69936. return;
  69937. }
  69938. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  69939. _this._isPointerDown = false;
  69940. }
  69941. });
  69942. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  69943. if (mesh) {
  69944. _this.zoomOnMesh(mesh);
  69945. }
  69946. });
  69947. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  69948. // Stop the animation if there is user interaction and the animation should stop for this interaction
  69949. _this._applyUserInteraction();
  69950. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  69951. // back to the default position after a given timeout
  69952. _this._maintainCameraAboveGround();
  69953. });
  69954. };
  69955. FramingBehavior.prototype.detach = function () {
  69956. var scene = this._attachedCamera.getScene();
  69957. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  69958. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  69959. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  69960. this._attachedCamera = null;
  69961. };
  69962. /**
  69963. * Targets the given mesh and updates zoom level accordingly.
  69964. * @param mesh The mesh to target.
  69965. * @param radius Optional. If a cached radius position already exists, overrides default.
  69966. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  69967. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  69968. */
  69969. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ) {
  69970. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  69971. mesh.computeWorldMatrix(true);
  69972. var boundingBox = mesh.getBoundingInfo().boundingBox;
  69973. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ);
  69974. };
  69975. /**
  69976. * Targets the given mesh and updates zoom level accordingly.
  69977. * @param mesh The mesh to target.
  69978. * @param radius Optional. If a cached radius position already exists, overrides default.
  69979. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  69980. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  69981. */
  69982. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ) {
  69983. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  69984. var zoomTarget;
  69985. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  69986. var bottom = minimumWorld.y;
  69987. var top = maximumWorld.y;
  69988. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  69989. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  69990. if (focusOnOriginXZ) {
  69991. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  69992. }
  69993. else {
  69994. var centerWorld = minimumWorld.add(radiusWorld);
  69995. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  69996. }
  69997. if (!this._vectorTransition) {
  69998. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  69999. }
  70000. this._betaIsAnimating = true;
  70001. this._animatables.push(BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime));
  70002. // sets the radius and lower radius bounds
  70003. // Small delta ensures camera is not always at lower zoom limit.
  70004. var delta = 0.1;
  70005. var radius = 0;
  70006. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  70007. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70008. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  70009. radius = position;
  70010. }
  70011. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70012. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  70013. if (this._attachedCamera.lowerRadiusLimit === null) {
  70014. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  70015. }
  70016. }
  70017. // transition to new radius
  70018. if (!this._radiusTransition) {
  70019. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70020. }
  70021. this._animatables.push(BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime));
  70022. };
  70023. /**
  70024. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  70025. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  70026. * frustum width.
  70027. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  70028. * to fully enclose the mesh in the viewing frustum.
  70029. */
  70030. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  70031. var size = maximumWorld.subtract(minimumWorld);
  70032. var boxVectorGlobalDiagonal = size.length();
  70033. var frustumSlope = this._getFrustumSlope();
  70034. // Formula for setting distance
  70035. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  70036. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  70037. // Horizon distance
  70038. var radius = radiusWithoutFraming * this._radiusScale;
  70039. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  70040. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  70041. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  70042. var camera = this._attachedCamera;
  70043. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  70044. // Don't exceed the requested limit
  70045. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  70046. }
  70047. // Don't exceed the upper radius limit
  70048. if (camera.upperRadiusLimit) {
  70049. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  70050. }
  70051. return distance;
  70052. };
  70053. /**
  70054. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  70055. * is automatically returned to its default position (expected to be above ground plane).
  70056. */
  70057. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  70058. var _this = this;
  70059. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  70060. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  70061. var limitBeta = Math.PI * 0.5;
  70062. // Bring the camera back up if below the ground plane
  70063. if (!this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  70064. this._betaIsAnimating = true;
  70065. //Transition to new position
  70066. this.stopAllAnimations();
  70067. if (!this._betaTransition) {
  70068. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  70069. }
  70070. this._animatables.push(BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  70071. _this._clearAnimationLocks();
  70072. _this.stopAllAnimations();
  70073. }));
  70074. }
  70075. };
  70076. /**
  70077. * Returns the frustum slope based on the canvas ratio and camera FOV
  70078. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  70079. */
  70080. FramingBehavior.prototype._getFrustumSlope = function () {
  70081. // Calculate the viewport ratio
  70082. // Aspect Ratio is Height/Width.
  70083. var camera = this._attachedCamera;
  70084. var engine = camera.getScene().getEngine();
  70085. var aspectRatio = engine.getAspectRatio(camera);
  70086. // Camera FOV is the vertical field of view (top-bottom) in radians.
  70087. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  70088. var frustumSlopeY = Math.tan(camera.fov / 2);
  70089. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  70090. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  70091. // along the forward vector.
  70092. var frustumSlopeX = frustumSlopeY * aspectRatio;
  70093. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  70094. };
  70095. /**
  70096. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  70097. */
  70098. FramingBehavior.prototype._clearAnimationLocks = function () {
  70099. this._betaIsAnimating = false;
  70100. };
  70101. /**
  70102. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70103. */
  70104. FramingBehavior.prototype._applyUserInteraction = function () {
  70105. if (this.isUserIsMoving) {
  70106. this._lastInteractionTime = BABYLON.Tools.Now;
  70107. this.stopAllAnimations();
  70108. this._clearAnimationLocks();
  70109. }
  70110. };
  70111. /**
  70112. * Stops and removes all animations that have been applied to the camera
  70113. */
  70114. FramingBehavior.prototype.stopAllAnimations = function () {
  70115. this._attachedCamera.animations = [];
  70116. while (this._animatables.length) {
  70117. if (this._animatables[0]) {
  70118. this._animatables[0].onAnimationEnd = null;
  70119. this._animatables[0].stop();
  70120. }
  70121. this._animatables.shift();
  70122. }
  70123. };
  70124. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  70125. /**
  70126. * Gets a value indicating if the user is moving the camera
  70127. */
  70128. get: function () {
  70129. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70130. this._attachedCamera.inertialBetaOffset !== 0 ||
  70131. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70132. this._attachedCamera.inertialPanningX !== 0 ||
  70133. this._attachedCamera.inertialPanningY !== 0 ||
  70134. this._isPointerDown;
  70135. },
  70136. enumerable: true,
  70137. configurable: true
  70138. });
  70139. /**
  70140. * The easing function used by animations
  70141. */
  70142. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  70143. /**
  70144. * The easing mode used by animations
  70145. */
  70146. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  70147. // Statics
  70148. /**
  70149. * The camera can move all the way towards the mesh.
  70150. */
  70151. FramingBehavior.IgnoreBoundsSizeMode = 0;
  70152. /**
  70153. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  70154. */
  70155. FramingBehavior.FitFrustumSidesMode = 1;
  70156. return FramingBehavior;
  70157. }());
  70158. BABYLON.FramingBehavior = FramingBehavior;
  70159. })(BABYLON || (BABYLON = {}));
  70160. //# sourceMappingURL=babylon.framingBehavior.js.map
  70161. var BABYLON;
  70162. (function (BABYLON) {
  70163. /**
  70164. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  70165. */
  70166. var BouncingBehavior = (function () {
  70167. function BouncingBehavior() {
  70168. /**
  70169. * The duration of the animation, in milliseconds
  70170. */
  70171. this.transitionDuration = 450;
  70172. /**
  70173. * Length of the distance animated by the transition when lower radius is reached
  70174. */
  70175. this.lowerRadiusTransitionRange = 2;
  70176. /**
  70177. * Length of the distance animated by the transition when upper radius is reached
  70178. */
  70179. this.upperRadiusTransitionRange = -2;
  70180. this._autoTransitionRange = false;
  70181. // Animations
  70182. this._radiusIsAnimating = false;
  70183. this._radiusBounceTransition = null;
  70184. this._animatables = new Array();
  70185. }
  70186. Object.defineProperty(BouncingBehavior.prototype, "name", {
  70187. get: function () {
  70188. return "Bouncing";
  70189. },
  70190. enumerable: true,
  70191. configurable: true
  70192. });
  70193. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  70194. /**
  70195. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70196. */
  70197. get: function () {
  70198. return this._autoTransitionRange;
  70199. },
  70200. /**
  70201. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  70202. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  70203. */
  70204. set: function (value) {
  70205. var _this = this;
  70206. if (this._autoTransitionRange === value) {
  70207. return;
  70208. }
  70209. this._autoTransitionRange = value;
  70210. var camera = this._attachedCamera;
  70211. if (value) {
  70212. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  70213. if (!mesh) {
  70214. return;
  70215. }
  70216. mesh.computeWorldMatrix(true);
  70217. var diagonal = mesh.getBoundingInfo().diagonalLength;
  70218. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  70219. _this.upperRadiusTransitionRange = diagonal * 0.05;
  70220. });
  70221. }
  70222. else if (this._onMeshTargetChangedObserver) {
  70223. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70224. }
  70225. },
  70226. enumerable: true,
  70227. configurable: true
  70228. });
  70229. BouncingBehavior.prototype.attach = function (camera) {
  70230. var _this = this;
  70231. this._attachedCamera = camera;
  70232. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70233. // Add the bounce animation to the lower radius limit
  70234. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  70235. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  70236. }
  70237. // Add the bounce animation to the upper radius limit
  70238. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  70239. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  70240. }
  70241. });
  70242. };
  70243. BouncingBehavior.prototype.detach = function () {
  70244. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70245. if (this._onMeshTargetChangedObserver) {
  70246. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  70247. }
  70248. this._attachedCamera = null;
  70249. };
  70250. /**
  70251. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  70252. * @param radiusLimit The limit to check against.
  70253. * @return Bool to indicate if at limit.
  70254. */
  70255. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  70256. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  70257. return true;
  70258. }
  70259. return false;
  70260. };
  70261. /**
  70262. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  70263. * @param radiusDelta The delta by which to animate to. Can be negative.
  70264. */
  70265. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  70266. var _this = this;
  70267. if (!this._radiusBounceTransition) {
  70268. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  70269. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  70270. }
  70271. // Prevent zoom until bounce has completed
  70272. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  70273. this._attachedCamera.wheelPrecision = Infinity;
  70274. this._attachedCamera.inertialRadiusOffset = 0;
  70275. // Animate to the radius limit
  70276. this.stopAllAnimations();
  70277. this._radiusIsAnimating = true;
  70278. this._animatables.push(BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); }));
  70279. };
  70280. /**
  70281. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  70282. */
  70283. BouncingBehavior.prototype._clearAnimationLocks = function () {
  70284. this._radiusIsAnimating = false;
  70285. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  70286. };
  70287. /**
  70288. * Stops and removes all animations that have been applied to the camera
  70289. */
  70290. BouncingBehavior.prototype.stopAllAnimations = function () {
  70291. this._attachedCamera.animations = [];
  70292. while (this._animatables.length) {
  70293. this._animatables[0].onAnimationEnd = null;
  70294. this._animatables[0].stop();
  70295. this._animatables.shift();
  70296. }
  70297. };
  70298. /**
  70299. * The easing function used by animations
  70300. */
  70301. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  70302. /**
  70303. * The easing mode used by animations
  70304. */
  70305. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  70306. return BouncingBehavior;
  70307. }());
  70308. BABYLON.BouncingBehavior = BouncingBehavior;
  70309. })(BABYLON || (BABYLON = {}));
  70310. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  70311. var BABYLON;
  70312. (function (BABYLON) {
  70313. var AutoRotationBehavior = (function () {
  70314. function AutoRotationBehavior() {
  70315. this._zoomStopsAnimation = false;
  70316. this._idleRotationSpeed = 0.05;
  70317. this._idleRotationWaitTime = 2000;
  70318. this._idleRotationSpinupTime = 2000;
  70319. this._isPointerDown = false;
  70320. this._lastFrameTime = null;
  70321. this._lastInteractionTime = -Infinity;
  70322. this._cameraRotationSpeed = 0;
  70323. this._lastFrameRadius = 0;
  70324. }
  70325. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  70326. get: function () {
  70327. return "AutoRotation";
  70328. },
  70329. enumerable: true,
  70330. configurable: true
  70331. });
  70332. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  70333. /**
  70334. * Gets the flag that indicates if user zooming should stop animation.
  70335. */
  70336. get: function () {
  70337. return this._zoomStopsAnimation;
  70338. },
  70339. /**
  70340. * Sets the flag that indicates if user zooming should stop animation.
  70341. */
  70342. set: function (flag) {
  70343. this._zoomStopsAnimation = flag;
  70344. },
  70345. enumerable: true,
  70346. configurable: true
  70347. });
  70348. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  70349. /**
  70350. * Gets the default speed at which the camera rotates around the model.
  70351. */
  70352. get: function () {
  70353. return this._idleRotationSpeed;
  70354. },
  70355. /**
  70356. * Sets the default speed at which the camera rotates around the model.
  70357. */
  70358. set: function (speed) {
  70359. this._idleRotationSpeed = speed;
  70360. },
  70361. enumerable: true,
  70362. configurable: true
  70363. });
  70364. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  70365. /**
  70366. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  70367. */
  70368. get: function () {
  70369. return this._idleRotationWaitTime;
  70370. },
  70371. /**
  70372. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  70373. */
  70374. set: function (time) {
  70375. this._idleRotationWaitTime = time;
  70376. },
  70377. enumerable: true,
  70378. configurable: true
  70379. });
  70380. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  70381. /**
  70382. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70383. */
  70384. get: function () {
  70385. return this._idleRotationSpinupTime;
  70386. },
  70387. /**
  70388. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  70389. */
  70390. set: function (time) {
  70391. this._idleRotationSpinupTime = time;
  70392. },
  70393. enumerable: true,
  70394. configurable: true
  70395. });
  70396. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  70397. /**
  70398. * Gets a value indicating if the camera is currently rotating because of this behavior
  70399. */
  70400. get: function () {
  70401. return Math.abs(this._cameraRotationSpeed) > 0;
  70402. },
  70403. enumerable: true,
  70404. configurable: true
  70405. });
  70406. AutoRotationBehavior.prototype.attach = function (camera) {
  70407. var _this = this;
  70408. this._attachedCamera = camera;
  70409. var scene = this._attachedCamera.getScene();
  70410. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  70411. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70412. _this._isPointerDown = true;
  70413. return;
  70414. }
  70415. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  70416. _this._isPointerDown = false;
  70417. }
  70418. });
  70419. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  70420. var now = BABYLON.Tools.Now;
  70421. var dt = 0;
  70422. if (_this._lastFrameTime != null) {
  70423. dt = now - _this._lastFrameTime;
  70424. }
  70425. _this._lastFrameTime = now;
  70426. // Stop the animation if there is user interaction and the animation should stop for this interaction
  70427. _this._applyUserInteraction();
  70428. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  70429. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  70430. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  70431. // Step camera rotation by rotation speed
  70432. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  70433. });
  70434. };
  70435. AutoRotationBehavior.prototype.detach = function () {
  70436. var scene = this._attachedCamera.getScene();
  70437. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  70438. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  70439. this._attachedCamera = null;
  70440. };
  70441. /**
  70442. * Returns true if user is scrolling.
  70443. * @return true if user is scrolling.
  70444. */
  70445. AutoRotationBehavior.prototype._userIsZooming = function () {
  70446. return this._attachedCamera.inertialRadiusOffset !== 0;
  70447. };
  70448. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  70449. var zoomHasHitLimit = false;
  70450. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  70451. zoomHasHitLimit = true;
  70452. }
  70453. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  70454. this._lastFrameRadius = this._attachedCamera.radius;
  70455. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  70456. };
  70457. /**
  70458. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  70459. */
  70460. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  70461. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  70462. this._lastInteractionTime = BABYLON.Tools.Now;
  70463. }
  70464. };
  70465. // Tools
  70466. AutoRotationBehavior.prototype._userIsMoving = function () {
  70467. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  70468. this._attachedCamera.inertialBetaOffset !== 0 ||
  70469. this._attachedCamera.inertialRadiusOffset !== 0 ||
  70470. this._attachedCamera.inertialPanningX !== 0 ||
  70471. this._attachedCamera.inertialPanningY !== 0 ||
  70472. this._isPointerDown;
  70473. };
  70474. return AutoRotationBehavior;
  70475. }());
  70476. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  70477. })(BABYLON || (BABYLON = {}));
  70478. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  70479. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\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>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\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#if defined(OPACITY) && OPACITYDIRECTUV == 0\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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\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) && SPECULARDIRECTUV == 0\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#if defined(BUMP) && BUMPDIRECTUV == 0\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<bumpVertex>\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}","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\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;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\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=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\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#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\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\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\ngl_FragColor=color;\n}","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nvNormalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,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 MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \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#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \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#if defined(OPACITY) && OPACITYDIRECTUV == 0 \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#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \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) && REFLECTIVITYDIRECTUV == 0 \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#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \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<bumpVertex>\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}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD)\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;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && !defined(USESPHERICALINFRAGMENT)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nfloat comp=sign(dot(normalW,faceNormal));\nnormalW*=-comp;\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\nfloat opacity0=opacityPerceptual*opacityPerceptual;\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<=ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n\n#ifdef REFRACTION\nvec3 environmentRefraction=vec3(0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\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#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD).rgb;\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec3 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords).rgb;\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords).rgb,\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords).rgb,\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec3 environmentRadiance=vec3(0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD).rgb;\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec3 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords).rgb;\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords).rgb,\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords).rgb,\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && !defined(USESPHERICALINFRAGMENT)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance*=vReflectionInfos.x;\nenvironmentRadiance*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(reflectionCoords,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction*=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=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction;\nfinalRefraction*=refractance;\n#endif\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n\n\n\nvec4 finalColor=vec4(finalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\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\nvFogDistance=viewPos;\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}","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}","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}","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\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}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\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>\nvec4 worldPos=finalWorld*vec4(position,1.0);\ngl_Position=viewProjection*worldPos;\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\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}","shadowMapPixelShader":"#ifndef FLOAT\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#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec2 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.y*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\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}","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}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\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\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\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}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\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","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=abs(texture(textureSampler,vUV).r);\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,1.0);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\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","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}","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}","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","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(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(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\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(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\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()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\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#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}","geometryVertexShader":"#version 300 es\nprecision highp float;\nprecision highp int;\n#include<bones300Declaration>\n#include<instances300Declaration>\nin vec3 position;\nin vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nout vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nin vec2 uv;\n#endif\n#ifdef UV2\nin vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nout vec3 vNormalV;\nout vec4 vViewPos;\n#ifdef POSITION\nout vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\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}","geometryPixelShader":"#version 300 es\nprecision highp float;\nprecision highp int;\nin vec3 vNormalV;\nin vec4 vViewPos;\n#ifdef POSITION\nin vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nin vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nlayout(location=0) out vec4 color0;\nlayout(location=1) out vec4 color1;\n#ifdef POSITION\nlayout(location=2) out vec4 color2;\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ncolor0=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\ncolor1=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ncolor2=vec4(vPosition,1.0);\n#endif\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}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\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}","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}","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 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\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","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,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(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,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}","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}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\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}\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\nvoid main(void)\n{\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\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}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","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}","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}","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,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\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}","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}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\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","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}","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}","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}"};
  70480. 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","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\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","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 normalW=normalize(vec3(finalWorld*vec4(normalUpdated,0.0)));\nvec3 tangentW=normalize(vec3(finalWorld*vec4(tangentUpdated.xyz,0.0)));\nvec3 bitangentW=cross(normalW,tangentW)*tangentUpdated.w;\nvTBN=mat3(tangentW,bitangentW,normalW);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 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}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{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#ifdef NDOTL\nfloat ndl;\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));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=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;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\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","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\nuniform sampler2D shadowSampler{X};\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\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_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vNormalReoderParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\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\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPCFCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\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\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPCF(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\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\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#endif\n","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","reflectionFunction":"vec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_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;\n#ifdef REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED\nreturn vec3(1.0-s,t,0);\n#else\nreturn vec3(s,t,0);\n#endif\n#endif\n#ifdef REFLECTIONMAP_EQUIRECTANGULAR\nvec3 cameraToVertex=normalize(worldPos.xyz-vEyePosition.xyz);\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.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\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}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\nuniform sampler2D txColorTransform;\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#ifdef COLORGRADING\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\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#ifdef USERIGHTHANDEDSYSTEM\nbinormal=-binormal;\n#endif\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(binormal,binormal)));\nreturn mat3(tangent*invmax,binormal*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap.x=vNormalReoderParams.x+vNormalReoderParams.y*map.x;\nmap.y=vNormalReoderParams.z+vNormalReoderParams.w*map.y;\nmap=map*255./127.-128./127.;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\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","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\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 vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\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(TBN,vBumpUV+uvOffset);\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X})\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else\n#ifdef SHADOWESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#else \n#ifdef SHADOWPCF{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPCFCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPCF(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#endif\n#endif\n#else\nshadow=1.;\n#endif\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif 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","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec4 vNormalReoderParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\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;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec4 vNormalReoderParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\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/(PI*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 reflectance0,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); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\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 fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\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{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 reflection,vec3 normal) {\n\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflection.z*=-1.0;\n#endif\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\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.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\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>=cosHalfAngle)\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 reflectance0,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=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*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 reflectance0,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+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor*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 reflectance0,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=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","kernelBlurFragment":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*KERNEL_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*KERNEL_WEIGHT{X};\n#endif","kernelBlurFragment2":"#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*KERNEL_DEP_WEIGHT{X};\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*KERNEL_DEP_WEIGHT{X};\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};"};
  70481. if (((typeof window != "undefined" && window.module) || (typeof module != "undefined")) && typeof module.exports != "undefined") {
  70482. module.exports = BABYLON;
  70483. };